pax_global_header00006660000000000000000000000064117563115540014522gustar00rootroot0000000000000052 comment=dd73b7d12b6bc5f4f4d08c2ac7dcfc5f00f6fd29 open-iscsi-2.0.873/000077500000000000000000000000001175631155400137545ustar00rootroot00000000000000open-iscsi-2.0.873/.gitignore000066400000000000000000000000041175631155400157360ustar00rootroot00000000000000*.o open-iscsi-2.0.873/COPYING000066400000000000000000000431311175631155400150110ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. open-iscsi-2.0.873/Changelog000066400000000000000000000150111175631155400155640ustar00rootroot00000000000000open-iscsi-2.0-872 - open-iscsi-2.0.873 Ales Kozumplik (1): fwparam_sysfs: fix pathname manipulation error in fwparam_sysfs_boot_info. Eddie Wai (3): ISCSID: Fixed a race condition in the INVALID_HOST path ISCSID: Fixed iface update for the new iface net config params ISCSIADM: Included the new iface net params to the node creation Hannes Reinecke (6): iscsid sends SIGTERM to PID 0 iscsid: Implement --no-pid-file Keep startup mode in sync when specified in config file Allow LOCK_DIR to be set via CFLAGS Allow 'onboot' as loginall parameter boot.suse: Update with latest fixes Jim Ramsay (12): Add specific session information to session_rec_t Add support for multiple sessions per iface to iscsid Add multiple sessions per iface commandline syntax Add new node.session.nr_sessions config parameter Implement leading-login support Fix dcb_app.c compile error with old kernels Check all ifaces during discovery even if some timeout iscsid: In foreground mode, treat SIGINT like SIGTERM Revise bind_conn_to_iface logic iscsi tools: Fix warnings reported by gcc-4.5.2 fwparam_ibft: Fix warnings reported by gcc-4.5.2 open-isns: Fix warnings reported by gcc-4.5.2 Karen Xie (1): open-iscsi: add transport cxgb4i Lalit Chandivade (2): iscsiadm: add netconfig support iscsi tools: manage qla4xxx iscsi sessions with iscsiadm Manish Rangankar (1): iscsid: Fixed iscsid restart issue for offload iSCSI login Mark Rustad (7): Add some consts to char * parameters that are not changed Add dcb_app.h for DCB support Add dcb_app.c for DCB support Add initial DCB support iscsid: Fix netdev check Remove redundant initialization iscsid: Add IEEE DCB support Mike Christie (86): iscsid: remove bogus debug log msg in isns_disc_new_portals isns: Fix endless loop when pollhup is returned iscsi tools: fix multi pdu sendtargets discovery sequences iscsi boot: fix iscsi_boot sysfs parsing Use pass through interface for sendtargets (take4) Currenly offload cards like bnx2i, be2iscsi, cxgb3i must use a normal eth for discovery. This patch allows us to do discovery using the iscsi class passthrough interface. Add userspace/tools iscsi error code defs iscsi tools: fix iscsiadm exit codes iscsid: modify data drop iscsi doc: document iscsiadm host argument iscsid: add new auth error code iscsi tools: convert discovery code to iscsi error codes iscsi tools: document iface rp_filter use iscsi tools: disable isns dsa code iscsi tools: support hostnames in node mode iscsi tools: fix discovery return code iscsiadm: fix offload discovery retry iscsid: fix signal handler debug msg iscsiadm: fix discovery exit code iscsi tools: fix dcbnl.h compile error iscsid: retry initial connect iscsi tools/kernel: switch make defaults iscsi tools: fix comment about sysfs lookup failures iscsi tools: fix netlink bug allocation iscsi tools: Don't try to bind offload EPs to sockets iscsi tools: fix oom_adj use iscsi tools: fix bnx2i boot due to MAC mismatch iscsiadm: fix discoverydb help Update SUSE init script iscsi tools: revert commit c440cbe7ba2464f8baadedb55b00754c36773c2c Add a TODO TODO: mark down Jose as working on idr Update TODO iscsi tools: fix iname sysfs handling iscsi tools: handle compile warnings about unused variables iscsiadm: print kernel iface info iscsi tools: add tgt reset to session info and fix unknown values iscsi tools: fix default iface binding setup iscsi tools: fix iscsiadm return value on failed login iscsi tools: don't build with openssl iscsi tools: check NULL pointer first and add limit check in str_remove_initial iscsi tools: fix README sid lookup info iscsid: print out more informative error string for kernel errors iscsi tools: fix netlink msg setup iscsi tools: fix up vlan support update todo iscsiadm: fix printing of unknown host values Do not run configure for open-isns on every build iscsi tools: fix ipv6 ibft/firmware boot iscsid: don't sync qla4xxx flash sessions iscsid: kill session if already exists. isns: remove rfc files. iscsistart: allow any rec/iscsid.conf setting as arg iscsistart: support params in offload/ibft mode iscsi tools: never use hdr digest with iser iscsi tools: update iscsi_if.h for host event iscsi tools: added ping support iscsi tools: Add support to display a host's CHAP list and delete iscsi tools: fix conn state compilation warnings iscsi tools: allow default to have different transort names iscsiadm: print ping status string iscsi tools: fix hostname with port handling iscsi tools: have iscsid/iscsiadm load modules as needed iscsi tools: have iscsiadm load offload modules init: update red hat init script for module changes iscsi tools: create def ifaces on demand iscsi tools: iscsiadm modprobe support iscsi tools: remove class version check iscsi tools: remove unused len variable iscsiadm: support multiple params in one call iscsid: remove DCB support iscsiadm: print port speed and link state iscsi tools: check for loaded module before loading iscsistart: have iscsistart use same multi param code as iscsiadm iscsi tools: print and load boot transport iscsiadm: load iface before checking for hostno/mac match iscsistart: fix iface overriding iscsiadm: make sure offload drivers are loaded in host mode iscsi tools: have iscsi tools bring up offload net iface iscsi tools: fix bnx2i login iscsi tools: fix ipv6 handling iscsistart: fix invalid param handling iscsiadm: added command line option '--interval' iscsi tools: fix unknown param warnings iscsi tools: fix socket leak in transport probe iscsi tools: remove useless NULL iface check iscsi tools: use strlpy in net code Nilesh Javali (1): iscsi tools: update documents for CHAP command Rahul Gupta (1): iscsi tools: Displaying timeout and CHAP in iscisadm info Vikas Chaudhary (2): iscsi tools: update documents for ping command iscsi tools: remove un-necessary print message Wang Sheng-Hui (1): usr/config.h: fix comment for struct iscsi_session_timeout_config open-iscsi-2.0.873/Makefile000066400000000000000000000106621175631155400154210ustar00rootroot00000000000000# # Makefile for the Open-iSCSI Initiator # # if you are packaging open-iscsi, set this variable to the location # that you want everything installed into. DESTDIR ?= prefix = /usr exec_prefix = / sbindir = $(exec_prefix)/sbin bindir = $(exec_prefix)/bin mandir = $(prefix)/share/man etcdir = /etc initddir = $(etcdir)/init.d MANPAGES = doc/iscsid.8 doc/iscsiadm.8 doc/iscsi_discovery.8 PROGRAMS = usr/iscsid usr/iscsiadm utils/iscsi_discovery utils/iscsi-iname INSTALL = install ETCFILES = etc/iscsid.conf IFACEFILES = etc/iface.example # Random comments: # using '$(MAKE)' instead of just 'make' allows make to run in parallel # over multiple makefile. all: user user: utils/open-isns/Makefile $(MAKE) -C utils/open-isns $(MAKE) -C utils/sysdeps $(MAKE) -C utils/fwparam_ibft $(MAKE) -C usr $(MAKE) -C utils @echo @echo "Compilation complete Output file" @echo "----------------------------------- ----------------" @echo "Built iSCSI daemon: usr/iscsid" @echo "Built management application: usr/iscsiadm" @echo "Built boot tool: usr/iscsistart" @echo @echo "Read README file for detailed information." utils/open-isns/Makefile: utils/open-isns/configure utils/open-isns/Makefile.in cd utils/open-isns; ./configure CFLAGS="$(OPTFLAGS)" --with-security=no kernel: force $(MAKE) -C kernel @echo "Kernel Compilation complete Output file" @echo "----------------------------------- ----------------" @echo "Built iSCSI Open Interface module: kernel/scsi_transport_iscsi.ko" @echo "Built iSCSI library module: kernel/libiscsi.ko" @echo "Built iSCSI over TCP library module: kernel/libiscsi_tcp.ko" @echo "Built iSCSI over TCP kernel module: kernel/iscsi_tcp.ko" force: ; clean: $(MAKE) -C utils/sysdeps clean $(MAKE) -C utils/fwparam_ibft clean $(MAKE) -C utils clean $(MAKE) -C usr clean $(MAKE) -C kernel clean $(MAKE) -C utils/open-isns clean $(MAKE) -C utils/open-isns distclean # this is for safety # now -jXXX will still be safe # note that make may still execute the blocks in parallel .NOTPARALLEL: install_user install_programs install_initd \ install_initd_suse install_initd_redhat install_initd_debian \ install_etc install_iface install_doc install_kernel install_iname install: install_programs install_doc install_etc \ install_initd install_iname install_iface install_user: install_programs install_doc install_etc \ install_initd install_iname install_iface install_programs: $(PROGRAMS) $(INSTALL) -d $(DESTDIR)$(sbindir) $(INSTALL) -m 755 $^ $(DESTDIR)$(sbindir) # ugh, auto-detection is evil # Gentoo maintains their own init.d stuff install_initd: if [ -f /etc/debian_version ]; then \ $(MAKE) install_initd_debian ; \ elif [ -f /etc/redhat-release ]; then \ $(MAKE) install_initd_redhat ; \ elif [ -f /etc/SuSE-release ]; then \ $(MAKE) install_initd_suse ; \ fi # these are external targets to allow bypassing distribution detection install_initd_suse: $(INSTALL) -d $(DESTDIR)$(initddir) $(INSTALL) -m 755 etc/initd/initd.suse \ $(DESTDIR)$(initddir)/open-iscsi $(INSTALL) -m 755 etc/initd/boot.suse \ $(DESTDIR)$(initddir)/boot.open-iscsi install_initd_redhat: $(INSTALL) -d $(DESTDIR)$(initddir) $(INSTALL) -m 755 etc/initd/initd.redhat \ $(DESTDIR)$(initddir)/open-iscsi install_initd_debian: $(INSTALL) -d $(DESTDIR)$(initddir) $(INSTALL) -m 755 etc/initd/initd.debian \ $(DESTDIR)$(initddir)/open-iscsi install_iface: $(IFACEFILES) $(INSTALL) -d $(DESTDIR)$(etcdir)/iscsi/ifaces $(INSTALL) -m 644 $^ $(DESTDIR)$(etcdir)/iscsi/ifaces install_etc: $(ETCFILES) if [ ! -f /etc/iscsi/iscsid.conf ]; then \ $(INSTALL) -d $(DESTDIR)$(etcdir)/iscsi ; \ $(INSTALL) -m 644 $^ $(DESTDIR)$(etcdir)/iscsi ; \ fi install_doc: $(MANPAGES) $(INSTALL) -d $(DESTDIR)$(mandir)/man8 $(INSTALL) -m 644 $^ $(DESTDIR)$(mandir)/man8 install_kernel: $(MAKE) -C kernel install_kernel install_iname: if [ ! -f /etc/iscsi/initiatorname.iscsi ]; then \ echo "InitiatorName=`$(DESTDIR)/sbin/iscsi-iname`" > $(DESTDIR)/etc/iscsi/initiatorname.iscsi ; \ echo "***************************************************" ; \ echo "Setting InitiatorName to `cat $(DESTDIR)/etc/iscsi/initiatorname.iscsi`" ; \ echo "To override edit /etc/iscsi/initiatorname.iscsi" ; \ echo "***************************************************" ; \ fi depend: for dir in usr utils utils/fwparam_ibft; do \ $(MAKE) -C $$dir $@; \ done # vim: ft=make tw=72 sw=4 ts=4: open-iscsi-2.0.873/README000066400000000000000000001502621175631155400146420ustar00rootroot00000000000000================================================================= Linux* Open-iSCSI ================================================================= May 20, 2012 Contents ======== - 1. In This Release - 2. Introduction - 3. Installation - 4. Open-iSCSI daemon - 5. Open-iSCSI Configuration Utility - 6. Configuration - 7. Getting Started - 8. Advanced Configuration - 9. iSCSI System Info 1. In This Release ================== This file describes the Linux* Open-iSCSI Initiator. The software was tested on AMD Opteron (TM) and Intel Xeon (TM). The latest development release is available at: http://www.open-iscsi.org For questions, comments, contributions send e-mail to: open-iscsi@googlegroups.com 1.1. Features - highly optimized and very small-footprint data path; - persistent configuration database; - SendTargets discovery; - CHAP; - PDU header Digest; - multiple sessions; 2. Introduction =============== Open-iSCSI project is a high-performance, transport independent, multi-platform implementation of RFC3720 iSCSI. Open-iSCSI is partitioned into user and kernel parts. The kernel portion of Open-iSCSI is a from-scratch code licensed under GPL. The kernel part implements iSCSI data path (that is, iSCSI Read and iSCSI Write), and consists of three loadable modules: scsi_transport_iscsi.ko, libiscsi.ko and iscsi_tcp.ko. User space contains the entire control plane: configuration manager, iSCSI Discovery, Login and Logout processing, connection-level error processing, Nop-In and Nop-Out handling, and (in the future:) Text processing, iSNS, SLP, Radius, etc. The user space Open-iSCSI consists of a daemon process called iscsid, and a management utility iscsiadm. 3. Installation =============== As of today, the Open-iSCSI Initiator requires a host running the Linux operating system with kernel version 2.6.16, or later. 2.6.14 and 2.6.15 are partially supported. Known issues with 2.6.14 - .15 support: - If the device is using a write back cache, during session logout the cache sync command will fail. - iscsiadm's -P 3 option will not print out scsi devices. - iscsid will not automatically online devices. You need to enable "Cryptographic API" under "Cryptographic options" in the kernel config. And you must enable "CRC32c CRC algorithm" even if you do not use header or data digests. They are the kernel options, CONFIG_CRYPTO and CONFIG_CRYPTO_CRC32C, respectively. By default the kernel's iSCSI modules will be used. Running: make make install will install the iSCSI tools iscsiadm and iscsid to /sbin. For 2.6.14 - 2.6.34 the modules in the kernel dir can built and install by running: make kernel When building those modules the kernel source found at /lib/modules/`uname -a`/build will be used to compile the open-iscsi modules. To specify a different kernel to build against use: make kernel KSRC= or cross-compilation: make kernel KSRC= KARCH="ARCH=um" To compile on SUSE Linux you'll have to use make kernel KSRC=/usr/src/linux \ KBUILD_OUTPUT=/usr/src/linux-obj// where is the kernel configuration to use (eg. 'smp'). To install the kernel modules that were built run: make install_kernel This will copy: iscsi_tcp.ko, libiscsi_tcp.ko, libiscsi.ko and scsi_transport_iscsi to /lib/modules/`uname -r`/kernel/drivers/scsi/ overwriting existing iscsi modules. For Debian, be sure to install the linux-headers package that corresponds to your kernel in order to compile the kernel modules ('aptitude install linux-headers-`uname -r`'). You may also wish to run 'make -C kernel/ dpkg_divert' before installing kernel modules if you run a Debian-provided kernel. This will use dpkg-divert(8) to move the packaged kernel modules out of the way, and ensure that future kernel upgrades will not overwrite them. Also, please be aware that the compatibility patches that enable these iscsi modules to run on kernels older than 2.6.25 will not update the ib_iser module; you may get warnings related to mismatched symbols on this driver, in which case you'll be unable to load ib_iser and open-iscsi simultaneously. 4. Open-iSCSI daemon ==================== The daemon implements control path of iSCSI protocol, plus some management facilities. For example, the daemon could be configured to automatically re-start discovery at startup, based on the contents of persistent iSCSI database (see next section). For help, run: ./iscsid --help Usage: iscsid [OPTION] -c, --config=[path] Execute in the config file (/etc/iscsi/iscsid.conf). -f, --foreground run iscsid in the foreground -d, --debug debuglevel print debugging information -u, --uid=uid run as uid, default is current user -g, --gid=gid run as gid, default is current user group -h, --help display this help and exit -v, --version display version and exit 5. Open-iSCSI Configuration Utility =================================== Open-iSCSI persistent configuration is implemented as a DBM database available on all Linux installations. The database contains two tables: - Discovery table (/etc/iscsi/send_targets); - Node table (/etc/iscsi/nodes). The regular place for iSCSI database files: /etc/iscsi/nodes The iscsiadm utility is a command-line tool to manage (update, delete, insert, query) the persistent database. The utility presents set of operations that a user can perform on iSCSI nodes, sessions, connections, and discovery records. Open-iscsi does not use the term node as defined by the iSCSI RFC, where a node is a single iSCSI initiator or target. Open-iscsi uses the term node to refer to a portal on a target, so tools like iscsiadm require that --targetname and --portal argument be used when in node mode. For session mode, a session id (sid) is used. The sid of a session can be found by running iscsiadm -m session -P 1. The session id is not currently persistent and is partially determined by when the session is setup. Note that some of the iSCSI Node and iSCSI Discovery operations do not require iSCSI daemon (iscsid) loaded. For help, run: ./iscsiadm --help Usage: iscsiadm [OPTION] -m, --mode specify operational mode op = -m discoverydb --type=[type] --interface=[iface...] --portal=[ip:port] \ --print=[N] \ --op=[op]=[NEW | UPDATE | DELETE | NONPERSISTENT] \ --discover This command will use the discovery record settings matching the record with type=type and portal=ip:port]. If a record does not exist, it will create a record using the iscsid.conf discovery settings. By default, it will then remove records for portals no longer returned. And, if a portal is returned by the target, then the discovery command will create a new record or modify an existing one with values from iscsi.conf and the command line. [op] can be passed in multiple times to this command, and it will alter the node DB manipulation. If [op] is passed in and the value is "new", iscsiadm will add records for portals that do not yet have records in the db. If [op] is passed in and the value is "update", iscsiadm will update node records using info from iscsi.conf and the command line for portals that are returned during discovery and have a record in the db. If [op] is passed in and the value is "delete", iscsiadm will delete records for portals that were not returned during discovery. If [op] is passed in and the value is "nonpersistent" iscsiadm will not store the portals found in the node DB. This only useful with the --login command. See the example section for more info. See below for how to setup iscsi ifaces for software iscsi or override the system defaults. Multiple ifaces can be passed in during discovery. For the above commands "print" is optional. If used, N can be 0 or 1. 0 = The old flat style of output is used. 1 = The tree style with the inteface info is used. If print is not used the old flay style is used. -m discoverydb --interface=[iface...] --type=[type] --portal=[ip:port] \ --print=[N] \ --op=[op]=[NEW | UPDATE | DELETE | NONPERSISTENT] \ --discover --login This works like the previous discoverydb command with the --login argument passed in will also log into the portals that are found. -m discoverydb --portal=[ip:port] --type=[type] \ --op=[op] [--name=[name] --value=[value]] Perform specific DB operation [op] for discovery portal. It could be one of: [new], [delete], [update] or [show]. In case of [update], you have to provide [name] and [value] you wish to update op=NEW will create a new discovery record using the iscsid.conf discovery settings. If it already exists, it will be overwritten using iscsid.conf discovery settings. op=DELETE will delete the discovery record and records for the targets found through that discovery source. op=SHOW will display the discovery record values. The --show arguemnt can be used to force the CHAP passwords to be displayed. -m discovery --type=[type] --interface=iscsi_ifacename \ --portal=[ip:port] --login --print=[N] \ --op=[op]=[NEW | UPDATE | DELETE | NONPERSISTENT] perform [type] discovery for target portal with ip-address [ip] and port [port]. This command will not use the discovery record settings. It will use the iscsid.conf discovery settings and it will overwrite the discovery record with iscsid.conf discovery settings if it exists. By default, it will then remove records for portals no longer returned. And, if a portal is returned by the target, then the discovery command will create a new record or modify an existing one with values from iscsi.conf and the command line. [op] can be passed in multiple times to this command, and it will alter the DB manipulation. If [op] is passed in and the value is "new", iscsiadm will add records for portals that do not yet have records in the db. If [op] is passed in and the value is "update", iscsiadm will update node records using info from iscsi.conf and the command line for portals that are returned during discovery and have a record in the db. If [op] is passed in and the value is "delete", iscsiadm will delete records for portals that were not returned during discovery. If [op] is passed in and the value is "nonpersistent" iscsiadm will not store the portals found in the node DB. See the example section for more info. See below for how to setup iscsi ifaces for software iscsi or override the system defaults. Multiple ifaces can be passed in during discovery. -m discovery --print=[N] display all discovery records from internal persistent discovery database. -m node display all discovered nodes from internal persistent discovery database -m node --targetname=[name] --portal=[ip:port] \ --interface=iscsi_ifacename] \ [--login|--logout|--rescan|--stats] -m node --targetname=[name] --portal=[ip:port] --interface=[driver,HWaddress] \ --op=[op] [--name=[name] --value=[value]] -m node --targetname=[name] --portal=[ip:port] --interface=iscsi_ifacename] \ --print=[level] perform specific DB operation [op] for specific interface on host that will connect to portal on target. targetname, portal and interface are optional. See below for how to setup iscsi ifaces for software iscsi or override the system defaults. op could be one of: [new], [delete], [update] or [show]. In case of [update], you have to provide [name] and [value] you wish to update. [delete] - Note that if a session is using the node record, the session will be logged out then the record will be deleted. Print level can be 0 to 1. Rescan will perform a SCSI layer scan of the session to find new LUNs. Stats prints the iSCSI stats for the session. -m node --logoutall=[all|manual|automatic] Logout "all" the running sessions or just the ones with a node startup value manual or automatic. Nodes marked as ONBOOT are skipped. -m node --loginall=[all|manual|automatic] Login "all" the running sessions or just the ones with a node startup value manual or automatic. Nodes marked as ONBOOT are skipped. -m session display all active sessions and connections -m session --sid=[sid] [ --print=level | --rescan | --logout ] --op=[op] [--name=[name] --value=[value]] perform operation for specific session with session id sid. If no sid is given the operation will be performed on all running sessions if possible. --logout and --op work like they do in node mode, but in session mode targetname and portal info is is not passed in. Print level can be 0 to 2. 1 = Print basic session info like node we are connected to and whether we are connected. 2 = Print iscsi params used. 3 = Print SCSI info like LUNs, device state. If no sid and no operation is given print out the running sessions. -m iface --interface=iscsi_ifacename --op=[op] [--name=[name] --value=[value]] --print=level perform operation on fiven interface with name iscsi_ifacename. See below for examples. -m iface --interface=iscsi_ifacename -C ping --ip=[ipaddr] --packetsize=[size] --count=[count] --interval=[interval] -m host --host=hostno|MAC --print=level -C chap --op=[op] --value=[chap_tbl_idx] Display information for a specific host. The host can be passed in by host number or by MAC address. If a host is not passed in then info for all hosts is printed. Print level can be 0 to 4. 1 = Print info for how like its state, MAC, and netinfo if possible. 2 = Print basic session info for nodes the host is connected to. 3 = Print iscsi params used. 4 = Print SCSI info like LUNs, device state. -d, --debug debuglevel print debugging information -V, --version display version and exit -h, --help display this help and exit 5.1 iSCSI iface setup ===================== The next sections describe how to setup iSCSI ifaces so you can bind a session to a NIC port when using software iscsi (section 5.1.1), and it describes how to setup ifaces for use with offload cards from Chelsio and Broadcm (section 5.1.2). 5.1.1 How to setup iSCSI interfaces (iface) for binding ======================================================= If you wish to allow the network susbsystem to figure out the best path/NIC to use then you can skip this section. For example if you have setup your portals and NICs on different subnets then this the following is not needed for software iscsi. Warning!!!!!! This feature is experimental. The interface may change. When reporting bugs, if you cannot do a "ping -I ethX target_portal", then check your network settings first. Make sure the rp_filter setting is set to 0 or 2 (see Prep section below for more info). If you cannot ping the portal, then you will not be able to bind a session to a NIC. What is a scsi_host and iface for software, hardware and partial offload iscsi? Software iscsi, like iscsi_tcp and iser, allocate a scsi_host per session and does a single connection per session. As a result /sys/class_scsi_host and /proc/scsi will report a scsi_host for each connection/session you have logged into. Offload iscsi, like Chelsio cxgb3i, allocates a scsi_host for each PCI device (each port on a HBA will show up as a different PCI device so you get a scsi_host per HBA port). To manage both types of initiator stacks, iscsiadm uses the interface (iface) structure. For each HBA port or for software iscsi for each network device (ethX) or NIC, that you wish to bind sessions to you must create a iface config /etc/iscsi/ifaces. Prep: The iface binding feature requires the sysctl setting net.ipv4.conf.default.rp_filter to be set to 0 or 2. This can be set in /etc/sysctl.conf by having the line: net.ipv4.conf.default.rp_filter = N where N is 0 or 2. Note that when setting this you may have to reboot the box for the value to take effect. rp_filter information from Documentation/networking/ip-sysctl.txt: rp_filter - INTEGER 0 - No source validation. 1 - Strict mode as defined in RFC3704 Strict Reverse Path Each incoming packet is tested against the FIB and if the interface is not the best reverse path the packet check will fail. By default failed packets are discarded. 2 - Loose mode as defined in RFC3704 Loose Reverse Path Each incoming packet's source address is also tested against the FIB and if the source address is not reachable via any interface the packet check will fail. Running: # iscsiadm -m iface iface0 qla4xxx,00:c0:dd:08:63:e8,20.15.0.7,default,iqn.2005-06.com.redhat:madmax iface1 qla4xxx,00:c0:dd:08:63:ea,20.15.0.9,default,iqn.2005-06.com.redhat:madmax Will report iface configurations that are setup in /etc/iscsi/ifaces. The format is: iface_name transport_name,hwaddress,ipaddress,net_ifacename,initiatorname For software iscsi, you can create the iface configs by hand, but it is reccomended that you use iscsiadm's iface mode. There is a iface.example in /etc/iscsi/ifaces which can be used as a template for the daring. For each network object you wish to bind a session to you must create a seperate iface config in /etc/iscsi/ifaces and each iface config file must have a unique name which is less than or equal to 64 characters. Example: If you have NIC1 with MAC address 00:0F:1F:92:6B:BF and NIC2 with MAC address 00:C0:DD:08:63:E7 and you wanted to do software iscsi over TCP/IP. Then in /etc/iscsi/ifaces/iface0 you would enter: iface.transport_name = tcp iface.hwaddress = 00:0F:1F:92:6B:BF and in /etc/iscsi/ifaces/iface1 you would enter: iface.transport_name = tcp iface.hwaddress = 00:C0:DD:08:63:E7 Warning: Do not name a iface config file "default" or "iser". They are special value/file that is used by the iscsi tools for backward compatibility. If you name a iface default or iser, then the behavior is not defined. To use iscsiadm to create iface0 above for you run: (This will create a new empty iface config. If there was already a iface with the name "iface0" this command will overwrite it.) # iscsiadm -m iface -I iface0 --op=new (This will set the hwaddress.) # iscsiadm -m iface -I iface0 --op=update -n iface.hwaddress -v 00:0F:1F:92:6B:BF If you had sessions logged in iscsiadm will not update, overwrite a iface. You must log out first. If you have a iface bound to a node/portal but you have not logged in then, iscsiadm will update the config and all existing bindings. You should now skip to 5.1.3 to see how to log in using the iface and for some helpful management commands. 5.1.2 Setting up a iface for a iSCSI offload card ================================================= This section describes how to setup ifaces for use with Chelsio, Broadcom and QLogic cards. By default, iscsiadm will create a iface for each Broadcom, QLogic and Chelsio port. The iface name will be of the form: $transport/driver_name.$MAC_ADDRESS Running: # iscsiadm -m iface default tcp,,,, iser iser,,,, cxgb3i.00:07:43:05:97:07 cxgb3i,00:07:43:05:97:07,,, qla4xxx.00:0e:1e:04:8b:2e qla4xxx,00:0e:1e:04:8b:2e,,, Will report iface configurations that are setup in /etc/iscsi/ifaces. The format is: iface_name transport_name,hwaddress,ipaddress,net_ifacename,initiatorname iface_name: name of iface transport_name: name of driver hwaddress: MAC address ipaddress: IP address to use for this port net_iface_name: Net_ifacename will be because change between reboots. It is used for software iSCSI's vlan or alias binding. initiatorname: Initiatorname to be used if you want to override the default one in /etc/iscsi/initiatorname.iscsi. To display these values in a more friendly way, run: iscsiadm -m iface -I cxgb3i.00:07:43:05:97:07 # BEGIN RECORD 2.0-871 iface.iscsi_ifacename = cxgb3i.00:07:43:05:97:07 iface.net_ifacename = iface.ipaddress = iface.hwaddress = 00:07:43:05:97:07 iface.transport_name = cxgb3i iface.initiatorname = # END RECORD Before you can use the iface, you must set the IP address for the port with the following command: iscsiadm -m iface -I cxgb3i.00:07:43:05:97:07 -o update -n iface.ipaddress -v 20.15.0.66 Note1. For the name of the value we want to update we use the name from the "iscsiadm -m iface -I cxgb3i.00:07:43:05:97:07" command which is "iface.ipaddress". Note2. For QLogic ports after updating the iface record, for network settings to take effect, one must apply or applyall the settings. iscsiadm -m iface -I qla4xxx.00:0e:1e:04:8b:2e -o apply or iscsiadm -m iface -H 00:0e:1e:04:8b:2e -o applyall With operation "apply" network setting for the specified iface will take effect. With operation "applyall" network settings for all ifaces on a specific host will take take effect. The host can be specified using the -H/--host argument by either the MAC address of the host or the host number. Here is an example of setting multiple IPv6 address on single iSCSI interface port. First interface (no need to set iface_num, it is 0 by default) iscsiadm -m iface -I qla4xxx.00:0e:1e:04:8b:2a -o update \ -n iface.ipaddress -v fec0:ce00:7014:0041:1111:2222:1e04:9392 Create the second interface if it does not exist iscsiadm -m iface -I qla4xxx.00:0e:1e:04:8b:2a.1 -op=new iscsiadm -m iface -I qla4xxx.00:0e:1e:04:8b:2a -o update \ -n iface.iface_num -v 1 (iface_num is mandatory for second iface) iscsiadm -m iface -I qla4xxx.00:0e:1e:04:8b:2a -o update \ -n iface.ipaddress -v = fec0:ce00:7014:0041:1111:2222:1e04:9393 iscsiadm -m iface -H 00:0e:1e:04:8b:2a --op=applyall Note: If there are common settings for multiple interfaces then the settings from 0th iface would be considered valid. Now, we can use this iface to login into targets, which is described in the next section. 5.1.3 Discoverying iSCSI targets/portals ======================================== Be aware that iscsiadm will use the default route to do discovery. It will not use the iface specified. So if you are using a offload card, you will need a seperate network connection to the target for discovery purposes. *This will be fixed in the next version of open-iscsi* For compatibility reasons, when you run iscsiadm to do discovery, it will check for interfaces in /etc/iscsi/iscsi/ifaces that are using tcp for the iface.transport and it will bind the portals that are discovered so that they will be logged in through those ifaces. This behavior can also be overriden by passing in the interfaces you want to use. For the case of offload like with cxgb3i and bnx2i this is required because the transport will not be tcp. For example if you had defined two interface but only wanted to use one you can use the --interface/-I argument: iscsiadm -m discoverydb -t st -p ip:port -I iface1 --discover -P 1 If you had defined interfaces but wanted the old behavior, where we do not bind a session to a iface, then you can use the special iface "default": iscsiadm -m discoverydb -t st -p ip:port -I default --discover -P 1 And if you did not define any interfaces in /etc/iscsi/ifaces and do not pass anything into iscsiadm, running iscsiadm will do the default behavior, where we allow the network subsystem to decide which device to use. If you later want to remove the bindings for a specific target and iface then you can run: iscsiadm -m node -T my_target -I iface0 --op=delete To do this for a specific portal on a target run: iscsiadm -m node -T my_target -p ip:port -I iface0 --op=delete If you wanted to delete all bindinds for iface0 then you can run iscsiadm -m node -I iface0 --op=delete And for equalogic targets it is sometimes useful to remove by just portal iscsiadm -m node -p ip:port -I iface0 --op=delete To now log into targets it is the same as with sofware iscsi. See section 7 for how to get started. 5.2 iscsiadm examples ===================== Usage examples using the one-letter options (see iscsiadm man page for long options): Discovery mode: - SendTargets iSCSI Discovery using the default driver and interface and using the discovery settings for the discovery record with the ID [192.168.1.1:3260]. ./iscsiadm -m discoverydb -t st -p 192.168.1.1:3260 --discover This will search /etc/iscsi/send_targets for a record with the ID [portal = 192.168.1.1:3260 and type = sendtargets. If found it will perform discovery using the settings stored in the record. If a record does not exist, it will be created using the iscsid.conf discovery settings. The argument to -p may also be a hostname instead of an address. ./iscsiadm -m discoverydb -t st -p smoehost --discover For the ifaces, iscsiadm will first search /etc/iscsi/ifaces for interfaces using software iscsi. If any are found then nodes found during discovery will be setup so that they can logged in through those interfaces. To specify a specific iface, pass the -I argument for each iface. - SendTargets iSCSI Discovery updating existing target records: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o update --discover If there is a record for targetX and portalY exists in the DB, and is returned during discovery, it will be updated with the info from the iscsi.conf. No new portals will be added and stale portals will not be removed. - SendTargets iSCSI Discovery deleting existing target records: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o delete --discover If there a record for targetX and portalY exists in the DB, but is not returned during discovery it will be removed from the DB. No new portals will be added and existing portal records will not be changed. Note: If a session is logged into portal we are going to delete a record for, it will be logged out then the record will be deleted. - SendTargets iSCSI Discovery adding new records: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o new --discover If there targetX and portalY is returned during discovery and does not have a record, it will be added. Existing records are not modified. - SendTargets iSCSI Discovery using multiple ops: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o new -o delete --discover This command will add new portals and delete records for portals no longer returned. It will not change the record information for existing portals. - SendTargets iSCSI Discovery in nonpersistent mode: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o nonpersistent --discover This command will perform discovery, but not manipulate the node DB. - SendTargets iSCSI Discovery with a specific interface. If you wish to only use a subset of the interfaces in /etc/iscsi/ifaces then you can pass them in during discovery: ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ --interface=iface0 --interface=iface1 --discover Note that for software iscsi, we let the network layer select which NIC to use for discovery, but for later logins iscsiadm will use the NIC defined in the iface config. qla4xxx support is very basic and experimental. It does not store the record info in the card's FLASH or the node DB, so you must rerun discovery every time the driver is reloaded. - Manipulate SendTargets DB. Create new SendTargets discovery record or overwrite an existing discovery record with iscsid.conf discovery settings. ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 -o new See discovery settings. ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 -o show See hidden discovery settings like CHAP passwords ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o show --show Set discovery setting. ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 \ -o update -n name -v value Delete discovery record. This will also delete the records for the targets found through the discovery source. ./iscsiadm -m discoverydb -t sendtargets -p 192.168.1.1:3260 -o delete Node mode. In node mode you can specify which records you want to log into by specifying the targetname, ip address, port or interface (if specifying the interface it must already be setup in the node db). iscsiadm will search the node db, for records which match the values you pass in, so if you pass in the targetname and interface, iscsiadm will search for records with those values and operate on only them. Passing in none of them will result in all node records being operated on. - iSCSI Login to all portals on every node/starget through each interface set in the db: ./iscsiadm -m node -l - iSCSI login to all portals on a node/target through each interface set in the db: ./iscsiadm -m node -T iqn.2005-03.com.max -l - iSCSI login to a specific portal through each interface set in the db: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 -l To specify a IPv6 address the following can be used: ./iscsiadm -m node -T iqn.2005-03.com.max \ -p 2001:c90::211:9ff:feb8:a9e9 -l The above command would use the default port, 3260. To specify a port use the following: ./iscsiadm -m node -T iqn.2005-03.com.max \ -p [2001:c90::211:9ff:feb8:a9e9]:3260 -l To specify a hostname the following can be used: ./iscsiadm -m node -T iqn.2005-03.com.max -p somehost -l - iSCSI Login to a specific portal through the NIC setup as iface0: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 \ -I iface0 -l - iSCSI Logout to all portals on every node/starget through each interface set in the db: ./iscsiadm -m node -u Warning: this does not check startup values like the logout/login all option. Do not use this if you are running iscsi on your root disk. - iSCSI logout to all portals on a node/target through each interface set in the db: ./iscsiadm -m node -T iqn.2005-03.com.max -u - iSCSI logout to a specific portal through each interface set in the db: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 -u - iSCSI Logout to a specific portal through the NIC setup as iface0: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 \ -I iface0 - Changing iSCSI parameter: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 \ -o update -n node.cnx[0].iscsi.MaxRecvDataSegmentLength -v 65536 You can also change paramaters for multiple records at once, by specifying different combinations of the target, portal and interface like above. - Adding custom iSCSI portal: ./iscsiadm -m node -o new -T iqn.2005-03.com.max \ -p 192.168.0.1:3260,2 -I iface4 The -I/--interface is optional. If not passed in, "default" is used. For tcp or iser, this would allow the network layer to decide what is best. Note that for this command the target portal group tag (TPGT) should be passed in. If it is not passed in on the initial creation command then the user must run iscsiadm again to set the value. Also if the TPGT is not initially passed in, the old behavior of not tracking whether the record was statically or dynamically created is used. - Adding custom NIC config to multiple targets: ./iscsiadm -m node -o new -I iface4 This command will add a interface config using the iSCSI and SCSI settings from iscsid.conf to every target that is in the node db. - Removing iSCSI portal: ./iscsiadm -m node -o delete -T iqn.2005-03.com.max -p 192.168.0.4:3260 You can also delete multiple records at once, by specifying different combinations of the target, portal and interface like above. - Display iSCSI portal onfiguration: ./iscsiadm -m node -T iqn.2005-03.com.max -p 192.168.0.4:3260 or ./iscsiadm -m node -o show -T iqn.2005-03.com.max -p 192.168.0.4:3260 You can also display multiple records at once, by specifying different combinations of the target, portal and interface like above. Note: running "iscsiadm -m node" will only display the records. It will not display the configuration info. You must run, "iscsiadm -m node -o show". - Show all node records: ./iscsiadm -m node This will print the nodes using the old flat format where the interface and driver are not displayed. To display that info use the -P argument with the arguent "1": ./iscsiadm -m node -P 1 - Show all records in discovery database: ./iscsiadm -m discovery - Show all records in discovery database and show the targets that were discovered from each record: ./iscsiadm -m discovery -P 1 - Display session statistics: ./iscsiadm -m session -r 1 --stats This function also works in node mode. Instead of the "-r $sid" argument, you would pass in the node info like targetname and/or portal, and/or interface. - Perform a SCSI scan on a session ./iscsiadm -m session -r 1 --rescan This function also works in node mode. Instead of the "-r $sid" argument, you would pass in the node info like targetname and/or portal, and/or interface. Note: Rescanning does not delete old LUNs. It will only pick up new ones. - Display running sessions: ./iscsiadm -m session -P 1 6. Configuration ================ The default configuration file is /etc/iscsi/iscsid.conf. This file contains only configuration that could be overwritten by iSCSI Discovery, or manualy updated via iscsiadm utility. Its OK if this file does not exist in which case compiled-in default configuration will take place for newer discovered Target nodes. See the man page and the example file for the current syntax. The manpages for iscsid, iscsiadm are in the doc subdirectory and can be installed in the appropriate man page directories and need to be manually copied into e.g. /usr/local/share/man8. 7. Getting Started ================== There are three steps needed to set up a system to use iSCSI storage: 7.1. iSCSI startup using the init script or manual startup. 7.2. Discover targets. 7.3. Automate target logins for future system reboots. The init scripts will start the iSCSI daemon and log into any portals that are set up for automatic login (discussed in 7.2) or discovered through the discover daemon iscsid.conf params (discussed in 7.1.2). If your distro does not have a init script, then you will have to start the daemon and log into the targets manually. 7.1.1 iSCSI startup using the init script ----------------------------------------------- Red Hat or Fedora: ----------------- To start open-iscsi in Red Hat/Fedora you can do: service open-iscsi start To get open-iscsi to automatically start at run time you may have to run: chkconfig --level open-iscsi on Where are the run levels. And, to automatically mount a file system during startup you must have the partition entry in /etc/fstab marked with the "_netdev" option. For example this would mount a iscsi disk sdb: /dev/sdb /mnt/iscsi ext3 _netdev 0 0 SUSE or Debian: --------------- Otherwise, if there is a initd script for your distro in etc/initd that gets installed with "make install" /etc/init.d/open-iscsi start will usually get you started. 7.1.2 Manual Startup: --------------------- 7.1.2.1 Starting up the iSCSI daemon (iscsid) and loading modules: ----------------------------------------------------------------- If there is no initd script, you must start the tools by hand. First load the iscsi modules with: modprobe -q iscsi_tcp after that start iSCSI daemon process: ./iscsid or alternatively, start it with debug enabled and with output redirected to the current console: ./iscsid -d 8 -f & 7.1.2.2 Logging into Targets: --------------------------- Use the configuration utility, iscsiadm, to add/remove/update Discovery records, iSCSI Node records or monitor active iSCSI sessions (see above or the iscsiadm man files and see section 7.2 below for how to discover targets). ./iscsiadm -m node will print out the nodes that have been discovered as: 10.15.85.19:3260,3 iqn.1992-08.com.netapp:sn.33615311 10.15.84.19:3260,2 iqn.1992-08.com.netapp:sn.33615311 The format is: ip:port,target_portal_group_tag targetname If you are using the iface argument or want to see the driver info use the following: ./iscsiadm -m node -P 1 Target: iqn.1992-08.com.netapp:sn.33615311 Portal: 10.15.84.19:3260,2 Iface Name: iface2 Portal: 10.15.85.19:3260,3 Iface Name: iface2 The format is: Target: targetname Portal ip_address:port,tpgt Iface: iface where targetname is the name of the target and ip_address:port is the address and port of the portal. tpgt, is the portal group tag of the portal, and is not used in iscsiadm commands except for static record creation. And iface name is the name of the iscsi interface defined in /etc/iscsi/ifaces. If no interface was defined in /etc/iscsi/ifaces or passed in, the default behavior is used. Default here is iscsi_tcp/tcp to be used over which ever NIC the network layer decides is best. To login, take the ip, port and targetname from above and run: ./iscsiadm -m node -T targetname -p ip:port -l In this example we would run ./iscsiadm -m node -T iqn.1992-08.com.netapp:sn.33615311 -p 10.15.84.19:3260 -l Note: drop the portal group tag from the "iscsiadm -m node" output. 7.2. Discover Targets --------------------- Once the iSCSI service is running, you can perform discovery using SendTarget with: iscsiadm -m discoverydb -t sendtargets -p ip:port --discover where "ip" is the address of the portal and port is the port. To use iSNS you can run the discovery command with the type as "isns" and pass in the ip:port: iscsiadm -m discoverydb -t isns -p ip:port --discover Both commands will print out the list of all discovered targets and their portals: # iscsiadm -m discoverydb -t st -p 10.15.85.19:3260 --discover 10.15.84.19:3260,2 iqn.1992-08.com.netapp:sn.33615311 10.15.85.19:3260,3 iqn.1992-08.com.netapp:sn.33615311 The format for the output is: ip:port,tpgt targetname In this example, for the first target the ip address is 10.15.85.19. The port is 3260. The target portal group is 3. The target name is iqn.1992-08.com.netapp:sn.33615311. If you would also like to see the iscsi inteface which will be used for each session then use the --print[N] option. iscsiadm -m discoverydb -t sendtargets -p ip:port -P 1 --discover will print: Target: iqn.1992-08.com.netapp:sn.33615311 Portal: 10.15.84.19:3260,2 Iface Name: iface2 Portal: 10.15.85.19:3260,3 Iface Name: iface2 In this example, The IP address of the first portal is 10.15.84.19. The port is 3260. The target portal group is 3. The target name is iqn.1992-08.com.netapp:sn.33615311. The iface being used is iface2. While discovery targets are kept in the discovery db, they are useful only for re-discovery. The discovered targets (a.k.a. nodes) are stored as records in the node db. The discovered targets are not logged into yet. Rather than logging into the discovered nodes (making LUs from those nodes available as storage), it is better to automate the login to the nodes we need. If you wish to log into a target manually now, see section "7.1.2.2 Logging in targets" above. 7.3. Automate Target Logins for Future System Statups ----------------------------------------------------- Note: this may only work for distros with init scripts. To automate login to a node, use the following with the record ID (record ID is the targetname and portal) of the node discovered in the discovery above: iscsiadm -m node -T targetname -p ip:port --op update -n node.startup -v automatic To set the automatic setting to all portals on a target through every interface setup for each protal, the following can be run: iscsiadm -m node -T targetname --op update -n node.startup -v automatic Or to set the "node.startup" attribute to "startup" as default for all sessions add the following to the /etc/iscsi/iscsid.conf: node.startup = automatic Setting this in iscsid.conf, will not affect existing nodes. It will only affect nodes that are discovered after setting the value. To login to all the automated nodes, simply restart the iscsi service: e.g /etc/init.d/open-iscsi restart. On your next startup the nodes will be logged into autmotically. 7.4 Automatic Discovery and Login ----------------------------------- Instead of running the iscsiadm discovery command and editing the startup setting, iscsid can be configured so that every X seconds it performs discovery and logs in and out of the portals return or no longer returned. In this mode, when iscsid starts it will check the discovery db for iSNS records with: discovery.isns.use_discoveryd = Yes and it will check for SendTargets discovery records that have the setting: discovery.sendtargets.use_discoveryd = Yes If set, iscsid will perform discovery to the address every discovery.isns.discoveryd_poll_inval or discovery.sendtargets.discoveryd_poll_inval seconds, and it will log into any portals found from the discovery source using the ifaces in /etc/iscsi/ifaces. Note that for iSNS the poll_interval does not have to be set. If not set, iscsid will only perform rediscovery when it gets a SCN from the server. # iSNS Note: # For servers like Microsofts where they allow SCN registrations, but do not # send SCN events, discovery.isns.poll_interval should be set to a non zero # value to auto discover new targets. This is also useful for servers like # linux-isns (SLES's iSNS server) where it sometimes does not send SCN # events in the proper format, so they may not get handled. Example: -------- SendTargets: ------------ - Create a SendTargets record by passing iscsiadm the "-o new" argument in discoverydb mode. # iscsiadm -m discoverydb -t st -p 20.15.0.7:3260 -o new New discovery record for [20.15.0.7,3260] added. - Set the use_discoveryd setting for the record. # iscsiadm -m discoverydb -t st -p 20.15.0.7:3260 -o update -n discovery.sendtargets.use_discoveryd -v Yes - Set the polling interval. # iscsiadm -m discoverydb -t st -p 20.15.0.7:3260 -o update -n discovery.sendtargets.discoveryd_poll_inval -v 30 To have the new settings take effect restart iscsid by restarting the iscsi service. Note: When iscsiadm is run with the -o new argument, it will use the discovery.sendtargets.use_discoveryd and discovery.sendtargets.discoveryd_poll_inval settings in iscsid.conf for the records initial settings. So if those are set in iscsid.conf, then you can skip the iscsiadm -o update commands. iSNS: ---- - Create a iSNS record by passing iscsiadm the "-o new" argument in discoverydb mode. # iscsiadm -m discoverydb -t isns -p 20.15.0.7:3205 -o new New discovery record for [20.15.0.7,3205] added. - Set the use_discoveryd setting for the record. # iscsiadm -m discoverydb -t isns -p 20.15.0.7:3205 -o update -n discovery.isns.use_discoveryd -v Yes - [OPTIONAL: see iSNS note above] Set the polling interval if needed. # iscsiadm -m discoverydb -t st -p 20.15.0.7:3205 -o update -n discovery.isns.discoveryd_poll_inval -v 30 To have the new settings take effect restart iscsid by restarting the iscsi service. Note: When iscsiadm is run with the -o new argument, it will use the discovery.isns.use_discoveryd and discovery.isns.discoveryd_poll_inval settings in iscsid.conf for the records initial settings. So if those are set in iscsid.conf, then you can skip the iscsiadm -o update commands. 8. Advanced Configuration ========================= 8.1 iSCSI settings for dm-multipath ----------------------------------- When using dm-multipath, the iSCSI timers should be set so that commands are quickly failed to the dm-multipath layer. For dm-multipath you should then set values like queue if no path, so that IO errors are retried and queued if all paths are failed in the multipath layer. 8.1.1 iSCSI ping/Nop-Out settings --------------------------------- To quickly detect problems in the network, the iSCSI layer will send iSCSI pings (iSCSI NOP-Out requests) to the target. If a NOP-Out times out the iSCSI layer will respond by failing running commands and asking the SCSI layer to requeue them if possible (SCSI disk commands get 5 retries if not using multipath). If dm-multipath is being used the SCSI layer will fail the command to the multipath layer instead of retrying. The multipath layer will then retry the command on another path. To control how often a NOP-Out is sent the following value can be set: node.conn[0].timeo.noop_out_interval = X Where X is in seconds and the default is 10 seconds. To control the timeout for the NOP-Out the noop_out_timeout value can be used: node.conn[0].timeo.noop_out_timeout = X Again X is in seconds and the default is 15 seconds. Normally for these values you can use: node.conn[0].timeo.noop_out_interval = 5 node.conn[0].timeo.noop_out_timeout = 10 If there are a lot of IO error messages, then the above values may be too aggressive and you may need to increase the values for your network conditions and workload, or you may need to check your network for possible problems. 8.1.2 replacement_timeout ------------------------- The next iSCSI timer that will need to be tweaked is: node.session.timeo.replacement_timeout = X Here X is in seconds. replacement_timeout will control how long to wait for session re-establishment before failing pending SCSI commands and commands that are being operated on by the SCSI layer's error handler up to a higher level like multipath or to an application if multipath is not being used. 8.1.2.1 Running Commands, the SCSI Error Handler, and replacement_timeout ------------------------------------------------------------------------- Remember, from the Nop-out discussion that if a network problem is detected, the running commands are failed immediately. There is one exception to this and that is when the SCSI layer's error handler is running. To check if the SCSI error handler is running iscsiadm can be run as: iscsiadm -m session -P 3 You will then see: Host Number: X State: Recovery When the SCSI EH is running, commands will not be failed until node.session.timeo.replacement_timeout seconds. To modify the timer that starts the SCSI EH, you can either write directly to the device's sysfs file: echo X > /sys/block/sdX/device/timeout where X is in seconds or on most distros you can modify the udev rule. To modify the udev rule open /etc/udev/rules.d/50-udev.rules, and find the following lines: ACTION=="add", SUBSYSTEM=="scsi" , SYSFS{type}=="0|7|14", \ RUN+="/bin/sh -c 'echo 60 > /sys$$DEVPATH/timeout'" And change the echo 60 part of the line to the value that you want. The default timeout for normal File System commands is 30 seconds when udev is not being used. If udev is used the default is the above value which is normally 60 seconds. 8.1.2.2 Pending Commands and replacement_timeout ------------------------------------------------ Commonly, the SCSI/BLOCK layer will queue 256 commands, but the path can only take 32. When a network problem is detected, the 32 commands in flight will be sent back to the SCSI layer immediately and because multipath is being used this will cause the commands to be sent to the multipath layer for execution on another path. However the other 96 commands that were still in the SCSI/BLOCK queue, will remain here until the session is re-established or until node.session.timeo.replacement_timeout seconds has gone by. After replacement_timeout seconds, the pending commands will be failed to the multipath layer, and all new incoming commands will be immediately failed back to the multipath layer. If a session is later re-established, then new commands will be queued and executed. Normally, multipathd's path tester mechanism will detect that the session has been re-established and the path is accessible again, and it will inform dm-multipath. 8.1.3 Optimal replacement_timeout Value --------------------------------------- The default value for replacement_timeout is 120 seconds, but because multipath's queue_if_no_path and no_path_retry setting can prevent IO errors from being propagated to the application, replacement_timeout can be set to a shorter value like 5 to 15 seconds. By setting it lower pending IO is quickly sent to a new path and executed while the iSCSI layer attempts re-establishment of the session. If all paths end up being failed, then the multipath and device mapper layer will internally queue IO based on the multipath.conf settings, instead of the iSCSI layer. 8.2 iSCSI settings for iSCSI root --------------------------------- When accessing the root partition directly through a iSCSI disk, the iSCSI timers should be set so that iSCSI layer has several chances to try to re-establish a session and so that commands are not quickly requeued to the SCSI layer. Basically you want the opposite of when using dm-multipath. For this setup, you can turn off iSCSI pings by setting: node.conn[0].timeo.noop_out_interval = 0 node.conn[0].timeo.noop_out_timeout = 0 And you can turn the replacement_timer to a very long value: node.session.timeo.replacement_timeout = 86400 9. iSCSI System Info ==================== To get information about the running sessions: including the session and device state, session ids (sid) for session mode, and some of the negotiated parameters, run: iscsiadm -m session -P 2 If you are looking for something shorter like just the sid to node mapping run: iscsiadm -m session -P 0 or iscsiadm -m session This will print the list of running sessions with the format: driver [sid] ip:port,target_portal_group_tag targetname # iscsiadm -m session tcp [2] 10.15.84.19:3260,2 iqn.1992-08.com.netapp:sn.33615311 tcp [3] 10.15.85.19:3260,3 iqn.1992-08.com.netapp:sn.33615311 To print the hw address info use the -P option with "1": iscsiadm -m session -P 1 This will print the sessions with the following format: Target: targetname Current Portal: portal currently logged into Persistent Portal: portal we would fall back to if we had got redirected during login Iface Transport: driver/transport_name Iface IPaddress: IP address of iface being used Iface HWaddress: HW address used to bind session Iface Netdev: netdev value used to bind session SID: iscsi sysfs session id iSCSI Connection State: iscsi state Note: if a older kernel is being used or if the session is not bound then the keyword "default" is print to indicate that the default network behavior is being used. Example: #iscsiadm -m session -P 1 Target: iqn.1992-08.com.netapp:sn.33615311 Current Portal: 10.15.85.19:3260,3 Persistent Portal: 10.15.85.19:3260,3 Iface Transport: tcp Iface IPaddress: 10.11.14.37 Iface HWaddress: default Iface Netdev: default SID: 7 iSCSI Connection State: LOGGED IN Internal iscsid Session State: NO CHANGE The connection state is currently not available for qla4xxx. To get a HBA/Host view of the session there is the host mode. Example: iscsiadm -m host cxgb3i: [7] 10.10.15.51,[00:07:43:05:97:07],eth3 This prints the list of iSCSI hosts in the system with the format: driver [hostno] ipaddress,[hwaddress],net_ifacename,initiatorname To print this info in a more user friendly way the -P argument can be used: iscsiadm -m host -P 1 Host Number: 7 State: running Transport: cxgb3i Initiatorname: IPaddress: 10.10.15.51 HWaddress: 00:07:43:05:97:07 Netdev: eth3 Here, you can also see the sate of the host. You can also pass in any value from 1 - 4 to print more info like the sessions running through the host, what ifaces are being used and what devices are accessed through it. To print the info for a specific host then you can pass in the -H argument with the host number: iscsiadm -m host -P 1 -H 7 open-iscsi-2.0.873/THANKS000066400000000000000000000010001175631155400146560ustar00rootroot00000000000000contribution: Wang Zhenyu contribution: Albert Pauw contribution: Arne Redlich contribution: Christoph Hellwig contribution: Mike Christie contribution: Ming Zhang packaging: Chad Tindel testing: FUJITA Tomonori testing: Harald Kubota testing: Pascal Renauld open-iscsi-2.0.873/TODO000066400000000000000000000363351175631155400144560ustar00rootroot00000000000000iSCSI DEVELOPMENT HOWTO AND TODO -------------------------------- July 7th 2011 If you are admin or user and just want to send a fix, just send the fix any way you can. We can port the patch to the proper tree and fix up the patch for you. Engineers that would like to do more advanced development then the following guideline should be followed. Submitting Patches ------------------ Code should follow the Linux kernel codying style doc: http://www.kernel.org/doc/Documentation/CodingStyle Patches should be submitted to the open-iscsi list open-iscsi@googlegroups.com. They should be made with "git diff" or "diff -up" or "diff -uprN", and kernel patches must have a "Signed-off-by" line. See section 12 http://www.kernel.org/doc/Documentation/SubmittingPatches for more information on the the signed off line. Getting the Code ---------------- Kernel patches should be made against the linux-2.6-iscsi tree. This can be downloaded from kernel.org with git with the following commands: git clone git://git.kernel.org/pub/scm/linux/kernel/git/mnc/linux-2.6-iscsi.git Userspace patches should be made against the open-iscsi git tree: git clone git://git.kernel.org/pub/scm/linux/kernel/git/mnc/open-iscsi.git KERNEL TODO ITEMS ----------------- 1. Make iSCSI log messages humanly readable. In many cases the iscsi tools and modules will log a error number value. The most well known is conn error 1011. Users should not have to search on google for what this means. We should: 1. Write a simple table to convert the error values to a string and print them out. 2. Document the values, how you commonly hit them and common solutions in the iSCSI docs. See scsi_transport_iscsi.c:iscsi_conn_error_event for where the evil "detected conn error 1011" is printed. See the enum iscsi_err in iscsi_if.h for a definition of the error code values. --------------------------------------------------------------------------- 2. Implement iSCSI dev loss support. Currently if a session is down for longer than replacement/recovery_timeout seconds, the iscsi layer will unblock the devices and fail IO. Other transport, like FC and SAS, will do something similar. FC has a fast_io_fail tmo which will unblock devices and fail IO, then it has a dev_loss_tmo which will delete the devices accessed through that port. iSCSI needs to implement dev_loss_tmo behavior, because apps are beginning to expect this behavior. An initial path was made here: http://groups.google.com/group/open-iscsi/msg/031510ab4cecccfd?dmode=source Since all drivers want this behavior we want to make it common. We need to change the patch in that link to add a dev_loss_tmo handler callback to the scsi_transport_template struct, and add some common sysfs and helpers functions to manage the dev_loss_tmo variable. *Being worked on by Vikek S --------------------------------------------------------------------------- 3. Reduce locking contention between session lock. The session lock is basically one big lock that protects everything in the iscsi_session. This lock could be broken down into smaller locks and maybe even replaced with something that would not require a lock. For example: 1. The session lock serializes access to the current R2T the initiator is handling (a R2T from the target or the initialR2T if being used). libiscsi/ libiscsi_tcp will call iscsi_tcp_get_curr_r2t and grab the session lock in the xmit path from the xmit thread and then in the recv path libiscsi_tcp/iscsi_tcp will call iscsi_tcp_r2t_rsp (this function is called with the session lock held). We could add a new per iscsi_task lock and use that to gaurd the R2T. 2. For iscsi_tcp and cxgb*i, libiscsi uses the session->cmdqueue linked list and the session lock to queue IO from the queuecommand function (run from scsi softirq or kblockd context) to the iscsi xmit thread. Once the task is sent from that thread, it is deleted from the list. It seems we should be able to remove the linked list use here. The tasks are all preallocated in the session->cmds array. We can access that array and check the task->state (see fail_scsi_tasks for an example). We just need to come up with a way to safely set the task state, wake the xmit thread and make sure that tasks are executed in the order that the scsi layer sent them to our queuecommand function. A starting point on the queueing: We might be able to create a workqueue per processor, queue the work, which in this case is the execution of the task, from the queuecommand, then rely on the work queue synchronization and serialization code. Not 100% sure about this. Alternative to changing the threading: Can we figure out a way to just remove the xmit thread? We currently cannot because the network may only be able to send 1000 bytes, but to send the current command we need to send 2000. We cannot sleep from the queuecommand context until another 1000 bytes frees up and for iscsi_tcp we cannot sleep from the recv conext (this happens because we could have got a R2T from target and are handling it from the recv path). Note: that for iser and offload drivers like bnx2i and be2iscsi their is no xmit thread used. Note2: cxgb*i does not actually need the xmit thread so a side project could be to convert that driver. --------------------------------------------------------------------------- 4. Make memory access more efficient on multi-processor machines. We are moving twords per process queues in the block layer, so it would be a good idea to move the iscsi structs to be allocated on a per process basis. --------------------------------------------------------------------------- 5. Make blk_iopoll support (see block/blk-iopoll.c and be2iscsi for an example) being able to round robin IO across processors or complete on the processor it was queued on (today it always completes the IO on the processor the softirq was raised on), and convert bnx2i, ib_iser and cxgb*i to it. Not sure if it will help iscsi_tcp and cxgb, because their completion is done from the network softirq which does polling already. With irq balancing it can also be spread over all processors too. --------------------------------------------------------------------------- 7. When userspace calls into the kernel using the iscsi netlink interface to execute oprations like creating/destroying a session, create a connection to a target, etc the rx_queue_mutex is held the entire time (see iscsi_if_rx for the iscsi netlink interface entry point). This means if the driver should block every thing will be held up. iscsi_tcp does not block, but some offload drivers might for a couple seconds to 10 or 15 secs while it figures out what is going on or cleans up. This a major problem for things like multipath where one connection blocking up the recovery of every other connection will delay IO from re-flowing quickly. We should looking into breaking up the rx_queue_mutex into finer grained locks or making it multi threaded. For the latter we could queue operations into workqueues. --------------------------------------------------------------------------- 7. Add tracing support to iscsi modules. See the scsi layer's trace_scsi_dispatch_cmd_start for an example. Well, actually in general look into all the tracing stuff available (trace_printk/ftrace, etc) and use one. See http://lwn.net/Articles/291091/ for some details on what is out there. We can only use something that is upstream though. --------------------------------------------------------------------------- 8. Improve the iscsi driver logging. Each driver has a different way to control logging. We should unify them and make it managable by iscsiadm. So each driver would use a common format, there would be a common kernel interface to set the logging level, etc. --------------------------------------------------------------------------- 9. Implement more features from the iSCSI RFC if they are worth it. - Error Recovery Level (ERL) 1 support - will help tape support. - Multi R2T support - Might improve write performance. - OutOfOrder support - Might imrpove performance. --------------------------------------------------------------------------- 10. Add support for digest/CRC offload. --------------------------------------------------------------------------- 11. Finish intel IOAT support. I started this here: http://groups.google.com/group/open-iscsi/msg/2626b8606edbe690?dmode=source but could only test on boxes with 1 gig interfaces which showed no difference in performance. Intel had said they saw significant throughput gains when using 10 gig. --------------------------------------------------------------------------- 12. Remove the login buffer preallocated buffer. Storage drivers must be able to make forward process, so that they can always write out a page incase the kernel needs to allocate the page to another process. If the connection were to be disconnected and the initiator needed to relogin to the target at this time, we might not be abe to allocate a page for the login commands buffer. To work around the problem the initiator prealloctes a 8K (sometimes more depending on the page size) buffer for each session (see iscsi_conn_setup' s __get_free_pages call). This is obviously very wasteful since it will be a rate occurance. Can we think of a way to allow multiple sessions to be relogged in at the same time, but not have to preallocate so many buffers? --------------------------------------------------------------------------- 13. Support iSCSI over swap safely. Basically just need to hook iscsi_tcp into the patches that were submitted here for NBD. https://lwn.net/Articles/446831/ --------------------------------------------------------------------------- USERSPACE TODO ITEMS -------------------- 1. The iscsi tools, iscsid, iscsiadm and iscsid, have a debug flag, -d N, that allows the user to control the amount of output that is logged. The argument N is a integer from 1 to 8, with 8 printing out the most output. The problem is that the values from 1 to 8 do not really mean much. It would helpful if we could replace them with something that controls what exactly the iscsi tools and kernel modules log. For example, if we made the debug level argument a bitmap then iscsiadm -m node --login -d LOGIN_ERRS,PDUS,FUNCTION might print out extended iscsi login error information (LOGIN_ERRS), the iSCSI packets that were sent/receieved (PDUS), and the functions that were run (FUNCTION). Note, the use of a bitmapp and the debug levels are just an example. Feel free to do something else. We would want to be able to have iscsiadm control the iscsi kernel logging as well. There are interfaces like /sys/module/libiscsi/paramters/*debug* /sys/module/libiscsi_tcp/paramters/*debug* /sys/module/iscsi_tcp/paramters/*debug* /sys/module/scsi_transport_iscsi/paramters/*debug* but we would want to extend the debugging options to be finer grained and we would want to make it supportable by all iscsi drivers. (see #8 on the kernel todo). --------------------------------------------------------------------------- 2. "iscsiadm -m session -P 3" can print out a lot of information about the session, but not all configuration values are printed. iscsiadm should be modified to print out other settings like timeouts, Chap settings, the iSCSI values that were requested vs negotiated for, etc. --------------------------------------------------------------------------- 3. iscsiadm cannot update a setting of a running session. If you want to change a timeout you have to run the iscsiadm logout command, then update the record value, then login: iscsiadm -m node -T target -p ip -u iscsidm -m node -T target -p ip -o update -n node.session.timeo.replacement_timeout -v 30 iscsiadm -m node -T target -p ip -l iscsiadm should be modified to allow updating of a setting without having to run the iscsiadm command. Note that for some settings like iSCSI ones (ImmediateData, FirstBurstLength, etc) that must be negotiated with the target we will have to logout the target then re-login, but we should not have to completely destroy the session and scsi devices like is done when running the iscsiadm logout command. We should be able to pass iscsid the new values and then have iscsid logout and relogin. Other settings like the abort timeout will not need a logout/login. We can just pass those to the kernel or iscsid to use. *Being worked on by Tomoaki Nishimura --------------------------------------------------------------------------- 4. iscsiadm will attempt to perform logins/logouts in parallel. Running iscsiadm -m node -L, will cause iscsiadm to login to all portals with the startup=automatic field set at the same time. To log into a target, iscsiadm opens a socket to iscsid, sends iscsid a request to login to a target, iscsid performs the iSCSI login operation, then iscsid sends iscsiadm a reply. To perform multiple logins iscsiadm will open a socket for each login request, then wait for a reply. This is a problem because for 1000s of targets we will have 1000s of sockets open. There is a rlimit to control how many files a process can have open and iscsiadm currently runs setrlimit to increase this. With users creating lots of virtual iscsi interfaces on the target and initiator with each having multiple paths it beomes inefficient to open a socket for each requests. At the very least we want to handle setrlimit RLIMIT_NOFILE limit better, and it would be best to just stop openening a socket per login request. --------------------------------------------------------------------------- 6. Implement broadcast/multicasts support, so the initiator can find iSNS servers without the user having to set the iSNS server address. See 5.6.5.14. Name Service Heartbeat (Heartbeat) in http://tools.ietf.org/html//rfc4171 --------------------------------------------------------------------------- 7. Open-iscsi uses the open-isns iSNS library. The library might be a little too complicated and a little too heavy for what we need. Investigate replacing it. Also explore merging the open-isns and linux-isns projects, so we do not have to support multiple isns clients/servers in linux. --------------------------------------------------------------------------- 8. Implement the DHCP iSNS option support, so we the initiator can find the iSNS sever without the user having to set the iSNS server address. See: http://www.ietf.org/rfc/rfc4174.txt --------------------------------------------------------------------------- 9. Some iscsiadm/iscsid operations that access the iscsi DB and sysfs can be up to Big O(N^2). Some of the code was written when we thought 64 sessions would be a lot and the norm would be 4 or 8. Due to virtualization, cloud use, and targets like equallogic that do a target per logical unit (device) we can see 1000s of sessions. - We should look into making the record DB more efficient. Maybe time to use a real DB (something small simple and efficient since this needs to run in places like the initramfs). - Rewrite code to look up a running session so we do not have loop over every session in sysfs. --------------------------------------------------------------------------- 10. Look into using udev's libudev for our sysfs access in iscsiadm/iscsid/ iscsistart. --------------------------------------------------------------------------- 11. iSCSI lib. I am working on this one. Hopefully it should be done soon. --------------------------------------------------------------------------- open-iscsi-2.0.873/debian/000077500000000000000000000000001175631155400151765ustar00rootroot00000000000000open-iscsi-2.0.873/debian/README.Debian000066400000000000000000000035251175631155400172440ustar00rootroot00000000000000linux-iscsi for Debian ----------------------------------- The linux-iscsi package contains the userspace portion the Linux iSCSI project. It has a dependency on the linux-iscsi-modules package, which needs to be built from the linux-iscsi-modules-source against the specific kernel version running on your system. Building -------- Modules cannot be built against the kernel-headers alone. You will need to extract and configure your kernel tree, then use the make-kpkg command (from the kernel-package package) to build a new kernel and modules. See the make-kpkg man page, particularly the modules-image section. The following example shows how to build the linux-iscsi-modules package; just substitute the appropriate version strings. Follow these instructions (as root) in order to build the linux-iscsi-modules package for your kernel: dpkg -i linux-iscsi-modules-source_5.0.0.0.3rc6-363_all.deb cd /usr/src rm -rf modules/linux-iscsi tar jxpvf linux-iscsi-modules-source.tar.bz2 cd linux-2.6.11.11 (or your appropriate version) make-kpkg --added-modules linux-iscsi modules-image By default, make-kpkg will assume /usr/src/linux-iscsi-modules-source.tar.bz2 has been extracted under /usr/src. However, that also requires building as root. If you want to do the build as a non-root user, you need to use the MODULE_LOC environment variable. For example: cd ~/builds export MODULES_LOC=$PWD/modules tar jxpvf /usr/src/linux-iscsi-modules-source.tar.bz2 cd ~/builds/linux-2.6.11.11 (or your appropriate version) make-kpkg --added-modules linux-iscsi modules-image Installing ---------- Once you have built the linux-iscsi-modules package, you can install the binaries: dpkg -i linux-iscsi_5.0.0.0.3rc6-363_i386.deb linux-iscsi-modules-2.6.11.11_5.0.0.0.3rc6-363+10.00.Custom_i386.deb -- Chad Tindel , Mon, 30 May 2005 15:17:53 -0600 open-iscsi-2.0.873/debian/changelog000066400000000000000000000002231175631155400170450ustar00rootroot00000000000000linux-iscsi (5.0.0.0.3rc6-363) unstable; urgency=low * Initial Release. -- Chad Tindel Mon, 30 May 2005 15:17:53 -0600 open-iscsi-2.0.873/debian/compat000066400000000000000000000000021175631155400163740ustar00rootroot000000000000004 open-iscsi-2.0.873/debian/control000066400000000000000000000016711175631155400166060ustar00rootroot00000000000000Source: linux-iscsi Section: net Priority: optional Maintainer: Chad Tindel Build-Depends: debhelper (>= 4.0.0), libdb4.3, libdb4.3-dev Standards-Version: 3.6.1 Package: linux-iscsi Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, linux-iscsi-modules Description: high performance, transport independent implementation of RFC3720. linux-iscsi is a high performance, transport independent, implementation of RFC3720. #Package: linux-iscsi #Architecture: all #Description: Documentation for linux-iscsi #linux-iscsi is a high performance, transport independent, implementation of #RFC3720. Package: linux-iscsi-modules-source Architecture: all Depends: ${shlibs:Depends}, ${misc:Depends}, module-assistant, debhelper (>= 4.0.0), bzip2 Description: Source Code for the Linux iSCSI Kernel Modules Along with make-kpkg, this package maybe used to build a linux-iscsi-modules package for a kernel-image package. open-iscsi-2.0.873/debian/control.modules.in000066400000000000000000000013641175631155400206610ustar00rootroot00000000000000Source: linux-iscsi-modules Section: net Priority: optional Maintainer: Chad Tindel Build-Depends: debhelper (>> 4.1.0), bzip2 Standards-Version: 3.6.1 Package: linux-iscsi-modules-_KVERS_ Architecture: any Depends: modutils, linux-iscsi Provides: linux-iscsi-modules Description: Linux Kernel Driver Modules for Linux iSCSI (kernel _KVERS_) This is a Linux driver for iSCSI initiator functionality. . This package contains the compiled kernel modules for _KVERS_ . If you have compiled your own kernel, you will most likely need to build your own linux-iscsi-modules. The linux-iscsi-source package has been provided for use with the Debian kernel-package utility to produce a version of linux-iscsi-module for your kernel. open-iscsi-2.0.873/debian/copyright000066400000000000000000000007111175631155400171300ustar00rootroot00000000000000This package was debianized by Chad Tindel on Mon, 30 May 2005 15:17:53 -0600. It was downloaded from http://sourceforge.net/projects/linux-iscsi Copyright Holder: Dmitry Yusupov License: You are free to distribute this software under the terms of the GNU General Public License. On Debian systems, the complete text of the GNU General Public License can be found in the file `/usr/share/common-licenses/GPL'. open-iscsi-2.0.873/debian/dirs000066400000000000000000000000341175631155400160570ustar00rootroot00000000000000usr/bin usr/sbin etc/init.d open-iscsi-2.0.873/debian/docs000066400000000000000000000000331175631155400160450ustar00rootroot00000000000000README COPYING THANKS TODO open-iscsi-2.0.873/debian/postinst.modules.in000066400000000000000000000002161175631155400210570ustar00rootroot00000000000000#!/bin/sh set -e if [ "`uname -r`" = "_KVERS_" ]; then /sbin/depmod -a & fi #DEBHELPER# exit 0 open-iscsi-2.0.873/debian/rules000066400000000000000000000074621175631155400162640ustar00rootroot00000000000000#!/usr/bin/make -f # -*- makefile -*- # Sample debian/rules that uses debhelper. # # This file was originally written by Joey Hess and Craig Small. # As a special exception, when this file is copied by dh-make into a # dh-make output file, you may use that output file without restriction. # This special exception was added by Craig Small in version 0.37 of dh-make. # # Modified to make a template file for a multi-binary package with separated # build-arch and build-indep targets by Bill Allombert 2001 # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 # This has to be exported to make some magic below work. export DH_OPTIONS CFLAGS = -Wall -g ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) CFLAGS += -O0 else CFLAGS += -O2 endif configure: configure-stamp configure-stamp: dh_testdir # Add here commands to configure the package. touch configure-stamp #Architecture build: build-arch build-indep build-arch: build-arch-stamp build-arch-stamp: configure-stamp # Add here commands to compile the arch part of the package. $(MAKE) -C usr touch build-arch-stamp build-indep: build-indep-stamp build-indep-stamp: configure-stamp # Add here commands to compile the indep part of the package. #$(MAKE) doc touch build-indep-stamp clean: dh_testdir dh_testroot rm -f build-arch-stamp build-indep-stamp #CONFIGURE-STAMP# # Add here commands to clean up after the build process. $(MAKE) -C usr clean rm -rf modules dh_clean install: install-indep install-arch install-indep: dh_testdir dh_testroot dh_clean -k -i dh_installdirs -i # create needed directories dh_installdirs -i usr/src/modules/linux-iscsi mkdir -p modules/linux-iscsi/debian # copy the driver source tar --exclude=debian -c * | (cd modules/linux-iscsi && tar xv) # copy all relevant debian/ files cp debian/{compat,copyright} modules/linux-iscsi/debian cat debian/changelog | sed -e 's/linux-iscsi/linux-iscsi-modules/' > modules/linux-iscsi/debian/changelog cp debian/*.modules.in modules/linux-iscsi/debian install -m755 debian/rules.modules modules/linux-iscsi/debian/rules # entar the source tar jcf debian/linux-iscsi-modules-source/usr/src/linux-iscsi-modules-source.tar.bz2 modules # Add here commands to install the indep part of the package into # debian/-doc. #INSTALLDOC# dh_install -i install-arch: dh_testdir dh_testroot dh_clean -k -s dh_installdirs -s # Add here commands to install the arch part of the package into # debian/linux-iscsi. install -m 755 usr/iscsiadm $(CURDIR)/debian/linux-iscsi/usr/bin install -m 755 usr/iscsid $(CURDIR)/debian/linux-iscsi/usr/sbin install -m 644 etc/iscsid.conf $(CURDIR)/debian/linux-iscsi/etc/iscsid.conf.example install -m 755 etc/initd/initd.debian $(CURDIR)/debian/linux-iscsi/etc/init.d/iscsid make clean dh_install -s # Must not depend on anything. This is to be called by # binary-arch/binary-indep # in another 'make' thread. binary-common: dh_testdir dh_testroot dh_installchangelogs dh_installdocs dh_installexamples # dh_installmenu # dh_installdebconf # dh_installlogrotate # dh_installemacsen # dh_installpam # dh_installmime # dh_installinit # dh_installcron # dh_installinfo dh_installman dh_link dh_strip dh_compress dh_fixperms # dh_perl # dh_python dh_makeshlibs dh_installdeb dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb # Build architecture independant packages using the common target. binary-indep: build-indep install-indep $(MAKE) -f debian/rules DH_OPTIONS=-i binary-common # Build architecture dependant packages using the common target. binary-arch: build-arch install-arch $(MAKE) -f debian/rules DH_OPTIONS=-a binary-common binary: binary-arch binary-indep .PHONY: build clean binary-indep binary-arch binary install install-indep install-arch configure open-iscsi-2.0.873/debian/rules.modules000066400000000000000000000016751175631155400177330ustar00rootroot00000000000000#!/usr/bin/make -f # module-assistant stuff PACKAGE = linux-iscsi-modules MA_DIR ?= /usr/share/modass -include $(MA_DIR)/include/generic.make -include $(MA_DIR)/include/common-rules.make kdist_clean: prep-deb-files dh_clean #$(MAKE) clean KERNEL_PATH=$(KSRC) make clean kdist_config: prep-deb-files TARGET = $(CURDIR)/debian/linux-iscsi-modules-$(KVERS) MODULES_TARGET = $(TARGET)/lib/modules/$(KVERS)/kernel/net/iscsi binary-modules: kdist_config dh_testdir dh_testroot dh_clean -k dh_installdirs lib/modules/$(KVERS) # build and install the module patch -d kernel < kernel/backward-compile-2.6.11.patch make -C kernel KSRC=$(KSRC) mkdir -p $(MODULES_TARGET) install -m 755 kernel/iscsi_tcp.ko $(MODULES_TARGET) install -m 755 kernel/scsi_transport_iscsi.ko $(MODULES_TARGET) dh_installdocs dh_installchangelogs dh_compress dh_fixperms dh_installdeb dh_gencontrol -- -v$(VERSION) dh_md5sums dh_builddeb --destdir=$(DEB_DESTDIR) open-iscsi-2.0.873/doc/000077500000000000000000000000001175631155400145215ustar00rootroot00000000000000open-iscsi-2.0.873/doc/iscsi-iname.8000066400000000000000000000007651175631155400170230ustar00rootroot00000000000000.TH ISCSI_INAME 8 "Jan 2010" "" "Linux Administrator's Manual" .SH NAME iscsi-iname \- iSCSI initiator name generation tool .SH SYNOPSIS .BI iscsi-iname [OPTION] .SH "DESCRIPTION" .B iscsi-iname generates a unique iSCSI node name on every invocation. .SH OPTIONS .TP .BI [-h|--help] Display help .TP .BI [-p=]\fIprefix\fP Use the prefix passed in instead of the default "iqn.2005-03.org.open-iscsi" .SH AUTHORS Open-iSCSI project .br Mike Christie open-iscsi-2.0.873/doc/iscsi_discovery.8000066400000000000000000000026421175631155400200170ustar00rootroot00000000000000.de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .TH "iscsi_discovery" 8 .SH NAME iscsi_discovery \- discover iSCSI targets .SH SYNOPSIS .B iscsi_discovery [-p ] [-d] [-t [-f]] [-m] [-l] .SH DESCRIPTION Perform send-targets discovery to the specified IP. If a discovery record is generated, try to login to the portal using the preferred transport (\-t flag specifies the requested transport type, TCP is the default). If login using a certain transport succeeds, mark the portal for automatic login (unless \-m flag is used), and disconnect (unless \-l flag is used). For iSCSI discovery to work, open-iscsi services must be running. i.e. iscsid should be up, and the iSCSI modules loaded. This is best accomplished by the init.d startup script. .\" .SH OPTIONS .TP .BI [-p=]\fIport\-number\fP set the port number (defualt is 3260). .TP .BI [-d] print debugging information. .TP .BI [-t=]\fItransport\-type\fP set transport (default is tcp). .TP .BI [-f] force specific transport - disable the fallback to tcp (default is fallback enabled). force the transport specified by the argument of the \-t flag. .TP .BI [-m] manual startup - will set manual startup (default is automatic startup). .TP .BI [-l] login - login to the new discovered nodes (defualt is false). .SH AUTHOR Written by Dan Bar Dov .SH "REPORTING BUGS" Report bugs to . .SH COPYRIGHT Copyright \(co Voltaire Ltd. 2006. open-iscsi-2.0.873/doc/iscsiadm.8000066400000000000000000000420761175631155400164170ustar00rootroot00000000000000.TH ISCSIADM 8 "Sep 2006" "" "Linux Administrator's Manual" .SH NAME iscsiadm \- open-iscsi administration utility .SH SYNOPSIS \fBiscsiadm\fR \-m discoverydb [ \-hV ] [ \-d debug_level ] [ \-P printlevel ] [ \-I iface \-t type \-p ip:port [ \-lD ] ] | [ [ -p ip:port -t type ] \ [ \-o operation ] [ \-n name ] [ \-v value ] [ \-lD ] ] \fBiscsiadm\fR \-m discovery [ \-hV ] [ \-d debug_level ] [ \-P printlevel ] [ \-I iface \-t type \-p ip:port [ \-l ] ] | [ [ -p ip:port ] [ \-l | \-D ] ] \fBiscsiadm\fR \-m node [ \-hV ] [ \-d debug_level ] [ \-P printlevel ] [ \-L all,manual,automatic ] [ \-U all,manual,automatic ] [ \-S ] [ [ \-T targetname \-p ip:port \-I iface ] [ \-l | \-u | \-R | \-s] ] [ [ \-o operation ] [ \-n name ] [ \-v value ] [ \-p ip:port ] ] \fBiscsiadm\fR \-m session [ \-hV ] [ \-d debug_level ] [ \-P printlevel ] [ \-r sessionid | sysfsdir [ \-R ] [ \-u | \-s | \-o new ] ] \fBiscsiadm\fR \-m iface [ \-hV ] [ \-d debug_level ] [ \-P printlevel ] [ \-I ifacename | \-H hostno|MAC ] [ [ \-o operation ] [ \-n name ] [ \-v value ] ] [ \-C ping [ \-a ip ] [ \-b packetsize ] [ \-c count ] [ \-i interval ] ] \fBiscsiadm\fR \-m fw [\-l] \fBiscsiadm\fR \-m host [ \-P printlevel ] [ \-H hostno|MAC ] [ -C chap [ -o operation ] [ -v chap_tbl_idx ] ] \fBiscsiadm\fR \-k priority .SH "DESCRIPTION" The iscsiadm utility is a command-line tool allowing discovery and login to iSCSI targets, as well as access and management of the open-iscsi database. Open-iscsi does not use the term node as defined by the iSCSI RFC, where a node is a single iSCSI initiator or target. Open-iscsi uses the term node to refer to a portal on a target. For session mode, a session id (sid) is used. The sid of a session can be found by running iscsiadm \-m session \-P 1. The session id and sysfs path are not currently persistent and is partially determined by when the session is setup. .PP Note that many of the node and discovery operations require that the iSCSI daemon (iscsid) be running. .SH OPTIONS .TP \fB\-a\fR, \fB\-\-ip=\fIipaddr\fP \fIipaddr\fR can be IPv4 or IPv6. This option is only valid for ping submode. .TP \fB\-b\fR, \fB\-\-packetsize=\fIpacketsize\fP Specify the ping \fIpacketsize\fR. This option is only valid for ping submode. .TP \fB\-c\fR, \fB\-\-count=\fIcount\fP \fIcount\fR specify number of ping iterations. This option is only valid for ping submode. .TP \fB\-C\fR, \fB\-\-submode=\fIop\fP Specify the submode for mode. op must be name of submode. Currently iscsiadm support ping as submode for iface. For example, iscsiadm -m iface -I ifacename -C ping -a ipaddr -b packetsize -c count -i interval .TP \fB\-d\fR, \fB\-\-debug=\fIdebug_level\fP print debugging information. Valid values for debug_level are 0 to 8. .TP \fB\-h\fR, \fB\-\-help\fR display help text and exit .TP \fB\-H\fR, \fB\-\-host=\fI[hostno|MAC]\fR The host agrument specifies the SCSI host to use for the operation. It can be the scsi host number assigned to the host by the kernel's scsi layer, or the MAC address of a scsi host. .TP \fB\-i\fR, \fB\-\-interval=\fIinterval\fP \fIinterval\fP specify delay between two ping iterations. This option is only valid for ping submode. .TP \fB\-I\fR, \fB\-\-interface=\fI[iface]\fR The interface argument specifies the iSCSI interface to use for the operation. iSCSI interfaces (iface) are defined in /etc/iscsi/ifaces. For hardware iSCSI (qla4xxx) the iface config must have the hardware address (iface.hwaddress = port's MAC address) and the driver/transport_name (iface.transport_name). The iface's name is then the filename of the iface config. For software iSCSI, the iface config must have either the hardware address (iface.hwaddress), or the network layer's interface name (iface.net_ifacename), and it must have the driver/transport_name The available drivers/iscsi_transports are tcp (software iSCSI over TCP/IP), iser (software iSCSI over infinniband), or qla4xxx (Qlogic 4XXXX HBAs). The hwaddress is the MAC address or for software iSCSI it may be the special value "default" which directs the initiator to not bind the session to a specific hardware resource and instead allow the network or infinniband layer to decide what to do. There is no need to create a iface config with the default behavior. If you do not specify a iface, then the default behavior is used. As mentioned above there is a special iface name default. There are three others -- cxgb3i, bnx2i and iser, which does not bind the session to a specific card, but will bind the session to the cxgb3i, bnx2i or iser transport. These are experimental and the use is not supported as a stable interface yet. In discovery mode multiple interfaces can be specified by passing in multiple \-I/\-\-interface instances. For example, "iscsiadm \-m discoverydb \-t st \-p ip:port \-I iface0 \-I iface2 --discover" Will direct iscsiadm to setup the node db to create records which will create sessions though the two intefaces passed in. In node mode, only a single interface is supported in each call to iscsiadm. .IP This option is valid for discovery, node and iface mode. .TP \fB\-k\fR, \fB\-\-killiscsid=\fI[priority]\fR Currently priority must be zero. This will immediately stop all iscsid operations and shutdown iscsid. It does not logout any sessions. Running this command is the same as doing "killall iscsid". Neither should normally not be used, because if iscsid is doing error recovery or if there is an error while iscsid is not running, the system may not be able to recover. This command and iscsid's SIGTERM handling are experimental. .TP \fB\-D\fR, \fB\-\-discover\fR Discover targets using the discovery record with the \fIrecid\fR matching the the discovery type and portal passed in. If there is no matching record, it will be created using the iscsid.conf discovery settings. This must be passed in \fIdiscoverydb\fR mode to instruct iscsiadm to perform discovery. .IP This option is only valid for SendTargets discovery mode. .TP \fB\-l\fR, \fB\-\-login\fR For node and fw mode, login to a specified record. For discovery mode, login to all discovered targets. .IP This option is only valid for discovery and node modes. .TP \fB\-L\fR, \fB\-\-loginall==\fI[all|manual|automatic]\fR For node mode, login all sessions with the node or conn startup values passed in or all running sesssion, except ones marked onboot, if all is passed in. .IP This option is only valid for node mode (it is valid but not functional for session mode). .TP \fB\-m, \-\-mode \fIop\fR specify the mode. \fIop\fR must be one of \fIdiscoverydb\fR, \fInode\fR, \fIfw\fR, \fIhost\fR \fIiface\fR or \fIsession\fR. .IP If no other options are specified: for \fIdiscoverydb\fR and \fInode\fR, all of their respective records are displayed; for \fIsession\fR, all active sessions and connections are displayed; for \fIfw\fR, all boot firmware values are displayed; for \fIhost\fR, all iSCSI hosts are displayed; and for \fIiface\fR, all ifaces setup in /etc/iscsi/ifaces are displayed. .TP \fB\-n\fR, \fB\-\-name=\fIname\fR Specify a field \fIname\fR in a record. For use with the \fIupdate\fR operator. .IP .TP \fB\-o\fR, \fB\-\-op=\fIop\fR Specifies a database operator \fIop\fR. \fIop\fR must be one of \fInew\fR, \fIdelete\fR, \fIupdate\fR, \fIshow\fR or \fInonpersistent\fR. .IP For iface mode, \fIapply\fR and \fIapplyall\fR are also applicable. .IP This option is valid for all modes except fw. Delete should not be used on a running session. If it is iscsiadm will stop the session and then delete the record. .IP \fInew\fR creates a new database record for a given object. In node mode, the \fIrecid\fR is the target name and portal (IP:port). In iface mode, the \fIrecid\fR is the iface name. In discovery mode, the \fIrecid\fR is the portal and discovery type. .IP In session mode, the \fInew\fR operation logs in a new session using the same node database and iface information as the specified session. .IP In discovery mode, if the \fIrecid\fR and new operation is passed in, but the \fI--discover\fR argument is not, then iscsiadm will only create a discovery record (it will not perform discovery). If the \fI--discover\fR argument is passed in with the portal and discovery type, then iscsiadm will create the discovery record if needed, and it will create records for portals returned by the target that do not yet have a node DB record. .IP \fIdelete\fR deletes a specified \fIrecid\fR. In discovery node, if iscsiadm is performing discovery it will delete records for portals that are no longer returned. .IP \fIupdate\fR will update the \fIrecid\fR with \fIname\fR to the specified \fIvalue\fR. In discovery node, if iscsiadm is performing discovery the \fIrecid\fR, \fIname\fR and \fIvalue\fR arguments are not needed. The update operation will operate on the portals returned by the target, and will update the node records with info from the config file and command line. .IP \fIshow\fR is the default behaviour for node, discovery and iface mode. It is also used when there are no commands passed into session mode and a running sid is passed in. \fIname\fR and \fIvalue\fR are currently ignored when used with \fIshow\fR. .IP \fInonpersistent\fR instructs iscsiadm to not manipulate the node DB. .IP \fIapply\fR will cause the network settings to take effect on the specified iface. .IP \fIapplyall\fR will cause the network settings to take effect on all the ifaces whose MAC address or host number matches that of the specific host. .TP \fB\-p\fR, \fB\-\-portal=\fIip[:port]\fR Use target portal with ip-address \fIip\fR and \fIport\fR. If port is not passed in the default \fIport\fR value is 3260. .IP IPv6 addresses can bs specified as [ddd.ddd.ddd.ddd]:port or ddd.ddd.ddd.ddd. .IP Hostnames can also be used for the ip argument. .IP This option is only valid for discovery, or for node operations with the \fInew\fR operator. .IP This should be used along with \-\-target in node mode, to specify what the open-iscsi docs refer to as a node or node record. Note: open-iscsi's use of the word node, does not match the iSCSI RFC's iSCSI Node term. .TP \fB\-P\fR, \fB\-\-print=\fIprintlevel\fR If in node mode print nodes in tree format. If in session mode print sessions in tree format. If in discovery mode print the nodes in tree format. .TP \fB\-T\fR, \fB\-\-targetname=\fItargetname\fR Use target \fItargetname\fR. .IP This should be used along with \-\-portal in node mode, to specify what the open-iscsi docs refer to as a node or node record. Note: open-iscsi's use of the word node, does not match the iSCSI RFC's iSCSI Node term. .TP \fB\-r\fR, \fB\-\-sid=\fIsid | sysfsdir\fR Use session ID \fIsid\fR. The sid of a session can be found from running iscsiadm in session mode with the \-\-info argument. Instead of sid, a sysfs path containing the session can be used. For example using one of the following: /sys/devices/platform/hostH/sessionS/targetH:B:I/H:B:I:L, /sys/devices/platform/hostH/sessionS/targetH:B:I, or /sys/devices/platform/hostH/sessionS, for the sysfsdir argument would result in the session with sid S to be used. .IP \fIsid | sysfsdir\fR is only required for session mode. .TP \fB\-R\fR, \fB\-\-rescan\fR In session mode, if sid is also passed in rescan the session. If no sid has been passed in rescan all running sessions. In node mode, rescan a session running through the target, portal, iface tuple passed in. .TP \fB\-s\fR, \fB\-\-stats\fR Display session statistics. .TP \fB\-S\fR, \fB\-\-show\fR When displaying records, do not hide masked values, such as the CHAP secret (password). .IP This option is only valid for node and session mode. .TP \fB\-t\fR, \fB\-\-type=\fItype\fR \fItype\fR must be \fIsendtargets\fR (or abbreviated as \fIst\fR), \fIslp\fR, \fIisns\fR or \fIfw\fR. Currently only sendtargets, fw, and iSNS is supported, see the DISCOVERY TYPES section. .IP This option is only valid for discovery mode. .TP \fB\-u\fR, \fB\-\-logout\fR logout for a specified record. .IP This option is only valid for node and session mode. .TP \fB\-U\fR, \fB\-\-logoutall==\fI[all,manual,automatic]\fR logout all sessions with the node or conn startup values passed in or all running sesssion, except ones marked onboot, if all is passed in. .IP This option is only valid for node mode (it is valid but not functional for session mode). .TP \fB\-v\fR, \fB\-\-value=\fIvalue\fR Specify a \fIvalue\fR for use with the \fIupdate\fR operator. .IP This option is only valid for node mode. .TP \fB\-V\fR, \fB\-\-version\fR display version and exit .SH DISCOVERY TYPES iSCSI defines 3 discovery types: SendTargets, SLP, and iSNS. .TP .B SendTargets A native iSCSI protocol which allows each iSCSI target to send a list of available targets to the initiator. .TP .B SLP Optionally an iSCSI target can use the Service Location Protocol (SLP) to announce the available targets. The initiator can either implement SLP queries directly or can use a separate tool to acquire the information about available targets. .TP .B iSNS iSNS (Internet Storage Name Service) records information about storage volumes within a larger network. To utilize iSNS, pass the address and optionally the port of the iSNS server to do discovery to. .TP .B fw Several NICs and systems contain a mini iSCSI initiator which can be used for boot. To get the values used for boot the fw option can be used. Doing fw discovery, does not store persistent records in the node or discovery DB, because the values are stored in the system's or NIC's resource. Performing fw discovery will print the portals, like with other discovery methods. To see other settings like CHAP values and initiator settings, like you would in node mode, run "iscsiadm \-m fw". fw support in open-iscsi is experimental. The settings and iscsiadm syntax and output format may change. .P iscsiadm supports the .B iSNS (isns) or .B SendTargets (st) discovery type. An SLP implementation is under development. .SH EXIT STATUS On success 0 is returned. On error one of the return codes below will be returned. Commands that operation on multiple objects (sessions, records, etc), iscsiadm/iscsistart will return the first error that is encountered. iscsiadm/iscsistart will attempt to execute the operation on the objects it can. If no objects are found ISCSI_ERR_NO_OBJS_FOUND is returned. .TP .B 0 ISCSI_SUCCESS - command executed successfully. .TP .B 1 ISCSI_ERR - generic error code. .TP .B 2 ISCSI_ERR_SESS_NOT_FOUND - session could not be found. .TP .B 3 ISCSI_ERR_NOMEM - could not allocate resource for operation. .TP .B 4 ISCSI_ERR_TRANS - connect problem caused operation to fail. .TP .B 5 ISCSI_ERR_LOGIN - generic iSCSI login failure. .TP .B 6 ISCSI_ERR_IDBM - error accessing/managing iSCSI DB. .TP .B 7 ISCSI_ERR_INVAL - invalid argument. .TP .B 8 ISCSI_ERR_TRANS_TIMEOUT - connection timer exired while trying to connect. .TP .B 9 ISCSI_ERR_INTERNAL - generic internal iscsid/kernel failure. .TP .B 10 ISCSI_ERR_LOGOUT - iSCSI logout failed. .TP .B 11 ISCSI_ERR_PDU_TIMEOUT - iSCSI PDU timedout. .TP .B 12 ISCSI_ERR_TRANS_NOT_FOUND - iSCSI transport module not loaded in kernel or iscsid. .TP .B 13 ISCSI_ERR_ACCESS - did not have proper OS permissions to access iscsid or execute iscsiadm command. .TP .B 14 ISCSI_ERR_TRANS_CAPS - transport module did not support operation. .TP .B 15 ISCSI_ERR_SESS_EXISTS - session is logged in. .TP .B 16 ISCSI_ERR_INVALID_MGMT_REQ - invalid IPC MGMT request. .TP .B 17 ISCSI_ERR_ISNS_UNAVAILABLE - iSNS service is not supported. .TP .B 18 ISCSI_ERR_ISCSID_COMM_ERR - a read/write to iscsid failed. .TP .B 19 ISCSI_ERR_FATAL_LOGIN - fatal iSCSI login error. .TP .B 20 ISCSI_ERR_ISCSID_NOTCONN - could ont connect to iscsid. .TP .B 21 ISCSI_ERR_NO_OBJS_FOUND - no records/targets/sessions/portals found to execute operation on. .TP .B 22 ISCSI_ERR_SYSFS_LOOKUP - could not lookup object in sysfs. .TP .B 23 ISCSI_ERR_HOST_NOT_FOUND - could not lookup host. .TP .B 24 ISCSI_ERR_LOGIN_AUTH_FAILED - login failed due to authorization failure. .TP .B 25 ISCSI_ERR_ISNS_QUERY - iSNS query failure. .TP .B 26 ISCSI_ERR_ISNS_REG_FAILED - iSNS registration/deregistration failed. .SH EXAMPLES .nf Discover targets at a given IP address: .ft R iscsiadm \-\-mode discoverydb \-\-type sendtargets \-\-portal 192.168.1.10 \-\-discover .nf Login, must use a node record id found by the discovery: .ft R iscsiadm \-\-mode node \-\-targetname iqn.2001-05.com.doe:test \-\-portal 192.168.1.1:3260 \-\-login .nf Logout: .ft R iscsiadm \-\-mode node \-\-targetname iqn.2001-05.com.doe:test \-\-portal 192.168.1.1:3260 \-\-logout .nf List node records: .ft R iscsiadm \-\-mode node .nf Display all data for a given node record: .ft R iscsiadm \-\-mode node \-\-targetname iqn.2001-05.com.doe:test \-\-portal 192.168.1.1:3260 .SH FILES .TP /etc/iscsi/iscsid.conf The configuration file read by \fBiscsid\fR and \fBiscsiadm\fR on startup. .TP /etc/iscsi/initiatorname.iscsi The file containing the iSCSI InitiatorName and InitiatorAlias read by \fBiscsid\fR and \fBiscsiadm\fR on startup. .TP /etc/iscsi/nodes/ This directory contains the nodes with their targets. .TP /etc/iscsi/send_targets This directory contains the portals. .SH "SEE ALSO" .BR iscsid (8) .SH AUTHORS Open-iSCSI project .br Alex Aizman .br Dmitry Yusupov open-iscsi-2.0.873/doc/iscsid.8000066400000000000000000000034431175631155400160740ustar00rootroot00000000000000.TH ISCSID 8 "July 2005" "" "Linux Administrator's Manual" .SH NAME iscsid \- Open-iSCSI daemon .SH SYNOPSIS .BI iscsid [OPTION] .SH "DESCRIPTION" The .B iscsid implements the control path of iSCSI protocol, plus some management facilities. For example, the daemon could be configured to automatically re-start discovery at startup, based on the contents of persistent iSCSI database. .SH OPTIONS .TP .BI [-c|--config=]\fIconfig\-file\fP Read configuration from \fIconfig\-file\fR rather than the default \fI/etc/iscsi/iscsid.conf\fR file. .TP .BI [-i|--initiatorname=]\fIiname\-file\fP Read initiator name from \fIiname\-file\fR rather than the default \fI/etc/iscsi/initiatorname.iscsi\fR file. .TP .BI [-f|--foreground] run .B iscsid in the foreground. .TP .BI [-d|--debug=]\fIdebug_level\fP print debugging information. Valid values for debug_level are 0 to 8. .TP .BI [-u|--uid=]\fIuid\fP run under user ID \fIuid\fR (default is the current user ID) .TP .BI [-g|--gid=]\fIgid\fP run under user group ID \fIgid\fR (default is the current user group ID). .TP .BI [-n|--no-pid-file]\fP do not write a process ID file. .TP .BI [-p|--pid=]\fIpid\-file\fP write process ID to \fIpid\-file\fR rather than the default \fI/var/run/iscsid.pid\fR .TP .BI [-h|--help] display this help and exit .TP .BI [-v|--version] display version and exit. .SH FILES .TP /etc/iscsi/iscsid.conf The configuration file read by .B iscsid and .B iscsiadm on startup. .TP /etc/iscsi/initiatorname.iscsi The file containing the iSCSI initiatorname and initiatoralias read by .B iscsid and .B iscsiadm on startup. .TP /etc/iscsi/nodes Open-iSCSI persistent configuration database .SH "SEE ALSO" .BR iscsiadm (8) .SH AUTHORS Open-iSCSI project .br Alex Aizman .br Dmitry Yusupov open-iscsi-2.0.873/doc/iscsistart.8000066400000000000000000000034571175631155400170130ustar00rootroot00000000000000.TH ISCSISTART 8 "Jan 2010" "" "Linux Administrator's Manual" .SH NAME iscsistart \- iSCSI boot tool .SH SYNOPSIS .BI iscsistart [OPTION] .SH "DESCRIPTION" .B iscsistart will start a session using the settings passed in, or using the iBFT or Open Firmware [OF] boot information. This program should not be run to manage sessions. Its primary use is to start sessions used for iSCSI root boot. .SH OPTIONS .TP .BI [-i|--initiatorname=]\fIname\fP Set InitiatorName to name (Required if not using iBFT or OF) .TP .BI [-t|--targetname=]\fIname\fP Set TargetName to name (Required if not using iBFT or OF) .TP .BI [-g|--tgpt=]\fIN\fP Set target portal group tag to N (Required if not using iBFT or OF) .TP .BI [-a|--address=]\fIA.B.C.D\fP Set IP addres to A.B.C.D (Required if not using iBFT or OF) .TP .BI [-p|--port=]\fIN\fP Set port to N (Optional. Default 3260) .TP .BI [-u|--username=]\fIN\fP Set username to N (Optional) .TP .BI [-w|--password=]\fIN\fP Set password to N (Optional) .TP .BI [-U|-username_in=]\fIN\fP Set incoming username to N (Optional) .TP .BI [-W|--password_in=]\fIN\fP Set incoming password to N (Optional) .TP .BI [-d|--debug=]\fIdebug_level\fP Print debugging information .TP .BI [-b|--fwparam_connect] Create a session to the target using the iBFT or OF info .TP .BI [-N|--fwparam_network] Bring up the network as specified by iBFT or OF .TP .BI [-f|--fwparam_print] Print the iBFT or OF info to STDOUT .TP .BI [-P|--param=]\fINAME=VALUE\fP Set the parameter with the name NAME to VALUE. NAME is one of the settings in the node record or iscsid.conf. Multiple params can be passed in. .TP .BI [-h|--help] Display this help and exit .TP .BI [-v|--version] Display version and exit .SH "SEE ALSO" .BR iscsiadm (8) .SH AUTHORS Open-iSCSI project .br Mike Christie open-iscsi-2.0.873/etc/000077500000000000000000000000001175631155400145275ustar00rootroot00000000000000open-iscsi-2.0.873/etc/iface.example000066400000000000000000000135371175631155400171640ustar00rootroot00000000000000# # Example iSCSI interface config # # There must be a seperate iscsi interface config file for each NIC, network # interface or port or iscsi HBA you want to bind sessions to. # # For hardware iscsi, this is created for you when you run iscsiadm. # For software iscsi, you must define these files yourself. # # REQUIRED: iface.transport_name # # Set the iscsi transport/driver to use for the iface by setting # iface.transport_name # example: # iface.transport_name = tcp # This value is required and valid values for iface.transport_name are: # - tcp (Software iSCSI over TCP/IP) # - iser (Software iSCSI over infinniband # - qla4xxx (Qlogic QLA4XXX HBAs) # - bnx2i (Broadcom bnx iSCSI HBAs); # - cxgb3i (Chelsio cxgb S3 iSCSI HBAs); # #OPTIONAL: iface.initiatorname # To use a initiator name other than the one set in # /etc/iscsi/initiatorname.iscsi for normal sessions set the # iface.initiatorname. This is only used for normal sessions. # For discovery sessions the /etc/iscsi/initiatorname.iscsi value # is used. # # iface.initiatorname = iqn.2003-04.com.fedora:test # # # REQUIRED to be able to bind a session to a network device: # [iface.net_ifacename | iface.hwaddress] # # OPTIONAL if you are creating ifaces so you can create multiple sessions # using the default behavior where the network layer selects the device. # # __One__ of the following values are required for binding a session # to a specific nic/netdevice. # # To bind by network interface name (example: eth0, eth2:2, eth1.3) # set iface.net_ifacename # example: # iface.net_ifacename = eth0 # To bind by hardware address set the NIC's MAC address to iface.hwaddress # example: # iface.hwaddress = 00:0F:1F:92:6B:BF # Note you can only bind using one value. If you set multiple values # the bahavior is not defined. # For some transport (cxgb3i), a user could to set the private ip address for # the iscsi traffic for an network interface: # example: # - set iscsi ip on eth0 to be 102.50.50.101, eth0 needs to be up and be on # the same subnet. # iface.net_ifacename = eth0 # iface.ipaddress = 102.50.50.101 # OPTIONAL: iface.bootproto # # Valid values are: # "dhcp" and "static" # # REQUIRED when IPv4 address need to be obtained dynamically using DHCP # example: # iface.bootproto = dhcp # # OPTIONAL when the IPv4 address is set statically # example: # iface.ipaddress = 102.50.50.101 # iface.bootproto = static # # OPTIONAL: iface.vlan_id # Used to set the VLAN ID for the iSCSI interfae. # example # iface.vlan_id = 1022 # OPTIONAL: iface.vlan_priority # Used to set the VLAN priority for the iSCSI interfae. # example # iface.vlan_priority = 1 # OPTIONAL: iface.vlan_state # Used to enable or disable the VLAN on the iSCSI interface # example # iface.vlan_state = enable # OPTIONAL: iface.ipv6_linklocal # Specify the IPV6 Link Local Address with the # link local prefix of FE80::0/64 # example: # iface.ipv6_linklocal = fe80:0000:0000:0000:020e:1eff:1111:2221 # OPTIONAL: iface.ipv6_router # Used to set a default IPV6 router # example: # iface.ipv6_router = fe80:0000:0000:0000:7ae7:d1ff:fe72:4048 # OPTIONAL: iface.ipv6_autocfg # Used to set the discovery protocol to obtain IPV6 address # For example qla4xxx support neighbor discovery # example: # iface.ipv6_autocfg = nd # OPTIONAL: iface.linklocal_autocfg # For transport like qla4xxx this allows to auto configure the # IPV6 link local address based on the MAC address of the iSCSI # interface # OPTIONAL: iface.router_autocfg # Required to set the IPv6 router discovery protocol # To set the router discovery protocol to Neighbor Discovery specify "nd" # example: # iface.router_autocfg = nd # OPTIONAL: iface.state # By default the iface is enabled # iface.state = enable # To disable the iface set the state to "disable" # iface.state = disable # iface.iface_num # REQUIRED: When there are more than 1 interface to be configured. # For transports like qla4xxx, one can specify two IPV6 interfaces # in such case the iface_num must be set correctly # example: # iface settings for first IPV6 interface # iface.iscsi_ifacename = iface-qla4xxx-ipv6-1 # iface.iface_num = 0 # # iface settings for second IPV6 interface # iface.iscsi_ifacename = iface-qla4xxx-ipv6-2 # iface.iface_num = 1 # Here are some example iface files # IPV4 sample config file with static IP address: # BEGIN RECORD 2.0-872 # iface.iscsi_ifacename = qla4xxx-3 # iface.ipaddress = 192.168.1.75 # iface.hwaddress = 00:0e:1e:04:93:92 # iface.transport_name = qla4xxx # iface.bootproto = static # iface.subnet_mask = 255.255.255.0 # iface.gateway = 192.168.1.1 # iface.state = enable # iface.vlan = # iface.iface_num = 0 # END RECORD # # IPV6 sample config file with neighbor discovery: # BEGIN RECORD 2.0-872 # iface.iscsi_ifacename = qla4xxx-3-1 # iface.ipaddress = # iface.hwaddress = 00:0e:1e:04:93:92 # iface.transport_name = qla4xxx # iface.ipv6_autocfg = nd # iface.linklocal_autocfg = auto # iface.router_autocfg = nd # iface.ipv6_linklocal = fe80:0000:0000:0000:020e:1eff:1111:2221 # iface.ipv6_router = auto # iface.state = enable # iface.vlan = # iface.iface_num = 0 # END RECORD # Ipv4 sample config file (DHCP configuration): # BEGIN RECORD 2.0-872 # iface.iscsi_ifacename = qla4xxx-3 # iface.hwaddress = 00:0e:1e:04:93:92 # iface.transport_name = qla4xxx # iface.bootproto = dhcp # iface.state = enable # iface.vlan = # iface.iface_num = 0 # END RECORD # Sample ipv6 config file(manual configured IPs): # BEGIN RECORD 2.0-872 # iface.iscsi_ifacename = iface-new-file # iface.ipaddress = fec0:ce00:7014:0041:1111:2222:1e04:9392 # iface.hwaddress = 00:0e:1e:04:93:92 # iface.transport_name = qla4xxx # iface.ipv6_autocfg = # iface.linklocal_autocfg = # iface.router_autocfg = # iface.ipv6_linklocal = fe80:0000:0000:0000:0000:0000:1e04:9392 # iface.ipv6_router = fe80:0000:0000:0000:7ae7:d1ff:fe72:4048 # iface.state = enable # iface.vlan = # iface.iface_num = 0 # END RECORD open-iscsi-2.0.873/etc/initd/000077500000000000000000000000001175631155400156365ustar00rootroot00000000000000open-iscsi-2.0.873/etc/initd/boot.suse000066400000000000000000000032511175631155400175030ustar00rootroot00000000000000#!/bin/bash # # /etc/init.d/iscsi # ### BEGIN INIT INFO # Provides: iscsiboot # Required-Start: # Should-Start: boot.multipath # Required-Stop: # Should-Stop: # Default-Start: B # Default-Stop: # Short-Description: iSCSI initiator daemon root-fs support # Description: Starts the iSCSI initiator daemon if the # root-filesystem is on an iSCSI device # ### END INIT INFO ISCSIADM=/sbin/iscsiadm CONFIG_FILE=/etc/iscsid.conf DAEMON=/sbin/iscsid ARGS="-c $CONFIG_FILE" # Source LSB init functions . /etc/rc.status # # This service is run right after booting. So all targets activated # during mkinitrd run should not be removed when the open-iscsi # service is stopped. # iscsi_mark_root_nodes() { $ISCSIADM -m session 2> /dev/null | while read t num i target ; do ip=${i%%:*} STARTUP=`$ISCSIADM -m node -p $ip -T $target 2> /dev/null | grep "node.conn\[0\].startup" | cut -d' ' -f3` if [ "$STARTUP" -a "$STARTUP" != "onboot" ] ; then $ISCSIADM -m node -p $ip -T $target -o update -n node.conn[0].startup -v onboot fi done } # Reset status of this service rc_reset # We only need to start this for root on iSCSI if ! grep -q iscsi_tcp /proc/modules ; then rc_failed 6 rc_exit fi case "$1" in start) echo -n "Starting iSCSI initiator for the root device: " startproc $DAEMON $ARGS rc_status -v iscsi_mark_root_nodes ;; stop|restart|reload) rc_failed 0 ;; status) echo -n "Checking for iSCSI initiator service: " if checkproc $DAEMON ; then rc_status -v else rc_failed 3 rc_status -v fi ;; *) echo "Usage: $0 {start|stop|status|restart|reload}" exit 1 ;; esac rc_exit open-iscsi-2.0.873/etc/initd/initd.debian000066400000000000000000000042141175631155400201120ustar00rootroot00000000000000#! /bin/sh ### BEGIN INIT INFO # Provides: # Required-Start: # Required-Stop: # Default-Start: # Default-Stop: # Short-Description: Starts and stops the iSCSI initiator services and logins to default targets ### END INIT INFO PATH=/sbin:/bin:/usr/sbin:/usr/bin DAEMON=/sbin/iscsid ADM=/sbin/iscsiadm PIDFILE=/var/run/iscsid.pid [ -x "$DAEMON" ] || exit 0 . /lib/lsb/init-functions if [ ! -d /sys/class/ ]; then log_failure_msg "iSCSI requires a mounted sysfs, not started." exit 1 fi nodestartup_re='s/^node\.conn\[0]\.startup[ ]*=[ ]*//p' RETVAL=0 start() { log_daemon_msg "Starting iSCSI initiator service" "iscsid" modprobe -q iscsi_tcp 2>/dev/null || : modprobe -q ib_iser 2>/dev/null || : start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON RETVAL=$? log_end_msg $RETVAL starttargets } starttargets() { log_daemon_msg "Setting up iSCSI targets" $ADM -m node --loginall=automatic log_end_msg 0 } stoptargets() { log_daemon_msg "Disconnecting iSCSI targets" sync $ADM -m node --logoutall=all RETVAL=$? log_end_msg $RETVAL } stop() { stoptargets if [ $RETVAL -ne 0 ]; then log_failure_msg "Could not stop all targets, try again later" return $RETVAL fi log_daemon_msg "Stopping iSCSI initiator service" start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON rm -f $PIDFILE status=0 modprobe -r ib_iser 2>/dev/null if [ "$?" -ne "0" -a "$?" -ne "1" ]; then status=1 fi modprobe -r iscsi_tcp 2>/dev/null if [ "$?" -ne "0" -a "$?" -ne "1" ]; then status=1 fi log_end_msg $status } restart() { stop if [ $RETVAL -ne 0 ]; then log_failure_msg "Stopping iSCSI initiator service failed, not starting" return $RETVAL fi start } restarttargets() { stoptargets if [ $RETVAL -ne 0 ]; then log_failure_msg "Could not stop all targets, try again later" return $RETVAL fi starttargets } status() { #XXX FIXME: what to do here? #status iscsid # list active sessions echo Current active iSCSI sessions: $ADM -m session } case "$1" in start|starttargets|stop|stoptargets|restart|restarttargets|status) $1 ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 ;; esac exit $RETVAL open-iscsi-2.0.873/etc/initd/initd.redhat000066400000000000000000000032071175631155400201400ustar00rootroot00000000000000#!/bin/sh # # chkconfig: 345 13 89 # description: Starts and stops the iSCSI initiator # # processname: iscsid # pidfile: /var/run/iscsid.pid # config: /etc/iscsi/iscsid.conf # Source function library. . /etc/init.d/functions PATH=/sbin:/bin:/usr/sbin:/usr/bin RETVAL=0 start() { echo -n $"Starting iSCSI initiator service: " daemon iscsid RETVAL=$? success echo [ $RETVAL -eq 0 ] || return touch /var/lock/subsys/open-iscsi echo -n $"Setting up iSCSI targets: " iscsiadm -m node --loginall=automatic success echo } stop() { echo -n $"Stopping iSCSI initiator service: " sync iscsiadm -m node --logoutall=all RETVAL=$? if [ $RETVAL -ne 0 ]; then echo "Could not logout from all nodes, try again later" return $RETVAL fi iscsiadm -k 0 rm -f /var/run/iscsid.pid [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/open-iscsi status=0 modprobe -r iscsi_tcp 2>/dev/null if [ "$?" -ne "0" -a "$?" -ne "1" ]; then status=1 fi modprobe -r ib_iser 2>/dev/null if [ "$?" -ne "0" -a "$?" -ne "1" ]; then status=1 fi if [ "$status" -eq "0" ]; then success else failure fi echo } restart() { stop if [ $RETVAL -ne 0 ]; then echo "Stopping iSCSI initiator service failed, not starting" return $RETVAL fi start } case "$1" in start) start ;; stop) stop ;; restart) stop if [ $RETVAL -ne 0 ]; then echo "Stopping iSCSI initiator service failed, not starting" exit $RETVAL fi start ;; status) status iscsid RETVAL=$? ;; condrestart) [ -f /var/lock/subsys/open-iscsi ] && restart ;; *) echo $"Usage: $0 {start|stop|restart|status|condrestart}" exit 1 esac exit $RETVAL open-iscsi-2.0.873/etc/initd/initd.suse000066400000000000000000000223541175631155400176540ustar00rootroot00000000000000#!/bin/bash # # /etc/init.d/iscsi # ### BEGIN INIT INFO # Provides: iscsi # Required-Start: $network # Should-Start: iscsitarget multipathd # Required-Stop: $network # Should-Stop: multipathd # Default-Start: 3 5 # Default-Stop: # Short-Description: iSCSI initiator daemon # Description: The iSCSI initator is used to create and # manage iSCSI connections to a iSCSI Target. # ### END INIT INFO CONFIG_FILE=/etc/iscsi/iscsid.conf DAEMON=/sbin/iscsid ISCSIADM=/sbin/iscsiadm BRCM_ISCSIUIO=/sbin/brcm_iscsiuio ARGS="-c $CONFIG_FILE -n" # Source LSB init functions . /etc/rc.status # Reset status of this service rc_reset DM_MAJOR=$(sed -n 's/\(.*\) device-mapper/\1/p' /proc/devices) iscsi_login_all_nodes() { echo -n "Setting up iSCSI targets: " $ISCSIADM -m node --loginall=automatic 2> /dev/null if [ $? == 21 ] ; then rc_failed 6 fi rc_status -v } # # Try to load all required modules prior to startup # iscsi_load_transport_modules() { loaded=$(sed -n "/^iscsi_tcp/p" /proc/modules) if [ -z "$loaded" ] ; then modprobe iscsi_tcp if [ $? = 0 ] ; then echo -n " tcp" fi fi for iface in /etc/iscsi/ifaces/*; do [ -f "$iface" ] || continue [ "$iface" = "iface.example" ] && continue # Check if the iface has been configured result=$(sed '/#.*/D;/iface.iscsi_ifacename/D;/iface.hwaddress/D;/iface.transport_name/D' $iface) if [ "$result" ] ; then mod=$(sed -n 's/iface.transport_name *= *\(.*\)/\1/p' $iface) loaded=$(sed -n "/^$mod/p" /proc/modules) if [ -z "$loaded" ] ; then modprobe $mod if [ $? = 0 ] ; then echo -n " $mod" fi fi fi done } # # Set a temporary startmode for ifdown # iscsi_modify_if_startmode() { local ifname=$1 local tmp_ifcfg=/dev/.sysconfig/network/if-$ifname if [ -e "$tmp_ifcfg" ] ; then . $tmp_ifcfg if [ "$startmode" ] ; then return fi fi : disabling shutdown on $ifname echo "startmode=nfsroot" >> $tmp_ifcfg } iscsi_get_ifacename_from_session() { local session=$1 local ifacename ifacename=$(iscsiadm -m session -r ${session##.*/session} 2> /dev/null | \ sed -n 's/iface.iscsi_ifacename = \(.*\)/\1/p') if [ -z "$ifacename" ] ; then # Check for iBFT ifacename=$(iscsiadm -m fw 2> /dev/null) if [ -n "$ifacename" ] ; then ifacename="fw" fi fi echo $ifacename } iscsi_get_hwaddress_from_iface() { local iface=$1 local hwaddress hwaddress=$(iscsiadm -m iface -I "$iface" 2> /dev/null | sed -n 's/iface.hwaddress = \(.*\)/\1/p') [ "$hwaddress" = "" ] && hwaddress= echo $hwaddress } iscsi_get_ifname_from_iface() { local iface=$1 local ifname ifname=$(iscsiadm -m iface -I "$iface" 2> /dev/null | sed -n 's/iface.net_ifacename = \(.*\)/\1/p') [ "$ifname" = "" ] && ifname= echo $ifname } iscsi_get_ipaddr_from_iface() { local iface=$1 local ipaddr ipaddr=$(iscsiadm -m iface -I "$iface" 2> /dev/null | sed -n 's/iface.ipaddress = \(.*\)/\1/p') [ "$ipaddr" = "" ] && ipaddr= echo $ipaddr } iscsi_get_ifname_from_firmware() { local hwaddress hwaddress=$(iscsiadm -m fw 2> /dev/null | sed -n 's/iface.net_ifacename = \(.*\)/\1/p') echo $hwaddress } # # cxgb3i is using the HWAddress to select # the correct interface # iscsi_get_ifname_from_hwaddress() { local hwaddress=$1 for if in /sys/class/net/*; do [ -e "$if" ] || continue read mac < $if/address [ "$mac" = "$hwaddress" ] || continue echo ${if##*/} break done } iscsi_get_ifname_from_ipaddr() { local ipaddr=$1 local ifname ifname=$(ip addr show to $ipaddr | sed -n 's/[0-9]*: \([^ :]*\): .*/\1/p') return $ifname } # # Handle 'default' interface: # It is basically impossible to determine via which # interface the iSCSI traffic will flow, so we take # the easy option and ignore _all_ active interfaces # during shutdown # iscsi_modify_all_interfaces() { ip link show up | sed -n '/.*LOOPBACK.*/d;s/[0-9]*: \(.*\): .*/\1/p' | while read ifname; do iscsi_modify_if_startmode $ifname done } # # Check iface setting and disable # affected network interfaces # iscsi_check_interface() { local session=$1 local i h n i=$(iscsi_get_ifacename_from_session $session) [ -z "$i" ] && continue if [ "$i" = "default" ] ; then iscsi_modify_all_interfaces elif [ "$i" = "fw" ] ; then n=$(iscsi_get_ifname_from_firmware) else n=$(iscsi_get_ifname_from_iface $i) if [ -z "$n" ] ; then h=$(iscsi_get_hwaddress_from_iface $i) if [ -n "$h" ] ; then n=$(iscsi_get_ifname_from_hwaddress $h) fi fi if [ -z "$n" ] ; then h=$(iscsi_get_ipaddr_from_iface $i) if [ -n "$h" ] ; then n=$(iscsi_get_ifname_from_ipaddr $h) fi fi fi if [ "$n" ] ; then iscsi_modify_if_startmode $n fi } # # Check if device 'dev' is mounted # Returns the mount point on success # iscsi_check_if_mounted() { local dev=$1 local d m t o x p cat /proc/mounts | sed -ne '/^\/dev\/.*/p' | while read d m t o x; do if [ -L "$d" ] ; then d=$(readlink -f $d) fi [ -b "$d" ] || continue b=$(ls -l $d | sed -n 's/.* \([0-9]*\), \([0-9]*\) .*/\1:\2/p') p=$(cd -P /sys/dev/block/$b ; echo $PWD) if [ -z "$p" ] ; then d=${d##/dev} p="/sys/block${d%%[0-9]*}" fi [ ! -d ${p} ] && continue if [ -e $p/partition ] ; then p=$(cd -P $p/../; echo $PWD) fi if [ "$dev" = "${p##*/}" ] ; then echo $m fi done } # # Unwind block device stack # # Stops unwinding if either no more 'holders' # are found or if a device is mounted # # Unmounts top-level device and deconfigures # all devices down the stack # # Root fs is not unmounted # iscsi_unwind_stack() { local p=$1 local d=${p##*/} local u local m if [ ! -d ${p} ] ; then return; fi m=$(iscsi_check_if_mounted $d) if [ -z "$m" ] ; then for s in $p/holders/* ; do [ -e $s ] || continue p=$(cd -P $s; echo $PWD) u=$(iscsi_unwind_stack $p) if [ "$u" ] ; then echo -n "$u " fi done else if [ "$m" = "/" ] ; then echo -n "$d " return 1 fi if ! umount $m ; then echo -n "$d " return 1 fi fi if [ "${d#dm-}" != "$d" ] ; then if ! dmsetup remove -j $DM_MAJOR -m ${d#dm-} 2> /dev/null ; then echo -n "$d " return 1 fi fi if [ "${d#md}" != "$d" ] ; then if ! mdadm --manage /dev/$d --stop 2> /dev/null ; then echo -n "$d " return 1 fi fi return 0 } # # Return all targets for a given session # iscsi_get_target() { local session=$1 local d for d in $session/device/target* ; do [ -e "$d" ] || continue echo "$d" done } # # Checks all devices presented by a target # and tries to umount them. # Skip unmounting for the root fs. # Stops on the first device which could not be unmounted # and returns the mount device of that device. # iscsi_check_target() { local t=$1 local d b m for d in $t/* ; do [ -d $d/block ] || continue for b in $d/block/sd* ; do [ -d "$b" ] || continue m=$(iscsi_unwind_stack $b) if [ -n "$m" ] ; then echo $m return 1 fi done done } # # Check all sessions for mounted devices # and shutdown the session if the affected # devices could be umounted cleanly. # If umount fails disable shutdown on all # affected network interfaces # iscsi_stop_sessions() { local t m s i i=0 for session in /sys/class/iscsi_session/session* ; do [ -e "$session" ] || continue; [ -e $session/device ] || continue t=$(iscsi_get_target $session) m=$(iscsi_check_target $t) s=${session##*/session} if [ -z "$m" ] ; then iscsiadm -m session -r ${s} -u i=$(( $i + 1 )) else iscsi_check_interface $s fi done echo $i } iscsi_list_all_nodes() { # Check for active sessions if $ISCSIADM -m session > /dev/null; then return 0 fi echo "Active connections:" $ISCSIADM -m session | while read proto num PORTAL TARGET ; do PORTAL=${PORTAL%,*} echo -e "\t$TARGET at $PORTAL" done } case "$1" in start) if checkproc $DAEMON ; then RETVAL=0 else echo -n "Starting iSCSI initiator service: " iscsi_load_transport_modules if grep -q bnx2i /proc/modules && [ -x $BRCM_ISCSIUIO ] ; then startproc $BRCM_ISCSIUIO fi startproc $DAEMON $ARGS RETVAL=$? rc_status -v fi if [ "$RETVAL" == "0" ]; then iscsi_login_all_nodes fi ;; stop) n=$(iscsi_stop_sessions) echo -n "Stopping iSCSI initiator service: " if [ "$n" ] && [ "$n" != "0" ] ; then m=$(iscsiadm -m session 2> /dev/null) if [ -z "$m" ] ; then killproc -KILL $DAEMON RETVAL=$? if grep -q bnx2i /proc/modules && [ -x $BRCM_ISCSIUIO ]; then killproc -KILL $BRCM_ISCSIUIO fi RETVAL=$? else RETVAL=1 fi rc_failed $RETVAL rc_status -v else # umounting failed, leave initiator running rc_status -s fi ;; status) echo -n "Checking for iSCSI initiator service: " if checkproc $DAEMON ; then rc_status -v iscsi_list_all_nodes else rc_failed 3 rc_status -v fi ;; restart|reload) $0 stop RETVAL=$? if [ "$RETVAL" != "0" ]; then echo "Stopping iSCSI initiator service failed, not starting" exit $RETVAL fi sleep 1 $0 start ;; *) echo "Usage: $0 {start|stop|status|restart|reload}" exit 1 ;; esac rc_exit open-iscsi-2.0.873/etc/iscsid.conf000066400000000000000000000267561175631155400166740ustar00rootroot00000000000000# # Open-iSCSI default configuration. # Could be located at /etc/iscsi/iscsid.conf or ~/.iscsid.conf # # Note: To set any of these values for a specific node/session run # the iscsiadm --mode node --op command for the value. See the README # and man page for iscsiadm for details on the --op command. # ###################### # iscsid daemon config ###################### # If you want iscsid to start the first time a iscsi tool # needs to access it, instead of starting it when the init # scripts run, set the iscsid startup command here. This # should normally only need to be done by distro package # maintainers. # # Default for Fedora and RHEL. (uncomment to activate). # iscsid.startup = /etc/rc.d/init.d/iscsid force-start # # Default for upstream open-iscsi scripts (uncomment to activate). iscsid.startup = /sbin/iscsid ############################# # NIC/HBA and driver settings ############################# # open-iscsi can create a session and bind it to a NIC/HBA. # To set this up see the example iface config file. #***************** # Startup settings #***************** # To request that the iscsi initd scripts startup a session set to "automatic". # node.startup = automatic # # To manually startup the session set to "manual". The default is manual. node.startup = manual # For "automatic" startup nodes, setting this to "Yes" will try logins on each # available iface until one succeeds, and then stop. The default "No" will try # logins on all availble ifaces simultaneously. node.leading_login = No # ************* # CHAP Settings # ************* # To enable CHAP authentication set node.session.auth.authmethod # to CHAP. The default is None. #node.session.auth.authmethod = CHAP # To set a CHAP username and password for initiator # authentication by the target(s), uncomment the following lines: #node.session.auth.username = username #node.session.auth.password = password # To set a CHAP username and password for target(s) # authentication by the initiator, uncomment the following lines: #node.session.auth.username_in = username_in #node.session.auth.password_in = password_in # To enable CHAP authentication for a discovery session to the target # set discovery.sendtargets.auth.authmethod to CHAP. The default is None. #discovery.sendtargets.auth.authmethod = CHAP # To set a discovery session CHAP username and password for the initiator # authentication by the target(s), uncomment the following lines: #discovery.sendtargets.auth.username = username #discovery.sendtargets.auth.password = password # To set a discovery session CHAP username and password for target(s) # authentication by the initiator, uncomment the following lines: #discovery.sendtargets.auth.username_in = username_in #discovery.sendtargets.auth.password_in = password_in # ******** # Timeouts # ******** # # See the iSCSI REAME's Advanced Configuration section for tips # on setting timeouts when using multipath or doing root over iSCSI. # # To specify the length of time to wait for session re-establishment # before failing SCSI commands back to the application when running # the Linux SCSI Layer error handler, edit the line. # The value is in seconds and the default is 120 seconds. # Special values: # - If the value is 0, IO will be failed immediately. # - If the value is less than 0, IO will remain queued until the session # is logged back in, or until the user runs the logout command. node.session.timeo.replacement_timeout = 120 # To specify the time to wait for login to complete, edit the line. # The value is in seconds and the default is 15 seconds. node.conn[0].timeo.login_timeout = 15 # To specify the time to wait for logout to complete, edit the line. # The value is in seconds and the default is 15 seconds. node.conn[0].timeo.logout_timeout = 15 # Time interval to wait for on connection before sending a ping. node.conn[0].timeo.noop_out_interval = 5 # To specify the time to wait for a Nop-out response before failing # the connection, edit this line. Failing the connection will # cause IO to be failed back to the SCSI layer. If using dm-multipath # this will cause the IO to be failed to the multipath layer. node.conn[0].timeo.noop_out_timeout = 5 # To specify the time to wait for abort response before # failing the operation and trying a logical unit reset edit the line. # The value is in seconds and the default is 15 seconds. node.session.err_timeo.abort_timeout = 15 # To specify the time to wait for a logical unit response # before failing the operation and trying session re-establishment # edit the line. # The value is in seconds and the default is 30 seconds. node.session.err_timeo.lu_reset_timeout = 30 # To specify the time to wait for a target response # before failing the operation and trying session re-establishment # edit the line. # The value is in seconds and the default is 30 seconds. node.session.err_timeo.tgt_reset_timeout = 30 #****** # Retry #****** # To specify the number of times iscsid should retry a login # if the login attempt fails due to the node.conn[0].timeo.login_timeout # expiring modify the following line. Note that if the login fails # quickly (before node.conn[0].timeo.login_timeout fires) because the network # layer or the target returns an error, iscsid may retry the login more than # node.session.initial_login_retry_max times. # # This retry count along with node.conn[0].timeo.login_timeout # determines the maximum amount of time iscsid will try to # establish the initial login. node.session.initial_login_retry_max is # multiplied by the node.conn[0].timeo.login_timeout to determine the # maximum amount. # # The default node.session.initial_login_retry_max is 8 and # node.conn[0].timeo.login_timeout is 15 so we have: # # node.conn[0].timeo.login_timeout * node.session.initial_login_retry_max = # 120 seconds # # Valid values are any integer value. This only # affects the initial login. Setting it to a high value can slow # down the iscsi service startup. Setting it to a low value can # cause a session to not get logged into, if there are distuptions # during startup or if the network is not ready at that time. node.session.initial_login_retry_max = 8 ################################ # session and device queue depth ################################ # To control how many commands the session will queue set # node.session.cmds_max to an integer between 2 and 2048 that is also # a power of 2. The default is 128. node.session.cmds_max = 128 # To control the device's queue depth set node.session.queue_depth # to a value between 1 and 1024. The default is 32. node.session.queue_depth = 32 ################################## # MISC SYSTEM PERFORMANCE SETTINGS ################################## # For software iscsi (iscsi_tcp) and iser (ib_iser) each session # has a thread used to transmit or queue data to the hardware. For # cxgb3i you will get a thread per host. # # Setting the thread's priority to a lower value can lead to higher throughput # and lower latencies. The lowest value is -20. Setting the priority to # a higher value, can lead to reduced IO performance, but if you are seeing # the iscsi or scsi threads dominate the use of the CPU then you may want # to set this value higher. # # Note: For cxgb3i you must set all sessions to the same value, or the # behavior is not defined. # # The default value is -20. The setting must be between -20 and 20. node.session.xmit_thread_priority = -20 #*************** # iSCSI settings #*************** # To enable R2T flow control (i.e., the initiator must wait for an R2T # command before sending any data), uncomment the following line: # #node.session.iscsi.InitialR2T = Yes # # To disable R2T flow control (i.e., the initiator has an implied # initial R2T of "FirstBurstLength" at offset 0), uncomment the following line: # # The defaults is No. node.session.iscsi.InitialR2T = No # # To disable immediate data (i.e., the initiator does not send # unsolicited data with the iSCSI command PDU), uncomment the following line: # #node.session.iscsi.ImmediateData = No # # To enable immediate data (i.e., the initiator sends unsolicited data # with the iSCSI command packet), uncomment the following line: # # The default is Yes node.session.iscsi.ImmediateData = Yes # To specify the maximum number of unsolicited data bytes the initiator # can send in an iSCSI PDU to a target, edit the following line. # # The value is the number of bytes in the range of 512 to (2^24-1) and # the default is 262144 node.session.iscsi.FirstBurstLength = 262144 # To specify the maximum SCSI payload that the initiator will negotiate # with the target for, edit the following line. # # The value is the number of bytes in the range of 512 to (2^24-1) and # the defauls it 16776192 node.session.iscsi.MaxBurstLength = 16776192 # To specify the maximum number of data bytes the initiator can receive # in an iSCSI PDU from a target, edit the following line. # # The value is the number of bytes in the range of 512 to (2^24-1) and # the default is 262144 node.conn[0].iscsi.MaxRecvDataSegmentLength = 262144 # To specify the maximum number of data bytes the initiator will send # in an iSCSI PDU to the target, edit the following line. # # The value is the number of bytes in the range of 512 to (2^24-1). # Zero is a special case. If set to zero, the initiator will use # the target's MaxRecvDataSegmentLength for the MaxXmitDataSegmentLength. # The default is 0. node.conn[0].iscsi.MaxXmitDataSegmentLength = 0 # To specify the maximum number of data bytes the initiator can receive # in an iSCSI PDU from a target during a discovery session, edit the # following line. # # The value is the number of bytes in the range of 512 to (2^24-1) and # the default is 32768 # discovery.sendtargets.iscsi.MaxRecvDataSegmentLength = 32768 # To allow the targets to control the setting of the digest checking, # with the initiator requesting a preference of enabling the checking, uncomment# one or both of the following lines: #node.conn[0].iscsi.HeaderDigest = CRC32C,None #node.conn[0].iscsi.DataDigest = CRC32C,None # # To allow the targets to control the setting of the digest checking, # with the initiator requesting a preference of disabling the checking, # uncomment one or both of the following lines: #node.conn[0].iscsi.HeaderDigest = None,CRC32C #node.conn[0].iscsi.DataDigest = None,CRC32C # # To enable CRC32C digest checking for the header and/or data part of # iSCSI PDUs, uncomment one or both of the following lines: #node.conn[0].iscsi.HeaderDigest = CRC32C #node.conn[0].iscsi.DataDigest = CRC32C # # To disable digest checking for the header and/or data part of # iSCSI PDUs, uncomment one or both of the following lines: #node.conn[0].iscsi.HeaderDigest = None #node.conn[0].iscsi.DataDigest = None # # The default is to never use DataDigests or HeaderDigests. # # For multipath configurations, you may want more than one session to be # created on each iface record. If node.session.nr_sessions is greater # than 1, performing a 'login' for that node will ensure that the # appropriate number of sessions is created. node.session.nr_sessions = 1 #************ # Workarounds #************ # Some targets like IET prefer after an initiator has sent a task # management function like an ABORT TASK or LOGICAL UNIT RESET, that # it does not respond to PDUs like R2Ts. To enable this behavior uncomment # the following line (The default behavior is Yes): node.session.iscsi.FastAbort = Yes # Some targets like Equalogic prefer that after an initiator has sent # a task management function like an ABORT TASK or LOGICAL UNIT RESET, that # it continue to respond to R2Ts. To enable this uncomment this line # node.session.iscsi.FastAbort = No open-iscsi-2.0.873/include/000077500000000000000000000000001175631155400153775ustar00rootroot00000000000000open-iscsi-2.0.873/include/fw_context.h000066400000000000000000000037261175631155400177400ustar00rootroot00000000000000/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * "Prasanna Mumbai" * */ #ifndef FWPARAM_CONTEXT_H_ #define FWPARAM_CONTEXT_H_ #include #include #include "iscsi_proto.h" #include "list.h" #include "auth.h" struct boot_context { struct list_head list; /* target settings */ int target_port; char targetname[TARGET_NAME_MAXLEN + 1]; char target_ipaddr[NI_MAXHOST]; char chap_name[AUTH_STR_MAX_LEN]; char chap_password[AUTH_STR_MAX_LEN]; char chap_name_in[AUTH_STR_MAX_LEN]; char chap_password_in[AUTH_STR_MAX_LEN]; /* initiator settings */ char isid[10]; char initiatorname[TARGET_NAME_MAXLEN + 1]; /* network settings */ char dhcp[NI_MAXHOST]; char iface[IF_NAMESIZE]; char mac[18]; char ipaddr[NI_MAXHOST]; char gateway[NI_MAXHOST]; char primary_dns[NI_MAXHOST]; char secondary_dns[NI_MAXHOST]; char mask[NI_MAXHOST]; char lun[17]; char vlan[15]; char scsi_host_name[64]; }; extern int fw_get_entry(struct boot_context *context); extern void fw_print_entry(struct boot_context *context); extern int fw_get_targets(struct list_head *list); extern void fw_free_targets(struct list_head *list); extern int fw_setup_nics(void); #endif /* FWPARAM_CONTEXT_H_ */ open-iscsi-2.0.873/include/iscsi_err.h000066400000000000000000000041401175631155400175310ustar00rootroot00000000000000/* * Return codes used by iSCSI tools. */ #ifndef _ISCSI_ERR_ #define _ISCSI_ERR_ enum { ISCSI_SUCCESS = 0, /* Generic error */ ISCSI_ERR = 1, /* session could not be found */ ISCSI_ERR_SESS_NOT_FOUND = 2, /* Could not allocate resource for operation */ ISCSI_ERR_NOMEM = 3, /* Transport error caused operation to fail */ ISCSI_ERR_TRANS = 4, /* Generic login failure */ ISCSI_ERR_LOGIN = 5, /* Error accessing/managing iSCSI DB */ ISCSI_ERR_IDBM = 6, /* Invalid argument */ ISCSI_ERR_INVAL = 7, /* Connection timer exired while trying to connect */ ISCSI_ERR_TRANS_TIMEOUT = 8, /* Generic internal iscsid failure */ ISCSI_ERR_INTERNAL = 9, /* Logout failed */ ISCSI_ERR_LOGOUT = 10, /* iSCSI PDU timedout */ ISCSI_ERR_PDU_TIMEOUT = 11, /* iSCSI transport module not loaded in kernel or iscsid */ ISCSI_ERR_TRANS_NOT_FOUND = 12, /* Permission denied */ ISCSI_ERR_ACCESS = 13, /* Transport module did not support operation */ ISCSI_ERR_TRANS_CAPS = 14, /* Session is logged in */ ISCSI_ERR_SESS_EXISTS = 15, /* Invalid IPC MGMT request */ ISCSI_ERR_INVALID_MGMT_REQ = 16, /* iSNS service is not supported */ ISCSI_ERR_ISNS_UNAVAILABLE = 17, /* A read/write to iscsid failed */ ISCSI_ERR_ISCSID_COMM_ERR = 18, /* Fatal login error */ ISCSI_ERR_FATAL_LOGIN = 19, /* Could ont connect to iscsid */ ISCSI_ERR_ISCSID_NOTCONN = 20, /* No records/targets/sessions/portals found to execute operation on */ ISCSI_ERR_NO_OBJS_FOUND = 21, /* Could not lookup object in sysfs */ ISCSI_ERR_SYSFS_LOOKUP = 22, /* Could not lookup host */ ISCSI_ERR_HOST_NOT_FOUND = 23, /* Login failed due to authorization failure */ ISCSI_ERR_LOGIN_AUTH_FAILED = 24, /* iSNS query failure */ ISCSI_ERR_ISNS_QUERY = 25, /* iSNS registration/deregistration failed */ ISCSI_ERR_ISNS_REG_FAILED = 26, /* operation not supported */ ISCSI_ERR_OP_NOT_SUPP = 27, /* device or resource in use */ ISCSI_ERR_BUSY = 28, /* Always last. Indicates end of error code space */ ISCSI_MAX_ERR_VAL, } iscsi_err; extern void iscsi_err_print_msg(int err); extern char *iscsi_err_to_str(int err); #endif open-iscsi-2.0.873/include/iscsi_if.h000066400000000000000000000433431175631155400173470ustar00rootroot00000000000000/* * iSCSI User/Kernel Shares (Defines, Constants, Protocol definitions, etc) * * Copyright (C) 2005 Dmitry Yusupov * Copyright (C) 2005 Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_IF_H #define ISCSI_IF_H #ifdef __KERNEL__ #include #include #else #include #endif #include "iscsi_proto.h" #define ISCSI_NL_GRP_ISCSID 1 #define ISCSI_NL_GRP_UIP 2 #define UEVENT_BASE 10 #define KEVENT_BASE 100 #define ISCSI_ERR_BASE 1000 enum iscsi_uevent_e { ISCSI_UEVENT_UNKNOWN = 0, /* down events */ ISCSI_UEVENT_CREATE_SESSION = UEVENT_BASE + 1, ISCSI_UEVENT_DESTROY_SESSION = UEVENT_BASE + 2, ISCSI_UEVENT_CREATE_CONN = UEVENT_BASE + 3, ISCSI_UEVENT_DESTROY_CONN = UEVENT_BASE + 4, ISCSI_UEVENT_BIND_CONN = UEVENT_BASE + 5, ISCSI_UEVENT_SET_PARAM = UEVENT_BASE + 6, ISCSI_UEVENT_START_CONN = UEVENT_BASE + 7, ISCSI_UEVENT_STOP_CONN = UEVENT_BASE + 8, ISCSI_UEVENT_SEND_PDU = UEVENT_BASE + 9, ISCSI_UEVENT_GET_STATS = UEVENT_BASE + 10, ISCSI_UEVENT_GET_PARAM = UEVENT_BASE + 11, ISCSI_UEVENT_TRANSPORT_EP_CONNECT = UEVENT_BASE + 12, ISCSI_UEVENT_TRANSPORT_EP_POLL = UEVENT_BASE + 13, ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT = UEVENT_BASE + 14, ISCSI_UEVENT_TGT_DSCVR = UEVENT_BASE + 15, ISCSI_UEVENT_SET_HOST_PARAM = UEVENT_BASE + 16, ISCSI_UEVENT_UNBIND_SESSION = UEVENT_BASE + 17, ISCSI_UEVENT_CREATE_BOUND_SESSION = UEVENT_BASE + 18, ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST = UEVENT_BASE + 19, ISCSI_UEVENT_PATH_UPDATE = UEVENT_BASE + 20, ISCSI_UEVENT_SET_IFACE_PARAMS = UEVENT_BASE + 21, ISCSI_UEVENT_PING = UEVENT_BASE + 22, ISCSI_UEVENT_GET_CHAP = UEVENT_BASE + 23, ISCSI_UEVENT_DELETE_CHAP = UEVENT_BASE + 24, ISCSI_UEVENT_MAX = ISCSI_UEVENT_DELETE_CHAP, /* up events */ ISCSI_KEVENT_RECV_PDU = KEVENT_BASE + 1, ISCSI_KEVENT_CONN_ERROR = KEVENT_BASE + 2, ISCSI_KEVENT_IF_ERROR = KEVENT_BASE + 3, ISCSI_KEVENT_DESTROY_SESSION = KEVENT_BASE + 4, ISCSI_KEVENT_UNBIND_SESSION = KEVENT_BASE + 5, ISCSI_KEVENT_CREATE_SESSION = KEVENT_BASE + 6, ISCSI_KEVENT_PATH_REQ = KEVENT_BASE + 7, ISCSI_KEVENT_IF_DOWN = KEVENT_BASE + 8, ISCSI_KEVENT_CONN_LOGIN_STATE = KEVENT_BASE + 9, ISCSI_KEVENT_HOST_EVENT = KEVENT_BASE + 10, ISCSI_KEVENT_PING_COMP = KEVENT_BASE + 11, ISCSI_KEVENT_MAX = ISCSI_KEVENT_PING_COMP, }; enum iscsi_tgt_dscvr { ISCSI_TGT_DSCVR_SEND_TARGETS = 1, ISCSI_TGT_DSCVR_ISNS = 2, ISCSI_TGT_DSCVR_SLP = 3, }; enum iscsi_host_event_code { ISCSI_EVENT_LINKUP = 1, ISCSI_EVENT_LINKDOWN, /* must always be last */ ISCSI_EVENT_MAX, }; struct iscsi_uevent { uint32_t type; /* k/u events type */ uint32_t iferror; /* carries interface or resource errors */ uint64_t transport_handle; union { /* messages u -> k */ struct msg_create_session { uint32_t initial_cmdsn; uint16_t cmds_max; uint16_t queue_depth; } c_session; struct msg_create_bound_session { uint64_t ep_handle; uint32_t initial_cmdsn; uint16_t cmds_max; uint16_t queue_depth; } c_bound_session; struct msg_destroy_session { uint32_t sid; } d_session; struct msg_create_conn { uint32_t sid; uint32_t cid; } c_conn; struct msg_bind_conn { uint32_t sid; uint32_t cid; uint64_t transport_eph; uint32_t is_leading; } b_conn; struct msg_destroy_conn { uint32_t sid; uint32_t cid; } d_conn; struct msg_send_pdu { uint32_t sid; uint32_t cid; uint32_t hdr_size; uint32_t data_size; } send_pdu; struct msg_set_param { uint32_t sid; uint32_t cid; uint32_t param; /* enum iscsi_param */ uint32_t len; } set_param; struct msg_start_conn { uint32_t sid; uint32_t cid; } start_conn; struct msg_stop_conn { uint32_t sid; uint32_t cid; uint64_t conn_handle; uint32_t flag; } stop_conn; struct msg_get_stats { uint32_t sid; uint32_t cid; } get_stats; struct msg_transport_connect { uint32_t non_blocking; } ep_connect; struct msg_transport_connect_through_host { uint32_t host_no; uint32_t non_blocking; } ep_connect_through_host; struct msg_transport_poll { uint64_t ep_handle; uint32_t timeout_ms; } ep_poll; struct msg_transport_disconnect { uint64_t ep_handle; } ep_disconnect; struct msg_tgt_dscvr { enum iscsi_tgt_dscvr type; uint32_t host_no; /* * enable = 1 to establish a new connection * with the server. enable = 0 to disconnect * from the server. Used primarily to switch * from one iSNS server to another. */ uint32_t enable; } tgt_dscvr; struct msg_set_host_param { uint32_t host_no; uint32_t param; /* enum iscsi_host_param */ uint32_t len; } set_host_param; struct msg_set_path { uint32_t host_no; } set_path; struct msg_set_iface_params { uint32_t host_no; uint32_t count; } set_iface_params; struct msg_iscsi_ping { uint32_t host_no; uint32_t iface_num; uint32_t iface_type; uint32_t payload_size; uint32_t pid; /* unique ping id associated with each ping request */ } iscsi_ping; struct msg_get_chap { uint32_t host_no; uint32_t num_entries; /* number of CHAP entries * on request, number of * valid CHAP entries on * response */ uint16_t chap_tbl_idx; } get_chap; struct msg_delete_chap { uint32_t host_no; uint16_t chap_tbl_idx; } delete_chap; } u; union { /* messages k -> u */ int retcode; struct msg_create_session_ret { uint32_t sid; uint32_t host_no; } c_session_ret; struct msg_create_conn_ret { uint32_t sid; uint32_t cid; } c_conn_ret; struct msg_unbind_session { uint32_t sid; uint32_t host_no; } unbind_session; struct msg_recv_req { uint32_t sid; uint32_t cid; uint64_t recv_handle; } recv_req; struct msg_conn_login { uint32_t sid; uint32_t cid; uint32_t state; /* enum iscsi_conn_state */ } conn_login; struct msg_conn_error { uint32_t sid; uint32_t cid; uint32_t error; /* enum iscsi_err */ } connerror; struct msg_session_destroyed { uint32_t host_no; uint32_t sid; } d_session; struct msg_transport_connect_ret { uint64_t handle; } ep_connect_ret; struct msg_req_path { uint32_t host_no; } req_path; struct msg_notify_if_down { uint32_t host_no; } notify_if_down; struct msg_host_event { uint32_t host_no; uint32_t data_size; enum iscsi_host_event_code code; } host_event; struct msg_ping_comp { uint32_t host_no; uint32_t status; /* enum * iscsi_ping_status_code */ uint32_t pid; /* unique ping id associated with each ping request */ uint32_t data_size; } ping_comp; } r; } __attribute__ ((aligned (sizeof(uint64_t)))); enum iscsi_param_type { ISCSI_PARAM, /* iscsi_param (session, conn, target, LU) */ ISCSI_HOST_PARAM, /* iscsi_host_param */ ISCSI_NET_PARAM, /* iscsi_net_param */ }; struct iscsi_iface_param_info { uint32_t iface_num; /* iface number, 0 - n */ uint32_t len; /* Actual length of the param */ uint16_t param; /* iscsi param value */ uint8_t iface_type; /* IPv4 or IPv6 */ uint8_t param_type; /* iscsi_param_type */ uint8_t value[0]; /* length sized value follows */ } __packed; /* * To keep the struct iscsi_uevent size the same for userspace code * compatibility, the main structure for ISCSI_UEVENT_PATH_UPDATE and * ISCSI_KEVENT_PATH_REQ is defined separately and comes after the * struct iscsi_uevent in the NETLINK_ISCSI message. */ struct iscsi_path { uint64_t handle; uint8_t mac_addr[6]; uint8_t mac_addr_old[6]; uint32_t ip_addr_len; /* 4 or 16 */ union { struct in_addr v4_addr; struct in6_addr v6_addr; } src; union { struct in_addr v4_addr; struct in6_addr v6_addr; } dst; uint16_t vlan_id; uint16_t pmtu; } __attribute__ ((aligned (sizeof(uint64_t)))); /* iscsi iface enabled/disabled setting */ #define ISCSI_IFACE_DISABLE 0x01 #define ISCSI_IFACE_ENABLE 0x02 /* ipv4 bootproto */ #define ISCSI_BOOTPROTO_STATIC 0x01 #define ISCSI_BOOTPROTO_DHCP 0x02 /* ipv6 addr autoconfig type */ #define ISCSI_IPV6_AUTOCFG_DISABLE 0x01 #define ISCSI_IPV6_AUTOCFG_ND_ENABLE 0x02 #define ISCSI_IPV6_AUTOCFG_DHCPV6_ENABLE 0x03 /* ipv6 link local addr type */ #define ISCSI_IPV6_LINKLOCAL_AUTOCFG_ENABLE 0x01 #define ISCSI_IPV6_LINKLOCAL_AUTOCFG_DISABLE 0x02 /* ipv6 router addr type */ #define ISCSI_IPV6_ROUTER_AUTOCFG_ENABLE 0x01 #define ISCSI_IPV6_ROUTER_AUTOCFG_DISABLE 0x02 #define ISCSI_IFACE_TYPE_IPV4 0x01 #define ISCSI_IFACE_TYPE_IPV6 0x02 #define ISCSI_MAX_VLAN_ID 4095 #define ISCSI_MAX_VLAN_PRIORITY 7 /* iscsi vlan enable/disabled setting */ #define ISCSI_VLAN_DISABLE 0x01 #define ISCSI_VLAN_ENABLE 0x02 /* iSCSI network params */ enum iscsi_net_param { ISCSI_NET_PARAM_IPV4_ADDR = 1, ISCSI_NET_PARAM_IPV4_SUBNET = 2, ISCSI_NET_PARAM_IPV4_GW = 3, ISCSI_NET_PARAM_IPV4_BOOTPROTO = 4, ISCSI_NET_PARAM_MAC = 5, ISCSI_NET_PARAM_IPV6_LINKLOCAL = 6, ISCSI_NET_PARAM_IPV6_ADDR = 7, ISCSI_NET_PARAM_IPV6_ROUTER = 8, ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG = 9, ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG = 10, ISCSI_NET_PARAM_IPV6_ROUTER_AUTOCFG = 11, ISCSI_NET_PARAM_IFACE_ENABLE = 12, ISCSI_NET_PARAM_VLAN_ID = 13, ISCSI_NET_PARAM_VLAN_PRIORITY = 14, ISCSI_NET_PARAM_VLAN_ENABLED = 15, ISCSI_NET_PARAM_VLAN_TAG = 16, ISCSI_NET_PARAM_IFACE_TYPE = 17, ISCSI_NET_PARAM_IFACE_NAME = 18, ISCSI_NET_PARAM_MTU = 19, ISCSI_NET_PARAM_PORT = 20, }; enum iscsi_conn_state { ISCSI_CONN_STATE_FREE, ISCSI_CONN_STATE_XPT_WAIT, ISCSI_CONN_STATE_IN_LOGIN, ISCSI_CONN_STATE_LOGGED_IN, ISCSI_CONN_STATE_IN_LOGOUT, ISCSI_CONN_STATE_LOGOUT_REQUESTED, ISCSI_CONN_STATE_CLEANUP_WAIT, }; /* * Common error codes */ enum iscsi_err { ISCSI_OK = 0, ISCSI_ERR_DATASN = ISCSI_ERR_BASE + 1, ISCSI_ERR_DATA_OFFSET = ISCSI_ERR_BASE + 2, ISCSI_ERR_MAX_CMDSN = ISCSI_ERR_BASE + 3, ISCSI_ERR_EXP_CMDSN = ISCSI_ERR_BASE + 4, ISCSI_ERR_BAD_OPCODE = ISCSI_ERR_BASE + 5, ISCSI_ERR_DATALEN = ISCSI_ERR_BASE + 6, ISCSI_ERR_AHSLEN = ISCSI_ERR_BASE + 7, ISCSI_ERR_PROTO = ISCSI_ERR_BASE + 8, ISCSI_ERR_LUN = ISCSI_ERR_BASE + 9, ISCSI_ERR_BAD_ITT = ISCSI_ERR_BASE + 10, ISCSI_ERR_CONN_FAILED = ISCSI_ERR_BASE + 11, ISCSI_ERR_R2TSN = ISCSI_ERR_BASE + 12, ISCSI_ERR_SESSION_FAILED = ISCSI_ERR_BASE + 13, ISCSI_ERR_HDR_DGST = ISCSI_ERR_BASE + 14, ISCSI_ERR_DATA_DGST = ISCSI_ERR_BASE + 15, ISCSI_ERR_PARAM_NOT_FOUND = ISCSI_ERR_BASE + 16, ISCSI_ERR_NO_SCSI_CMD = ISCSI_ERR_BASE + 17, ISCSI_ERR_INVALID_HOST = ISCSI_ERR_BASE + 18, ISCSI_ERR_XMIT_FAILED = ISCSI_ERR_BASE + 19, ISCSI_ERR_TCP_CONN_CLOSE = ISCSI_ERR_BASE + 20, ISCSI_ERR_SCSI_EH_SESSION_RST = ISCSI_ERR_BASE + 21, }; /* * iSCSI Parameters (RFC3720) */ enum iscsi_param { /* passed in using netlink set param */ ISCSI_PARAM_MAX_RECV_DLENGTH, ISCSI_PARAM_MAX_XMIT_DLENGTH, ISCSI_PARAM_HDRDGST_EN, ISCSI_PARAM_DATADGST_EN, ISCSI_PARAM_INITIAL_R2T_EN, ISCSI_PARAM_MAX_R2T, ISCSI_PARAM_IMM_DATA_EN, ISCSI_PARAM_FIRST_BURST, ISCSI_PARAM_MAX_BURST, ISCSI_PARAM_PDU_INORDER_EN, ISCSI_PARAM_DATASEQ_INORDER_EN, ISCSI_PARAM_ERL, ISCSI_PARAM_IFMARKER_EN, ISCSI_PARAM_OFMARKER_EN, ISCSI_PARAM_EXP_STATSN, ISCSI_PARAM_TARGET_NAME, ISCSI_PARAM_TPGT, ISCSI_PARAM_PERSISTENT_ADDRESS, ISCSI_PARAM_PERSISTENT_PORT, ISCSI_PARAM_SESS_RECOVERY_TMO, /* passed in through bind conn using transport_fd */ ISCSI_PARAM_CONN_PORT, ISCSI_PARAM_CONN_ADDRESS, ISCSI_PARAM_USERNAME, ISCSI_PARAM_USERNAME_IN, ISCSI_PARAM_PASSWORD, ISCSI_PARAM_PASSWORD_IN, ISCSI_PARAM_FAST_ABORT, ISCSI_PARAM_ABORT_TMO, ISCSI_PARAM_LU_RESET_TMO, ISCSI_PARAM_HOST_RESET_TMO, ISCSI_PARAM_PING_TMO, ISCSI_PARAM_RECV_TMO, ISCSI_PARAM_IFACE_NAME, ISCSI_PARAM_ISID, ISCSI_PARAM_INITIATOR_NAME, ISCSI_PARAM_TGT_RESET_TMO, ISCSI_PARAM_TARGET_ALIAS, /* must always be last */ ISCSI_PARAM_MAX, }; #define ISCSI_MAX_RECV_DLENGTH (1ULL << ISCSI_PARAM_MAX_RECV_DLENGTH) #define ISCSI_MAX_XMIT_DLENGTH (1ULL << ISCSI_PARAM_MAX_XMIT_DLENGTH) #define ISCSI_HDRDGST_EN (1ULL << ISCSI_PARAM_HDRDGST_EN) #define ISCSI_DATADGST_EN (1ULL << ISCSI_PARAM_DATADGST_EN) #define ISCSI_INITIAL_R2T_EN (1ULL << ISCSI_PARAM_INITIAL_R2T_EN) #define ISCSI_MAX_R2T (1ULL << ISCSI_PARAM_MAX_R2T) #define ISCSI_IMM_DATA_EN (1ULL << ISCSI_PARAM_IMM_DATA_EN) #define ISCSI_FIRST_BURST (1ULL << ISCSI_PARAM_FIRST_BURST) #define ISCSI_MAX_BURST (1ULL << ISCSI_PARAM_MAX_BURST) #define ISCSI_PDU_INORDER_EN (1ULL << ISCSI_PARAM_PDU_INORDER_EN) #define ISCSI_DATASEQ_INORDER_EN (1ULL << ISCSI_PARAM_DATASEQ_INORDER_EN) #define ISCSI_ERL (1ULL << ISCSI_PARAM_ERL) #define ISCSI_IFMARKER_EN (1ULL << ISCSI_PARAM_IFMARKER_EN) #define ISCSI_OFMARKER_EN (1ULL << ISCSI_PARAM_OFMARKER_EN) #define ISCSI_EXP_STATSN (1ULL << ISCSI_PARAM_EXP_STATSN) #define ISCSI_TARGET_NAME (1ULL << ISCSI_PARAM_TARGET_NAME) #define ISCSI_TPGT (1ULL << ISCSI_PARAM_TPGT) #define ISCSI_PERSISTENT_ADDRESS (1ULL << ISCSI_PARAM_PERSISTENT_ADDRESS) #define ISCSI_PERSISTENT_PORT (1ULL << ISCSI_PARAM_PERSISTENT_PORT) #define ISCSI_SESS_RECOVERY_TMO (1ULL << ISCSI_PARAM_SESS_RECOVERY_TMO) #define ISCSI_CONN_PORT (1ULL << ISCSI_PARAM_CONN_PORT) #define ISCSI_CONN_ADDRESS (1ULL << ISCSI_PARAM_CONN_ADDRESS) #define ISCSI_USERNAME (1ULL << ISCSI_PARAM_USERNAME) #define ISCSI_USERNAME_IN (1ULL << ISCSI_PARAM_USERNAME_IN) #define ISCSI_PASSWORD (1ULL << ISCSI_PARAM_PASSWORD) #define ISCSI_PASSWORD_IN (1ULL << ISCSI_PARAM_PASSWORD_IN) #define ISCSI_FAST_ABORT (1ULL << ISCSI_PARAM_FAST_ABORT) #define ISCSI_ABORT_TMO (1ULL << ISCSI_PARAM_ABORT_TMO) #define ISCSI_LU_RESET_TMO (1ULL << ISCSI_PARAM_LU_RESET_TMO) #define ISCSI_HOST_RESET_TMO (1ULL << ISCSI_PARAM_HOST_RESET_TMO) #define ISCSI_PING_TMO (1ULL << ISCSI_PARAM_PING_TMO) #define ISCSI_RECV_TMO (1ULL << ISCSI_PARAM_RECV_TMO) #define ISCSI_IFACE_NAME (1ULL << ISCSI_PARAM_IFACE_NAME) #define ISCSI_ISID (1ULL << ISCSI_PARAM_ISID) #define ISCSI_INITIATOR_NAME (1ULL << ISCSI_PARAM_INITIATOR_NAME) #define ISCSI_TGT_RESET_TMO (1ULL << ISCSI_PARAM_TGT_RESET_TMO) #define ISCSI_TARGET_ALIAS (1ULL << ISCSI_PARAM_TARGET_ALIAS) /* iSCSI HBA params */ enum iscsi_host_param { ISCSI_HOST_PARAM_HWADDRESS, ISCSI_HOST_PARAM_INITIATOR_NAME, ISCSI_HOST_PARAM_NETDEV_NAME, ISCSI_HOST_PARAM_IPADDRESS, ISCSI_HOST_PARAM_MAX, }; #define ISCSI_HOST_HWADDRESS (1ULL << ISCSI_HOST_PARAM_HWADDRESS) #define ISCSI_HOST_INITIATOR_NAME (1ULL << ISCSI_HOST_PARAM_INITIATOR_NAME) #define ISCSI_HOST_NETDEV_NAME (1ULL << ISCSI_HOST_PARAM_NETDEV_NAME) #define ISCSI_HOST_IPADDRESS (1ULL << ISCSI_HOST_PARAM_IPADDRESS) /* iSCSI PING status/error code */ enum iscsi_ping_status_code { ISCSI_PING_SUCCESS = 0, ISCSI_PING_FW_DISABLED = 0x1, ISCSI_PING_IPADDR_INVALID = 0x2, ISCSI_PING_LINKLOCAL_IPV6_ADDR_INVALID = 0x3, ISCSI_PING_TIMEOUT = 0x4, ISCSI_PING_INVALID_DEST_ADDR = 0x5, ISCSI_PING_OVERSIZE_PACKET = 0x6, ISCSI_PING_ICMP_ERROR = 0x7, ISCSI_PING_MAX_REQ_EXCEEDED = 0x8, ISCSI_PING_NO_ARP_RECEIVED = 0x9, }; #define iscsi_ptr(_handle) ((void*)(unsigned long)_handle) #define iscsi_handle(_ptr) ((uint64_t)(unsigned long)_ptr) /* * These flags presents iSCSI Data-Path capabilities. */ #define CAP_RECOVERY_L0 0x1 #define CAP_RECOVERY_L1 0x2 #define CAP_RECOVERY_L2 0x4 #define CAP_MULTI_R2T 0x8 #define CAP_HDRDGST 0x10 #define CAP_DATADGST 0x20 #define CAP_MULTI_CONN 0x40 #define CAP_TEXT_NEGO 0x80 #define CAP_MARKERS 0x100 #define CAP_FW_DB 0x200 #define CAP_SENDTARGETS_OFFLOAD 0x400 /* offload discovery process */ #define CAP_DATA_PATH_OFFLOAD 0x800 /* offload entire IO path */ #define CAP_DIGEST_OFFLOAD 0x1000 /* offload hdr and data digests */ #define CAP_PADDING_OFFLOAD 0x2000 /* offload padding insertion, removal, and verification */ #define CAP_LOGIN_OFFLOAD 0x4000 /* offload normal session login */ /* * These flags describes reason of stop_conn() call */ #define STOP_CONN_TERM 0x1 #define STOP_CONN_SUSPEND 0x2 #define STOP_CONN_RECOVER 0x3 #define ISCSI_STATS_CUSTOM_MAX 32 #define ISCSI_STATS_CUSTOM_DESC_MAX 64 struct iscsi_stats_custom { char desc[ISCSI_STATS_CUSTOM_DESC_MAX]; uint64_t value; }; /* * struct iscsi_stats - iSCSI Statistics (iSCSI MIB) * * Note: this structure contains counters collected on per-connection basis. */ struct iscsi_stats { /* octets */ uint64_t txdata_octets; uint64_t rxdata_octets; /* xmit pdus */ uint32_t noptx_pdus; uint32_t scsicmd_pdus; uint32_t tmfcmd_pdus; uint32_t login_pdus; uint32_t text_pdus; uint32_t dataout_pdus; uint32_t logout_pdus; uint32_t snack_pdus; /* recv pdus */ uint32_t noprx_pdus; uint32_t scsirsp_pdus; uint32_t tmfrsp_pdus; uint32_t textrsp_pdus; uint32_t datain_pdus; uint32_t logoutrsp_pdus; uint32_t r2t_pdus; uint32_t async_pdus; uint32_t rjt_pdus; /* errors */ uint32_t digest_err; uint32_t timeout_err; /* * iSCSI Custom Statistics support, i.e. Transport could * extend existing MIB statistics with its own specific statistics * up to ISCSI_STATS_CUSTOM_MAX */ uint32_t custom_length; struct iscsi_stats_custom custom[0] __attribute__ ((aligned (sizeof(uint64_t)))); }; enum chap_type_e { CHAP_TYPE_OUT, CHAP_TYPE_IN, }; #define ISCSI_CHAP_AUTH_NAME_MAX_LEN 256 #define ISCSI_CHAP_AUTH_SECRET_MAX_LEN 256 struct iscsi_chap_rec { uint16_t chap_tbl_idx; enum chap_type_e chap_type; char username[ISCSI_CHAP_AUTH_NAME_MAX_LEN]; uint8_t password[ISCSI_CHAP_AUTH_SECRET_MAX_LEN]; uint8_t password_length; }; #endif open-iscsi-2.0.873/include/iscsi_net_util.h000066400000000000000000000006521175631155400205700ustar00rootroot00000000000000#ifndef __ISCSI_NET_UTIL_h__ #define __ISCSI_NET_UTIL_h__ #define ISCSI_HWADDRESS_BUF_SIZE 18 extern int net_get_transport_name_from_netdev(char *netdev, char *transport); extern int net_get_netdev_from_hwaddress(char *hwaddress, char *netdev); extern int net_setup_netdev(char *netdev, char *local_ip, char *mask, char *gateway, char *remote_ip, int needs_bringup); extern int net_ifup_netdev(char *netdev); #endif open-iscsi-2.0.873/include/iscsi_proto.h000066400000000000000000000365101175631155400201120ustar00rootroot00000000000000/* * RFC 3720 (iSCSI) protocol data types * * Copyright (C) 2005 Dmitry Yusupov * Copyright (C) 2005 Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_PROTO_H #define ISCSI_PROTO_H #ifndef __KERNEL__ #include #endif #include #define ISCSI_DRAFT20_VERSION 0x00 /* default iSCSI listen port for incoming connections */ #define ISCSI_LISTEN_PORT 3260 /* Padding word length */ #define ISCSI_PAD_LEN 4 /* * useful common(control and data pathes) macro */ #define ntoh24(p) (((p)[0] << 16) | ((p)[1] << 8) | ((p)[2])) #define hton24(p, v) { \ p[0] = (((v) >> 16) & 0xFF); \ p[1] = (((v) >> 8) & 0xFF); \ p[2] = ((v) & 0xFF); \ } #define zero_data(p) {p[0]=0;p[1]=0;p[2]=0;} /* * If running svn modules we may need to define these. * This should not go upstream since this is already properly defined there */ #ifdef __CHECKER__ #define __bitwise__ __attribute__((bitwise)) #else #define __bitwise__ #endif #ifdef __CHECK_ENDIAN__ #define __bitwise __bitwise__ #else #define __bitwise #endif /* initiator tags; opaque for target */ typedef uint32_t __bitwise__ itt_t; /* below makes sense only for initiator that created this tag */ #define build_itt(itt, age) ((__force itt_t)\ ((itt) | ((age) << ISCSI_AGE_SHIFT))) #define get_itt(itt) ((__force uint32_t)(itt_t)(itt) & ISCSI_ITT_MASK) #define RESERVED_ITT ((__force itt_t)0xffffffff) /* * iSCSI Template Message Header */ struct iscsi_hdr { uint8_t opcode; uint8_t flags; /* Final bit */ uint8_t rsvd2[2]; uint8_t hlength; /* AHSs total length */ uint8_t dlength[3]; /* Data length */ uint8_t lun[8]; itt_t itt; /* Initiator Task Tag, opaque for target */ __be32 ttt; /* Target Task Tag */ __be32 statsn; __be32 exp_statsn; __be32 max_statsn; uint8_t other[12]; }; /************************* RFC 3720 Begin *****************************/ #define ISCSI_RESERVED_TAG 0xffffffff /* Opcode encoding bits */ #define ISCSI_OP_RETRY 0x80 #define ISCSI_OP_IMMEDIATE 0x40 #define ISCSI_OPCODE_MASK 0x3F /* Initiator Opcode values */ #define ISCSI_OP_NOOP_OUT 0x00 #define ISCSI_OP_SCSI_CMD 0x01 #define ISCSI_OP_SCSI_TMFUNC 0x02 #define ISCSI_OP_LOGIN 0x03 #define ISCSI_OP_TEXT 0x04 #define ISCSI_OP_SCSI_DATA_OUT 0x05 #define ISCSI_OP_LOGOUT 0x06 #define ISCSI_OP_SNACK 0x10 #define ISCSI_OP_VENDOR1_CMD 0x1c #define ISCSI_OP_VENDOR2_CMD 0x1d #define ISCSI_OP_VENDOR3_CMD 0x1e #define ISCSI_OP_VENDOR4_CMD 0x1f /* Target Opcode values */ #define ISCSI_OP_NOOP_IN 0x20 #define ISCSI_OP_SCSI_CMD_RSP 0x21 #define ISCSI_OP_SCSI_TMFUNC_RSP 0x22 #define ISCSI_OP_LOGIN_RSP 0x23 #define ISCSI_OP_TEXT_RSP 0x24 #define ISCSI_OP_SCSI_DATA_IN 0x25 #define ISCSI_OP_LOGOUT_RSP 0x26 #define ISCSI_OP_R2T 0x31 #define ISCSI_OP_ASYNC_EVENT 0x32 #define ISCSI_OP_REJECT 0x3f struct iscsi_ahs_hdr { __be16 ahslength; uint8_t ahstype; uint8_t ahspec[5]; }; #define ISCSI_AHSTYPE_CDB 1 #define ISCSI_AHSTYPE_RLENGTH 2 #define ISCSI_CDB_SIZE 16 /* iSCSI PDU Header */ struct iscsi_cmd { uint8_t opcode; uint8_t flags; __be16 rsvd2; uint8_t hlength; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; /* Initiator Task Tag */ __be32 data_length; __be32 cmdsn; __be32 exp_statsn; uint8_t cdb[ISCSI_CDB_SIZE]; /* SCSI Command Block */ /* Additional Data (Command Dependent) */ }; /* Command PDU flags */ #define ISCSI_FLAG_CMD_FINAL 0x80 #define ISCSI_FLAG_CMD_READ 0x40 #define ISCSI_FLAG_CMD_WRITE 0x20 #define ISCSI_FLAG_CMD_ATTR_MASK 0x07 /* 3 bits */ /* SCSI Command Attribute values */ #define ISCSI_ATTR_UNTAGGED 0 #define ISCSI_ATTR_SIMPLE 1 #define ISCSI_ATTR_ORDERED 2 #define ISCSI_ATTR_HEAD_OF_QUEUE 3 #define ISCSI_ATTR_ACA 4 struct iscsi_rlength_ahdr { __be16 ahslength; uint8_t ahstype; uint8_t reserved; __be32 read_length; }; /* Extended CDB AHS */ struct iscsi_ecdb_ahdr { __be16 ahslength; /* CDB length - 15, including reserved byte */ uint8_t ahstype; uint8_t reserved; /* 4-byte aligned extended CDB spillover */ uint8_t ecdb[260 - ISCSI_CDB_SIZE]; }; /* SCSI Response Header */ struct iscsi_cmd_rsp { uint8_t opcode; uint8_t flags; uint8_t response; uint8_t cmd_status; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd[8]; itt_t itt; /* Initiator Task Tag */ __be32 rsvd1; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; __be32 exp_datasn; __be32 bi_residual_count; __be32 residual_count; /* Response or Sense Data (optional) */ }; /* Command Response PDU flags */ #define ISCSI_FLAG_CMD_BIDI_OVERFLOW 0x10 #define ISCSI_FLAG_CMD_BIDI_UNDERFLOW 0x08 #define ISCSI_FLAG_CMD_OVERFLOW 0x04 #define ISCSI_FLAG_CMD_UNDERFLOW 0x02 /* iSCSI Status values. Valid if Rsp Selector bit is not set */ #define ISCSI_STATUS_CMD_COMPLETED 0 #define ISCSI_STATUS_TARGET_FAILURE 1 #define ISCSI_STATUS_SUBSYS_FAILURE 2 /* Asynchronous Event Header */ struct iscsi_async { uint8_t opcode; uint8_t flags; uint8_t rsvd2[2]; uint8_t rsvd3; uint8_t dlength[3]; uint8_t lun[8]; uint8_t rsvd4[8]; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; uint8_t async_event; uint8_t async_vcode; __be16 param1; __be16 param2; __be16 param3; uint8_t rsvd5[4]; }; /* iSCSI Event Codes */ #define ISCSI_ASYNC_MSG_SCSI_EVENT 0 #define ISCSI_ASYNC_MSG_REQUEST_LOGOUT 1 #define ISCSI_ASYNC_MSG_DROPPING_CONNECTION 2 #define ISCSI_ASYNC_MSG_DROPPING_ALL_CONNECTIONS 3 #define ISCSI_ASYNC_MSG_PARAM_NEGOTIATION 4 #define ISCSI_ASYNC_MSG_VENDOR_SPECIFIC 255 /* NOP-Out Message */ struct iscsi_nopout { uint8_t opcode; uint8_t flags; __be16 rsvd2; uint8_t rsvd3; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; /* Initiator Task Tag */ __be32 ttt; /* Target Transfer Tag */ __be32 cmdsn; __be32 exp_statsn; uint8_t rsvd4[16]; }; /* NOP-In Message */ struct iscsi_nopin { uint8_t opcode; uint8_t flags; __be16 rsvd2; uint8_t rsvd3; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; /* Initiator Task Tag */ __be32 ttt; /* Target Transfer Tag */ __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; uint8_t rsvd4[12]; }; /* SCSI Task Management Message Header */ struct iscsi_tm { uint8_t opcode; uint8_t flags; uint8_t rsvd1[2]; uint8_t hlength; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; /* Initiator Task Tag */ itt_t rtt; /* Reference Task Tag */ __be32 cmdsn; __be32 exp_statsn; __be32 refcmdsn; __be32 exp_datasn; uint8_t rsvd2[8]; }; #define ISCSI_FLAG_TM_FUNC_MASK 0x7F /* Function values */ #define ISCSI_TM_FUNC_ABORT_TASK 1 #define ISCSI_TM_FUNC_ABORT_TASK_SET 2 #define ISCSI_TM_FUNC_CLEAR_ACA 3 #define ISCSI_TM_FUNC_CLEAR_TASK_SET 4 #define ISCSI_TM_FUNC_LOGICAL_UNIT_RESET 5 #define ISCSI_TM_FUNC_TARGET_WARM_RESET 6 #define ISCSI_TM_FUNC_TARGET_COLD_RESET 7 #define ISCSI_TM_FUNC_TASK_REASSIGN 8 #define ISCSI_TM_FUNC_VALUE(hdr) ((hdr)->flags & ISCSI_FLAG_TM_FUNC_MASK) /* SCSI Task Management Response Header */ struct iscsi_tm_rsp { uint8_t opcode; uint8_t flags; uint8_t response; /* see Response values below */ uint8_t qualifier; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd2[8]; itt_t itt; /* Initiator Task Tag */ itt_t rtt; /* Reference Task Tag */ __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; uint8_t rsvd3[12]; }; /* Response values */ #define ISCSI_TMF_RSP_COMPLETE 0x00 #define ISCSI_TMF_RSP_NO_TASK 0x01 #define ISCSI_TMF_RSP_NO_LUN 0x02 #define ISCSI_TMF_RSP_TASK_ALLEGIANT 0x03 #define ISCSI_TMF_RSP_NO_FAILOVER 0x04 #define ISCSI_TMF_RSP_NOT_SUPPORTED 0x05 #define ISCSI_TMF_RSP_AUTH_FAILED 0x06 #define ISCSI_TMF_RSP_REJECTED 0xff /* Ready To Transfer Header */ struct iscsi_r2t_rsp { uint8_t opcode; uint8_t flags; uint8_t rsvd2[2]; uint8_t hlength; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; /* Initiator Task Tag */ __be32 ttt; /* Target Transfer Tag */ __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; __be32 r2tsn; __be32 data_offset; __be32 data_length; }; /* SCSI Data Hdr */ struct iscsi_data { uint8_t opcode; uint8_t flags; uint8_t rsvd2[2]; uint8_t rsvd3; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; __be32 ttt; __be32 rsvd4; __be32 exp_statsn; __be32 rsvd5; __be32 datasn; __be32 offset; __be32 rsvd6; /* Payload */ }; /* SCSI Data Response Hdr */ struct iscsi_data_rsp { uint8_t opcode; uint8_t flags; uint8_t rsvd2; uint8_t cmd_status; uint8_t hlength; uint8_t dlength[3]; uint8_t lun[8]; itt_t itt; __be32 ttt; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; __be32 datasn; __be32 offset; __be32 residual_count; }; /* Data Response PDU flags */ #define ISCSI_FLAG_DATA_ACK 0x40 #define ISCSI_FLAG_DATA_OVERFLOW 0x04 #define ISCSI_FLAG_DATA_UNDERFLOW 0x02 #define ISCSI_FLAG_DATA_STATUS 0x01 /* Text Header */ struct iscsi_text { uint8_t opcode; uint8_t flags; uint8_t rsvd2[2]; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd4[8]; itt_t itt; __be32 ttt; __be32 cmdsn; __be32 exp_statsn; uint8_t rsvd5[16]; /* Text - key=value pairs */ }; #define ISCSI_FLAG_TEXT_CONTINUE 0x40 /* Text Response Header */ struct iscsi_text_rsp { uint8_t opcode; uint8_t flags; uint8_t rsvd2[2]; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd4[8]; itt_t itt; __be32 ttt; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; uint8_t rsvd5[12]; /* Text Response - key:value pairs */ }; /* Login Header */ struct iscsi_login { uint8_t opcode; uint8_t flags; uint8_t max_version; /* Max. version supported */ uint8_t min_version; /* Min. version supported */ uint8_t hlength; uint8_t dlength[3]; uint8_t isid[6]; /* Initiator Session ID */ __be16 tsih; /* Target Session Handle */ itt_t itt; /* Initiator Task Tag */ __be16 cid; __be16 rsvd3; __be32 cmdsn; __be32 exp_statsn; uint8_t rsvd5[16]; }; /* Login PDU flags */ #define ISCSI_FLAG_LOGIN_TRANSIT 0x80 #define ISCSI_FLAG_LOGIN_CONTINUE 0x40 #define ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK 0x0C /* 2 bits */ #define ISCSI_FLAG_LOGIN_NEXT_STAGE_MASK 0x03 /* 2 bits */ #define ISCSI_LOGIN_CURRENT_STAGE(flags) \ ((flags & ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK) >> 2) #define ISCSI_LOGIN_NEXT_STAGE(flags) \ (flags & ISCSI_FLAG_LOGIN_NEXT_STAGE_MASK) /* Login Response Header */ struct iscsi_login_rsp { uint8_t opcode; uint8_t flags; uint8_t max_version; /* Max. version supported */ uint8_t active_version; /* Active version */ uint8_t hlength; uint8_t dlength[3]; uint8_t isid[6]; /* Initiator Session ID */ __be16 tsih; /* Target Session Handle */ itt_t itt; /* Initiator Task Tag */ __be32 rsvd3; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; uint8_t status_class; /* see Login RSP ststus classes below */ uint8_t status_detail; /* see Login RSP Status details below */ uint8_t rsvd4[10]; }; /* Login stage (phase) codes for CSG, NSG */ #define ISCSI_INITIAL_LOGIN_STAGE -1 #define ISCSI_SECURITY_NEGOTIATION_STAGE 0 #define ISCSI_OP_PARMS_NEGOTIATION_STAGE 1 #define ISCSI_FULL_FEATURE_PHASE 3 /* Login Status response classes */ #define ISCSI_STATUS_CLS_SUCCESS 0x00 #define ISCSI_STATUS_CLS_REDIRECT 0x01 #define ISCSI_STATUS_CLS_INITIATOR_ERR 0x02 #define ISCSI_STATUS_CLS_TARGET_ERR 0x03 /* Login Status response detail codes */ /* Class-0 (Success) */ #define ISCSI_LOGIN_STATUS_ACCEPT 0x00 /* Class-1 (Redirection) */ #define ISCSI_LOGIN_STATUS_TGT_MOVED_TEMP 0x01 #define ISCSI_LOGIN_STATUS_TGT_MOVED_PERM 0x02 /* Class-2 (Initiator Error) */ #define ISCSI_LOGIN_STATUS_INIT_ERR 0x00 #define ISCSI_LOGIN_STATUS_AUTH_FAILED 0x01 #define ISCSI_LOGIN_STATUS_TGT_FORBIDDEN 0x02 #define ISCSI_LOGIN_STATUS_TGT_NOT_FOUND 0x03 #define ISCSI_LOGIN_STATUS_TGT_REMOVED 0x04 #define ISCSI_LOGIN_STATUS_NO_VERSION 0x05 #define ISCSI_LOGIN_STATUS_ISID_ERROR 0x06 #define ISCSI_LOGIN_STATUS_MISSING_FIELDS 0x07 #define ISCSI_LOGIN_STATUS_CONN_ADD_FAILED 0x08 #define ISCSI_LOGIN_STATUS_NO_SESSION_TYPE 0x09 #define ISCSI_LOGIN_STATUS_NO_SESSION 0x0a #define ISCSI_LOGIN_STATUS_INVALID_REQUEST 0x0b /* Class-3 (Target Error) */ #define ISCSI_LOGIN_STATUS_TARGET_ERROR 0x00 #define ISCSI_LOGIN_STATUS_SVC_UNAVAILABLE 0x01 #define ISCSI_LOGIN_STATUS_NO_RESOURCES 0x02 /* Logout Header */ struct iscsi_logout { uint8_t opcode; uint8_t flags; uint8_t rsvd1[2]; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd2[8]; itt_t itt; /* Initiator Task Tag */ __be16 cid; uint8_t rsvd3[2]; __be32 cmdsn; __be32 exp_statsn; uint8_t rsvd4[16]; }; /* Logout PDU flags */ #define ISCSI_FLAG_LOGOUT_REASON_MASK 0x7F /* logout reason_code values */ #define ISCSI_LOGOUT_REASON_CLOSE_SESSION 0 #define ISCSI_LOGOUT_REASON_CLOSE_CONNECTION 1 #define ISCSI_LOGOUT_REASON_RECOVERY 2 #define ISCSI_LOGOUT_REASON_AEN_REQUEST 3 /* Logout Response Header */ struct iscsi_logout_rsp { uint8_t opcode; uint8_t flags; uint8_t response; /* see Logout response values below */ uint8_t rsvd2; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd3[8]; itt_t itt; /* Initiator Task Tag */ __be32 rsvd4; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; __be32 rsvd5; __be16 t2wait; __be16 t2retain; __be32 rsvd6; }; /* logout response status values */ #define ISCSI_LOGOUT_SUCCESS 0 #define ISCSI_LOGOUT_CID_NOT_FOUND 1 #define ISCSI_LOGOUT_RECOVERY_UNSUPPORTED 2 #define ISCSI_LOGOUT_CLEANUP_FAILED 3 /* SNACK Header */ struct iscsi_snack { uint8_t opcode; uint8_t flags; uint8_t rsvd2[14]; itt_t itt; __be32 begrun; __be32 runlength; __be32 exp_statsn; __be32 rsvd3; __be32 exp_datasn; uint8_t rsvd6[8]; }; /* SNACK PDU flags */ #define ISCSI_FLAG_SNACK_TYPE_MASK 0x0F /* 4 bits */ /* Reject Message Header */ struct iscsi_reject { uint8_t opcode; uint8_t flags; uint8_t reason; uint8_t rsvd2; uint8_t hlength; uint8_t dlength[3]; uint8_t rsvd3[8]; __be32 ffffffff; uint8_t rsvd4[4]; __be32 statsn; __be32 exp_cmdsn; __be32 max_cmdsn; __be32 datasn; uint8_t rsvd5[8]; /* Text - Rejected hdr */ }; /* Reason for Reject */ #define ISCSI_REASON_CMD_BEFORE_LOGIN 1 #define ISCSI_REASON_DATA_DIGEST_ERROR 2 #define ISCSI_REASON_DATA_SNACK_REJECT 3 #define ISCSI_REASON_PROTOCOL_ERROR 4 #define ISCSI_REASON_CMD_NOT_SUPPORTED 5 #define ISCSI_REASON_IMM_CMD_REJECT 6 #define ISCSI_REASON_TASK_IN_PROGRESS 7 #define ISCSI_REASON_INVALID_SNACK 8 #define ISCSI_REASON_BOOKMARK_INVALID 9 #define ISCSI_REASON_BOOKMARK_NO_RESOURCES 10 #define ISCSI_REASON_NEGOTIATION_RESET 11 /* Max. number of Key=Value pairs in a text message */ #define MAX_KEY_VALUE_PAIRS 8192 /* maximum length for text keys/values */ #define KEY_MAXLEN 64 #define VALUE_MAXLEN 255 #define TARGET_NAME_MAXLEN VALUE_MAXLEN #define ISCSI_DEF_MAX_RECV_SEG_LEN 8192 #define ISCSI_MIN_MAX_RECV_SEG_LEN 512 #define ISCSI_MAX_MAX_RECV_SEG_LEN 16777215 #define ISCSI_DEF_FIRST_BURST_LEN 65536 #define ISCSI_MIN_FIRST_BURST_LEN 512 #define ISCSI_MAX_FIRST_BURST_LEN 16777215 #define ISCSI_DEF_MAX_BURST_LEN 262144 #define ISCSI_MIN_MAX_BURST_LEN 512 #define ISCSI_MAX_MAX_BURST_LEN 16777215 #define ISCSI_DEF_TIME2WAIT 2 /************************* RFC 3720 End *****************************/ #endif /* ISCSI_PROTO_H */ open-iscsi-2.0.873/include/list.h000066400000000000000000000051111175631155400165210ustar00rootroot00000000000000#ifndef __LIST_H__ #define __LIST_H__ #include /* taken from linux kernel */ #undef offsetof #ifdef __compiler_offsetof #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) #else #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif #define list_container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) struct list_head { struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } static inline int list_empty(const struct list_head *head) { return head->next == head; } #define list_entry(ptr, type, member) \ list_container_of(ptr, type, member) #define list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) #define list_for_each_entry(pos, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member); \ &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member)) #define list_for_each_entry_safe(pos, n, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member), \ n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member)) static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; new->prev = prev; prev->next = new; } static inline void list_add(struct list_head *new, struct list_head *head) { __list_add(new, head, head->next); } static inline void list_add_tail(struct list_head *new, struct list_head *head) { __list_add(new, head->prev, head); } static inline void __list_del(struct list_head * prev, struct list_head * next) { next->prev = prev; prev->next = next; } static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); entry->next = entry->prev = NULL; } static inline void list_del_init(struct list_head *entry) { __list_del(entry->prev, entry->next); INIT_LIST_HEAD(entry); } /** * list_move_tail - delete from one list and add as another's tail * @list: the entry to move * @head: the head that will follow our entry */ static inline void list_move_tail(struct list_head *list, struct list_head *head) { __list_del(list->prev, list->next); list_add_tail(list, head); } #endif open-iscsi-2.0.873/include/sysdeps.h000066400000000000000000000017201175631155400172420ustar00rootroot00000000000000/* * wrapping of libc features and kernel interfaces * * Copyright (C) 2005-2006 Kay Sievers * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef _SYSDEPS_H_ #define _SYSDEPS_H_ extern size_t strlcpy(char *dst, const char *src, size_t size); extern size_t strlcat(char *dst, const char *src, size_t size); #endif open-iscsi-2.0.873/kernel/000077500000000000000000000000001175631155400152345ustar00rootroot00000000000000open-iscsi-2.0.873/kernel/.gitignore000066400000000000000000000001771175631155400172310ustar00rootroot00000000000000.*.ko.cmd .*.o.cmd .tmp_versions Module.symvers cur_patched has_*_patch *.ko *.mod.* open_iscsi_compat.h *.orig Module.markers open-iscsi-2.0.873/kernel/2.6.14-19_compat.patch000066400000000000000000001130471175631155400206050ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 8ef3f41..14c6706 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -445,11 +445,9 @@ static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task, if (!task->sc) iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count); else { - struct scsi_data_buffer *sdb = scsi_out(task->sc); - - err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, offset, - count); + err = iscsi_sw_tcp_send_data_prep(conn, scsi_sglist(task->sc), + scsi_sg_count(task->sc), + offset, count); } if (err) { @@ -782,7 +780,11 @@ iscsi_sw_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, shost->max_lun = iscsi_max_lun; shost->max_id = 0; shost->max_channel = 0; +#ifndef SCSI_MAX_VARLEN_CDB_SIZE + shost->max_cmd_len = 16; +#else shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE; +#endif if (iscsi_host_add(shost, NULL)) goto free_host; @@ -830,6 +832,9 @@ static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev) } static struct scsi_host_template iscsi_sw_tcp_sht = { +#if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,24) + .use_sg_chaining = ENABLE_SG_CHAINING, +#endif .module = THIS_MODULE, .name = "iSCSI Initiator over TCP/IP", .queuecommand = iscsi_queuecommand, @@ -840,7 +845,7 @@ static struct scsi_host_template iscsi_sw_tcp_sht = { .cmd_per_lun = ISCSI_DEF_CMD_PER_LUN, .eh_abort_handler = iscsi_eh_abort, .eh_device_reset_handler= iscsi_eh_device_reset, - .eh_target_reset_handler= iscsi_eh_target_reset, + .eh_host_reset_handler = iscsi_eh_target_reset, .use_clustering = DISABLE_CLUSTERING, .slave_configure = iscsi_sw_tcp_slave_configure, .proc_name = "iscsi_tcp", diff --git a/iscsi_tcp.h b/iscsi_tcp.h index f9a4044..ab20530 100644 --- a/iscsi_tcp.h +++ b/iscsi_tcp.h @@ -22,6 +22,8 @@ #ifndef ISCSI_SW_TCP_H #define ISCSI_SW_TCP_H +#include "open_iscsi_compat.h" + #include "libiscsi.h" #include "libiscsi_tcp.h" diff --git a/libiscsi.c b/libiscsi.c index 457ecfe..756b171 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -24,7 +24,10 @@ #include #include #include +#include +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) #include +#endif #include #include #include @@ -38,6 +41,8 @@ #include "scsi_transport_iscsi.h" #include "libiscsi.h" +#include "open_iscsi_compat.h" + /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */ #define SNA32_CHECK 2147483648UL @@ -199,7 +204,7 @@ static int iscsi_prep_bidi_ahs(struct iscsi_task *task) sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; - rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); + rlen_ahdr->read_length = cpu_to_be32(scsi_bufflen(sc)); debug_scsi("bidi-in rlen_ahdr->read_length(%d) " "rlen_ahdr->ahslength(%d)\n", @@ -267,7 +272,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { - unsigned out_len = scsi_out(sc)->length; + unsigned out_len = scsi_bufflen(sc); struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->data_length = cpu_to_be32(out_len); @@ -313,7 +318,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); - hdr->data_length = cpu_to_be32(scsi_in(sc)->length); + hdr->data_length = cpu_to_be32(scsi_bufflen(sc)); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; @@ -340,7 +345,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), - scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, + scsi_bidi_cmnd(sc) ? scsi_bufflen(sc) : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; } @@ -432,12 +437,7 @@ static void fail_command(struct iscsi_conn *conn, struct iscsi_task *task, conn->session->queued_cmdsn--; sc->result = err; - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); if (conn->task == task) conn->task = NULL; @@ -631,7 +631,7 @@ invalid_datalen: goto out; } - senselen = get_unaligned_be16(data); + senselen = be16_to_cpu(get_unaligned((__be16 *) data)); if (datalen < senselen) goto invalid_datalen; @@ -647,8 +647,8 @@ invalid_datalen: if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -697,8 +697,8 @@ iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -1244,10 +1244,9 @@ again: return rc; } -static void iscsi_xmitworker(struct work_struct *work) +static void iscsi_xmitworker(void *data) { - struct iscsi_conn *conn = - container_of(work, struct iscsi_conn, xmitwork); + struct iscsi_conn *conn = data; int rc; /* * serialize Xmit worker on a per-connection basis. @@ -1408,12 +1407,7 @@ prepd_fault: fault: spin_unlock(&session->lock); debug_scsi("iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); done(sc); spin_lock(host->host_lock); return 0; @@ -1998,8 +1992,10 @@ int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev) if (!shost->can_queue) shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX; +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,16) if (!shost->transportt->eh_timed_out) shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out; +#endif return scsi_add_host(shost, pdev); } EXPORT_SYMBOL_GPL(iscsi_host_add); @@ -2295,7 +2291,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, INIT_LIST_HEAD(&conn->mgmtqueue); INIT_LIST_HEAD(&conn->xmitqueue); INIT_LIST_HEAD(&conn->requeue); - INIT_WORK(&conn->xmitwork, iscsi_xmitworker); + INIT_WORK(&conn->xmitwork, iscsi_xmitworker, conn); /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); diff --git a/libiscsi.h b/libiscsi.h index a261e2c..1274bc9 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -25,13 +25,16 @@ #include #include +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16) #include -#include -#include +#endif + #include "iscsi_proto.h" #include "iscsi_if.h" #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct scsi_host_template; struct scsi_device; diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 92cb13d..ea7dd8d 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -357,6 +357,17 @@ iscsi_segment_seek_sg(struct iscsi_segment *segment, debug_scsi("iscsi_segment_seek_sg offset %u size %llu\n", offset, size); + + /* + * older kernels could send use_sg=0 for commands like sgio + * or scsi-ml commands. + */ + if (!sg_count) { + iscsi_segment_init_linear(segment, (void *)sg_list + offset, + size, done, hash); + return 0; + } + __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { debug_scsi("sg %d, len %u offset %u\n", i, sg->length, @@ -469,7 +480,7 @@ static int iscsi_tcp_data_in(struct iscsi_conn *conn, struct iscsi_task *task) struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr; int datasn = be32_to_cpu(rhdr->datasn); - unsigned total_in_length = scsi_in(task->sc)->length; + unsigned total_in_length = scsi_bufflen(task->sc); iscsi_update_cmdsn(conn->session, (struct iscsi_nopin*)rhdr); if (tcp_conn->in.datalen == 0) @@ -557,11 +568,11 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); - if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { + if (r2t->data_offset + r2t->data_length > scsi_bufflen(task->sc)) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, - r2t->data_offset, scsi_out(task->sc)->length); + r2t->data_offset, scsi_bufflen(task->sc)); __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; @@ -660,7 +671,6 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; - struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd @@ -679,8 +689,8 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) tcp_task->data_offset, tcp_conn->in.datalen); rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, - sdb->table.sgl, - sdb->table.nents, + scsi_sglist(task->sc), + scsi_sg_count(task->sc), tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index 3bacef5..5ea284d 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -21,6 +21,7 @@ #ifndef LIBISCSI_TCP_H #define LIBISCSI_TCP_H +#include "open_iscsi_compat.h" #include "libiscsi.h" struct iscsi_tcp_conn; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..2dbe4ce --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,303 @@ +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#include +#include +#include +#include + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#ifndef bool +#define bool int +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif +#else +/* not a redhat kernel */ +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} +#endif +#else +/* not a redhat kernel */ +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} +#endif + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} +#endif +#else +/* not a redhat kernel */ +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} +#endif + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index 4781d81..98d1351 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -21,7 +21,10 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include +#include +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16) #include +#endif #include #include #include @@ -41,13 +44,13 @@ struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; - struct device dev; + struct class_device cdev; - struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; + struct class_device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; - struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; + struct class_device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; - struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; + struct class_device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ @@ -64,12 +67,12 @@ static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) -#define dev_to_iscsi_internal(_dev) \ - container_of(_dev, struct iscsi_internal, dev) +#define cdev_to_iscsi_internal(_cdev) \ + container_of(_cdev, struct iscsi_internal, cdev) -static void iscsi_transport_release(struct device *dev) +static void iscsi_transport_release(struct class_device *cdev) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); kfree(priv); } @@ -79,33 +82,31 @@ static void iscsi_transport_release(struct device *dev) */ static struct class iscsi_transport_class = { .name = "iscsi_transport", - .dev_release = iscsi_transport_release, + .release = iscsi_transport_release, }; static ssize_t -show_transport_handle(struct device *dev, struct device_attribute *attr, - char *buf) +show_transport_handle(struct class_device *cdev, char *buf) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } -static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); +static CLASS_DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ -show_transport_##name(struct device *dev, \ - struct device_attribute *attr,char *buf) \ +show_transport_##name(struct class_device *cdev, char *buf) \ { \ - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ -static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); +static CLASS_DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { - &dev_attr_handle.attr, - &dev_attr_caps.attr, + &class_device_attr_handle.attr, + &class_device_attr_caps.attr, NULL, }; @@ -113,6 +114,7 @@ static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; +#if 0 /* * iSCSI endpoint attrs */ @@ -236,9 +238,10 @@ struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); +#endif static int iscsi_setup_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -257,7 +260,7 @@ static int iscsi_setup_host(struct transport_container *tc, struct device *dev, } static int iscsi_remove_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -497,10 +500,9 @@ static int iscsi_user_scan(struct Scsi_Host *shost, uint channel, iscsi_user_scan_session); } -static void iscsi_scan_session(struct work_struct *work) +static void iscsi_scan_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, scan_work); + struct iscsi_cls_session *session = data; struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; struct iscsi_scan_data scan_data; @@ -513,11 +515,9 @@ static void iscsi_scan_session(struct work_struct *work) atomic_dec(&ihost->nr_scans); } -static void session_recovery_timedout(struct work_struct *work) +static void session_recovery_timedout(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - recovery_work.work); + struct iscsi_cls_session *session = data; unsigned long flags; iscsi_cls_session_printk(KERN_INFO, session, @@ -543,11 +543,9 @@ static void session_recovery_timedout(struct work_struct *work) scsi_target_unblock(&session->dev); } -static void __iscsi_unblock_session(struct work_struct *work) +static void __iscsi_unblock_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - unblock_work); + struct iscsi_cls_session *session = data; struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; @@ -567,10 +565,12 @@ static void __iscsi_unblock_session(struct work_struct *work) * the async scanning code (drivers like iscsi_tcp do login and * scanning from userspace). */ +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) if (shost->hostt->scan_finished) { if (queue_work(ihost->scan_workq, &session->scan_work)) atomic_inc(&ihost->nr_scans); } +#endif } /** @@ -590,11 +590,9 @@ void iscsi_unblock_session(struct iscsi_cls_session *session) } EXPORT_SYMBOL_GPL(iscsi_unblock_session); -static void __iscsi_block_session(struct work_struct *work) +static void __iscsi_block_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - block_work); + struct iscsi_cls_session *session = data; unsigned long flags; spin_lock_irqsave(&session->lock, flags); @@ -611,11 +609,9 @@ void iscsi_block_session(struct iscsi_cls_session *session) } EXPORT_SYMBOL_GPL(iscsi_block_session); -static void __iscsi_unbind_session(struct work_struct *work) +static void __iscsi_unbind_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - unbind_work); + struct iscsi_cls_session *session = data; struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; @@ -658,12 +654,12 @@ iscsi_alloc_session(struct Scsi_Host *shost, struct iscsi_transport *transport, session->transport = transport; session->recovery_tmo = 120; session->state = ISCSI_SESSION_FREE; - INIT_DELAYED_WORK(&session->recovery_work, session_recovery_timedout); + INIT_WORK(&session->recovery_work, session_recovery_timedout, session); INIT_LIST_HEAD(&session->sess_list); - INIT_WORK(&session->unblock_work, __iscsi_unblock_session); - INIT_WORK(&session->block_work, __iscsi_block_session); - INIT_WORK(&session->unbind_work, __iscsi_unbind_session); - INIT_WORK(&session->scan_work, iscsi_scan_session); + INIT_WORK(&session->unblock_work, __iscsi_unblock_session, session); + INIT_WORK(&session->block_work, __iscsi_block_session, session); + INIT_WORK(&session->unbind_work, __iscsi_unbind_session, session); + INIT_WORK(&session->scan_work, iscsi_scan_session, session); spin_lock_init(&session->lock); /* this is released in the dev's release function */ @@ -723,7 +719,8 @@ int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id) } session->target_id = id; - dev_set_name(&session->dev, "session%u", session->sid); + snprintf(session->dev.bus_id, BUS_ID_SIZE, "session%u", + session->sid); err = device_add(&session->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, @@ -822,7 +819,7 @@ void iscsi_remove_session(struct iscsi_cls_session *session) scsi_target_unblock(&session->dev); /* flush running scans then delete devices */ flush_workqueue(ihost->scan_workq); - __iscsi_unbind_session(&session->unbind_work); + __iscsi_unbind_session(session); /* hw iscsi may not have removed all connections from session */ err = device_for_each_child(&session->dev, NULL, @@ -896,7 +893,8 @@ iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid) if (!get_device(&session->dev)) goto free_conn; - dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid); + snprintf(conn->dev.bus_id, BUS_ID_SIZE, "connection%d:%u", + session->sid, cid); conn->dev.parent = &session->dev; conn->dev.release = iscsi_conn_release; err = device_register(&conn->dev); @@ -1305,6 +1303,8 @@ static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { + return -ENOSYS; +#if 0 struct iscsi_endpoint *ep; struct sockaddr *dst_addr; int rc = 0; @@ -1345,6 +1345,8 @@ iscsi_if_transport_ep(struct iscsi_transport *transport, break; } return rc; + +#endif } static int @@ -1426,6 +1428,9 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: + err = -ENOSYS; + break; +#if 0 ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; @@ -1437,6 +1442,7 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; +#endif case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) @@ -1519,55 +1525,70 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) } /* - * Get message from skb. Each message is processed by iscsi_if_recv_msg. - * Malformed skbs with wrong lengths or invalid creds are not processed. + * Get message from skb (based on rtnetlink_rcv_skb). Each message is + * processed by iscsi_if_recv_msg. Malformed skbs with wrong lengths or + * invalid creds are discarded silently. */ static void -iscsi_if_rx(struct sk_buff *skb) +iscsi_if_rx(struct sock *sk, int len) { + struct sk_buff *skb; + mutex_lock(&rx_queue_mutex); - while (skb->len >= NLMSG_SPACE(0)) { - int err; - uint32_t rlen; - struct nlmsghdr *nlh; - struct iscsi_uevent *ev; - - nlh = nlmsg_hdr(skb); - if (nlh->nlmsg_len < sizeof(*nlh) || - skb->len < nlh->nlmsg_len) { - break; + while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { + if (NETLINK_CREDS(skb)->uid) { + skb_pull(skb, skb->len); + goto free_skb; } - ev = NLMSG_DATA(nlh); - rlen = NLMSG_ALIGN(nlh->nlmsg_len); - if (rlen > skb->len) - rlen = skb->len; + while (skb->len >= NLMSG_SPACE(0)) { + int err; + uint32_t rlen; + struct nlmsghdr *nlh; + struct iscsi_uevent *ev; - err = iscsi_if_recv_msg(skb, nlh); - if (err) { - ev->type = ISCSI_KEVENT_IF_ERROR; - ev->iferror = err; - } - do { - /* - * special case for GET_STATS: - * on success - sending reply and stats from - * inside of if_recv_msg(), - * on error - fall through. - */ - if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + nlh = nlmsg_hdr(skb); + if (nlh->nlmsg_len < sizeof(*nlh) || + skb->len < nlh->nlmsg_len) { break; - err = iscsi_if_send_reply( - NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, - nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); - } while (err < 0 && err != -ECONNREFUSED); - skb_pull(skb, rlen); + } + + ev = NLMSG_DATA(nlh); + rlen = NLMSG_ALIGN(nlh->nlmsg_len); + if (rlen > skb->len) + rlen = skb->len; + + err = iscsi_if_recv_msg(skb, nlh); + if (err) { + ev->type = ISCSI_KEVENT_IF_ERROR; + ev->iferror = err; + } + do { + /* + * special case for GET_STATS: + * on success - sending reply and stats from + * inside of if_recv_msg(), + * on error - fall through. + */ + if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + break; + err = iscsi_if_send_reply( + NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, + nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); + } while (err < 0 && err != -ECONNREFUSED); + skb_pull(skb, rlen); + } +free_skb: + kfree_skb(skb); } mutex_unlock(&rx_queue_mutex); } +#define iscsi_cdev_to_conn(_cdev) \ + iscsi_dev_to_conn(_cdev->dev) + #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ -struct device_attribute dev_attr_##_prefix##_##_name = \ +struct class_device_attribute class_device_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* @@ -1575,10 +1596,9 @@ struct device_attribute dev_attr_##_prefix##_##_name = \ */ #define iscsi_conn_attr_show(param) \ static ssize_t \ -show_conn_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_conn_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ + struct iscsi_cls_conn *conn = iscsi_cdev_to_conn(cdev); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } @@ -1602,16 +1622,17 @@ iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); +#define iscsi_cdev_to_session(_cdev) \ + iscsi_dev_to_session(_cdev->dev) + /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ -show_session_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_session_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ @@ -1645,10 +1666,9 @@ iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t -show_priv_session_state(struct device *dev, struct device_attribute *attr, - char *buf) +show_priv_session_state(struct class_device *cdev, char *buf) { - struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, @@ -1656,11 +1676,9 @@ static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ -show_priv_session_##field(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_priv_session_##field(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev);\ return sprintf(buf, format"\n", session->field); \ } @@ -1675,10 +1693,9 @@ iscsi_priv_session_attr(recovery_tmo, "%d"); */ #define iscsi_host_attr_show(param) \ static ssize_t \ -show_host_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_host_param_##param(struct class_device *cdev, char *buf) \ { \ - struct Scsi_Host *shost = transport_class_to_shost(dev); \ + struct Scsi_Host *shost = transport_class_to_shost(cdev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } @@ -1695,7 +1712,7 @@ iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ - priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_priv_sess_##field; \ count++; \ } while (0) @@ -1703,7 +1720,7 @@ do { \ #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->session_attrs[count] = &dev_attr_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_sess_##field; \ count++; \ } \ } while (0) @@ -1711,7 +1728,7 @@ do { \ #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->conn_attrs[count] = &dev_attr_conn_##field; \ + priv->conn_attrs[count] = &class_device_attr_conn_##field; \ count++; \ } \ } while (0) @@ -1719,7 +1736,7 @@ do { \ #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ - priv->host_attrs[count] = &dev_attr_host_##field; \ + priv->host_attrs[count] = &class_device_attr_host_##field; \ count++; \ } \ } while (0) @@ -1808,19 +1825,21 @@ iscsi_register_transport(struct iscsi_transport *tt) INIT_LIST_HEAD(&priv->list); priv->daemon_pid = -1; priv->iscsi_transport = tt; +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16) priv->t.user_scan = iscsi_user_scan; +#endif if (!(tt->caps & CAP_DATA_PATH_OFFLOAD)) priv->t.create_work_queue = 1; - priv->dev.class = &iscsi_transport_class; - dev_set_name(&priv->dev, "%s", tt->name); - err = device_register(&priv->dev); + priv->cdev.class = &iscsi_transport_class; + snprintf(priv->cdev.class_id, BUS_ID_SIZE, "%s", tt->name); + err = class_device_register(&priv->cdev); if (err) goto free_priv; - err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); + err = sysfs_create_group(&priv->cdev.kobj, &iscsi_transport_group); if (err) - goto unregister_dev; + goto unregister_cdev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; @@ -1899,9 +1918,8 @@ iscsi_register_transport(struct iscsi_transport *tt) printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; -unregister_dev: - device_unregister(&priv->dev); - return NULL; +unregister_cdev: + class_device_unregister(&priv->cdev); free_priv: kfree(priv); return NULL; @@ -1928,8 +1946,8 @@ int iscsi_unregister_transport(struct iscsi_transport *tt) transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); - sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); - device_unregister(&priv->dev); + sysfs_remove_group(&priv->cdev.kobj, &iscsi_transport_group); + class_device_unregister(&priv->cdev); mutex_unlock(&rx_queue_mutex); return 0; @@ -1949,13 +1967,14 @@ static __init int iscsi_transport_init(void) if (err) return err; +#if 0 err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; - +#endif err = transport_class_register(&iscsi_host_class); if (err) - goto unregister_endpoint_class; + goto unregister_transport_class; err = transport_class_register(&iscsi_connection_class); if (err) @@ -1986,8 +2005,10 @@ unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); +#if 0 unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); +#endif unregister_transport_class: class_unregister(&iscsi_transport_class); return err; @@ -2000,7 +2021,9 @@ static void __exit iscsi_transport_exit(void) transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); +#if 0 class_unregister(&iscsi_endpoint_class); +#endif class_unregister(&iscsi_transport_class); } diff --git a/scsi_transport_iscsi.h b/scsi_transport_iscsi.h index 27d067a..6fa17f6 100644 --- a/scsi_transport_iscsi.h +++ b/scsi_transport_iscsi.h @@ -25,9 +25,14 @@ #include #include +#include +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16) #include +#endif #include "iscsi_if.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct iscsi_transport; struct iscsi_endpoint; @@ -184,7 +189,7 @@ struct iscsi_cls_session { /* recovery fields */ int recovery_tmo; - struct delayed_work recovery_work; + struct work_struct recovery_work; unsigned int target_id; -- 1.5.6.6 open-iscsi-2.0.873/kernel/2.6.14-23_compat.patch000066400000000000000000001277561175631155400206140ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..13636d4 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " @@ -480,10 +481,9 @@ static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task, if (!task->sc) iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count); else { - struct scsi_data_buffer *sdb = scsi_out(task->sc); - err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, offset, + err = iscsi_sw_tcp_send_data_prep(conn, scsi_sglist(task->sc), + scsi_sg_count(task->sc), offset, count); } @@ -860,12 +860,6 @@ static void iscsi_sw_tcp_session_destroy(struct iscsi_cls_session *cls_session) iscsi_host_free(shost); } -static int iscsi_sw_tcp_slave_alloc(struct scsi_device *sdev) -{ - set_bit(QUEUE_FLAG_BIDI, &sdev->request_queue->queue_flags); - return 0; -} - static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev) { blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_ANY); @@ -883,10 +877,9 @@ static struct scsi_host_template iscsi_sw_tcp_sht = { .max_sectors = 0xFFFF, .cmd_per_lun = ISCSI_DEF_CMD_PER_LUN, .eh_abort_handler = iscsi_eh_abort, + .eh_host_reset_handler = iscsi_eh_recover_target, .eh_device_reset_handler= iscsi_eh_device_reset, - .eh_target_reset_handler = iscsi_eh_recover_target, .use_clustering = DISABLE_CLUSTERING, - .slave_alloc = iscsi_sw_tcp_slave_alloc, .slave_configure = iscsi_sw_tcp_slave_configure, .target_alloc = iscsi_target_alloc, .proc_name = "iscsi_tcp", diff --git a/libiscsi.c b/libiscsi.c index 59e3a5f..ee9716e 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -24,7 +24,10 @@ #include #include #include +#include +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) #include +#endif #include #include #include @@ -39,6 +42,8 @@ #include "scsi_transport_iscsi.h" #include "libiscsi.h" +#include "open_iscsi_compat.h" + static int iscsi_dbg_lib_conn; module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int, S_IRUGO | S_IWUSR); @@ -256,7 +261,7 @@ static int iscsi_prep_bidi_ahs(struct iscsi_task *task) sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; - rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); + rlen_ahdr->read_length = cpu_to_be32(scsi_bufflen(sc)); ISCSI_DBG_SESSION(task->conn->session, "bidi-in rlen_ahdr->read_length(%d) " @@ -411,7 +416,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { - unsigned out_len = scsi_out(sc)->length; + unsigned out_len = scsi_bufflen(sc); struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->data_length = cpu_to_be32(out_len); @@ -457,7 +462,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); - hdr->data_length = cpu_to_be32(scsi_in(sc)->length); + hdr->data_length = cpu_to_be32(scsi_bufflen(sc)); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; @@ -486,7 +491,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), - scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, + scsi_bidi_cmnd(sc) ? scsi_bufflen(sc) : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; @@ -518,7 +523,7 @@ static void iscsi_free_task(struct iscsi_task *task) if (conn->login_task == task) return; - kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); + __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; @@ -648,12 +653,7 @@ static void fail_scsi_task(struct iscsi_task *task, int err) state = ISCSI_TASK_ABRT_TMF; sc->result = err << 16; - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); iscsi_complete_task(task, state); } @@ -738,7 +738,7 @@ __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } @@ -853,7 +853,7 @@ invalid_datalen: goto out; } - senselen = get_unaligned_be16(data); + senselen = be16_to_cpu(get_unaligned((__be16 *) data)); if (datalen < senselen) goto invalid_datalen; @@ -870,8 +870,8 @@ invalid_datalen: if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -920,8 +920,8 @@ iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -1568,7 +1568,7 @@ static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, { struct iscsi_task *task; - if (!kfifo_out(&conn->session->cmdpool.queue, + if (!__kfifo_get(conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; @@ -1717,7 +1717,11 @@ reject: ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason); spin_lock(host->host_lock); +#if (defined RHELC1) || (defined SLEC1) + return SCSI_MLQUEUE_DEVICE_BUSY; +#else return SCSI_MLQUEUE_TARGET_BUSY; +#endif prepd_fault: sc->scsi_done = NULL; @@ -1726,33 +1730,16 @@ fault: spin_unlock(&session->lock); ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); done(sc); spin_lock(host->host_lock); return 0; } EXPORT_SYMBOL_GPL(iscsi_queuecommand); -int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) +int iscsi_change_queue_depth(struct scsi_device *sdev, int depth) { - switch (reason) { - case SCSI_QDEPTH_DEFAULT: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - case SCSI_QDEPTH_QFULL: - scsi_track_queue_full(sdev, depth); - break; - case SCSI_QDEPTH_RAMP_UP: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - default: - return -EOPNOTSUPP; - } + scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); @@ -2524,7 +2511,12 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) if (q->pool == NULL) return -ENOMEM; - kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); + q->queue = kfifo_init((void*)q->pool, max * sizeof(void*), + GFP_KERNEL, NULL); + if (IS_ERR(q->queue)) { + q->queue = NULL; + goto enomem; + } for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); @@ -2532,7 +2524,7 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) q->max = i; goto enomem; } - kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); + __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { @@ -2555,6 +2547,7 @@ void iscsi_pool_free(struct iscsi_pool *q) for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); + kfree(q->queue); } EXPORT_SYMBOL_GPL(iscsi_pool_free); @@ -2882,7 +2875,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); @@ -2902,7 +2895,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, return cls_conn; login_task_data_alloc_fail: - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); @@ -2965,7 +2958,7 @@ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; diff --git a/libiscsi.h b/libiscsi.h index 0563539..4be9333 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -231,7 +231,7 @@ struct iscsi_conn { }; struct iscsi_pool { - struct kfifo queue; /* FIFO Queue */ + struct kfifo *queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; @@ -334,8 +334,7 @@ struct iscsi_host { /* * scsi host template */ -extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, - int reason); +extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 1122de4..c590df2 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -361,6 +361,17 @@ iscsi_segment_seek_sg(struct iscsi_segment *segment, struct scatterlist *sg; unsigned int i; + /* + * older kernels could send use_sg=0 for commands like sgio + * or scsi-ml commands. + */ + + if (!sg_count) { + iscsi_segment_init_linear(segment, (void *)sg_list + offset, + size, done, hash); + return 0; + } + __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { if (offset < sg->length) { @@ -446,15 +457,15 @@ void iscsi_tcp_cleanup_task(struct iscsi_task *task) return; /* flush task's r2t queues */ - while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + while (__kfifo_get(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } @@ -472,7 +483,7 @@ static int iscsi_tcp_data_in(struct iscsi_conn *conn, struct iscsi_task *task) struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr; int datasn = be32_to_cpu(rhdr->datasn); - unsigned total_in_length = scsi_in(task->sc)->length; + unsigned total_in_length = scsi_bufflen(task->sc); /* * lib iscsi will update this in the completion handling if there @@ -542,7 +553,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) return 0; } - rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); + rc = __kfifo_get(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " @@ -555,7 +566,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -566,12 +577,12 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); - if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { + if (r2t->data_offset + r2t->data_length > scsi_bufflen(task->sc)) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, - r2t->data_offset, scsi_out(task->sc)->length); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + r2t->data_offset, scsi_bufflen(task->sc)); + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -581,7 +592,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; - kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); + __kfifo_put(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); @@ -669,7 +680,6 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; - struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd @@ -689,8 +699,8 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) tcp_conn->in.datalen); task->last_xfer = jiffies; rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, - sdb->table.sgl, - sdb->table.nents, + scsi_sglist(task->sc), + scsi_sg_count(task->sc), tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, @@ -952,7 +962,7 @@ int iscsi_tcp_task_init(struct iscsi_task *task) return conn->session->tt->init_pdu(task, 0, task->data_count); } - BUG_ON(kfifo_len(&tcp_task->r2tqueue)); + BUG_ON(__kfifo_len(tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ @@ -983,7 +993,7 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); - kfifo_in(&tcp_task->r2tpool.queue, + __kfifo_put(tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; @@ -991,12 +1001,9 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) } if (r2t == NULL) { - if (kfifo_out(&tcp_task->r2tqueue, - (void *)&tcp_task->r2t, sizeof(void *)) != - sizeof(void *)) - r2t = NULL; - else - r2t = tcp_task->r2t; + __kfifo_get(tcp_task->r2tqueue, + (void *)&tcp_task->r2t, sizeof(void *)); + r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } @@ -1131,8 +1138,9 @@ int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) } /* R2T xmit queue */ - if (kfifo_alloc(&tcp_task->r2tqueue, - session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { + tcp_task->r2tqueue = kfifo_alloc( + session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL); + if (tcp_task->r2tqueue == ERR_PTR(-ENOMEM)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } @@ -1145,7 +1153,7 @@ r2t_alloc_fail: struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; @@ -1160,7 +1168,7 @@ void iscsi_tcp_r2tpool_free(struct iscsi_session *session) struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index c020eee..3bacef5 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -80,7 +80,7 @@ struct iscsi_tcp_task { int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; - struct kfifo r2tqueue; + struct kfifo *r2tqueue; void *dd_data; }; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..e6511d3 --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,399 @@ +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#include +#include +#include +#include +#include + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#ifdef RHEL_RELEASE_CODE +#if (RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(6, 0)) +#define RHELC1 1 +#endif +#endif + +#ifdef SLE_VERSION_CODE +#if (SLE_VERSION_CODE < SLE_VERSION(11, 0, 0)) +#define SLEC1 1 +#endif +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,19) +struct delayed_work { + struct work_struct work; +}; + +#define cancel_delayed_work(_dwork) cancel_delayed_work(&(_dwork)->work) +#define INIT_DELAYED_WORK(_work,_func) INIT_WORK(&(_work)->work, _func) + +static inline void INIT_WORK_compat(struct work_struct *work, void *func) +{ + INIT_WORK(work, func, work); +} + +#undef INIT_WORK +#define INIT_WORK(_work, _func) INIT_WORK_compat(_work, _func) +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) +#ifdef RHEL_RELEASE_CODE && \ + RHEL_RELEASE_CODE != RHEL_RELEASE_VERSION(4,8) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#if !defined SLEC1 +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} +#endif +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)) \ + && !(defined RHELC1) +static inline int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +static inline int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} +#endif +#endif + +#ifndef bool +#define bool int +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) && \ + RHEL_RELEASE_CODE != RHEL_RELEASE_VERSION(4,8) +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif +#else +/* not a redhat kernel */ +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} +#endif +#else +/* not a redhat kernel */ +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} +#endif + +#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22)) && \ + !defined(SLEC1) +/** + * scsilun_to_int: convert a scsi_lun to an int + * @scsilun: struct scsi_lun to be converted. + * + * Description: + * Convert @scsilun from a struct scsi_lun to a four byte host byte-ordered + * integer, and return the result. The caller must check for + * truncation before using this function. + * + * Notes: + * The struct scsi_lun is assumed to be four levels, with each level + * effectively containing a SCSI byte-ordered (big endian) short; the + * addressing bits of each level are ignored (the highest two bits). + * For a description of the LUN format, post SCSI-3 see the SCSI + * Architecture Model, for SCSI-3 see the SCSI Controller Commands. + * + * Given a struct scsi_lun of: 0a 04 0b 03 00 00 00 00, this function returns + * the integer: 0x0b030a04 + **/ +static inline int scsilun_to_int(struct scsi_lun *scsilun) +{ + int i; + unsigned int lun; + + lun = 0; + for (i = 0; i < sizeof(lun); i += 2) + lun = lun | (((scsilun->scsi_lun[i] << 8) | + scsilun->scsi_lun[i + 1]) << (i * 8)); + return lun; +} +#endif + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +#ifdef RHEL_RELEASE_VERSION +#if RHEL_RELEASE_CODE < RHEL_RELEASE_VERSION(5,2) +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} +#endif +#else +/* not a redhat kernel */ +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} +#endif + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#ifdef SLE_VERSION_CODE +#if SLE_VERSION_CODE == SLE_VERSION(10,2,0) + +static inline unsigned fls_long(unsigned long l) +{ + if (sizeof(l) == 4) + return fls(l); + return fls64(l); +} + +#endif +#endif + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + +#ifndef SCSI_MAX_VARLEN_CDB_SIZE +#define SCSI_MAX_VARLEN_CDB_SIZE 16 +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index fed8c9e..362bd4d 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -73,13 +73,13 @@ struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; - struct device dev; + struct class_device cdev; - struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; + struct class_device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; - struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; + struct class_device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; - struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; + struct class_device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ @@ -96,12 +96,12 @@ static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) -#define dev_to_iscsi_internal(_dev) \ - container_of(_dev, struct iscsi_internal, dev) +#define cdev_to_iscsi_internal(_cdev) \ + container_of(_cdev, struct iscsi_internal, cdev) -static void iscsi_transport_release(struct device *dev) +static void iscsi_transport_release(struct class_device *cdev) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); kfree(priv); } @@ -111,33 +111,31 @@ static void iscsi_transport_release(struct device *dev) */ static struct class iscsi_transport_class = { .name = "iscsi_transport", - .dev_release = iscsi_transport_release, + .release = iscsi_transport_release, }; static ssize_t -show_transport_handle(struct device *dev, struct device_attribute *attr, - char *buf) +show_transport_handle(struct class_device *cdev, char *buf) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } -static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); +static CLASS_DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ -show_transport_##name(struct device *dev, \ - struct device_attribute *attr,char *buf) \ +show_transport_##name(struct class_device *cdev, char *buf) \ { \ - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ -static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); +static CLASS_DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { - &dev_attr_handle.attr, - &dev_attr_caps.attr, + &class_device_attr_handle.attr, + &class_device_attr_caps.attr, NULL, }; @@ -155,27 +153,28 @@ static struct attribute_group iscsi_transport_group = { struct device_attribute dev_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) -static void iscsi_endpoint_release(struct device *dev) +static void iscsi_endpoint_release(struct class_device *cdev) { - struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); + struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(cdev); kfree(ep); } static struct class iscsi_endpoint_class = { .name = "iscsi_endpoint", - .dev_release = iscsi_endpoint_release, + .release = iscsi_endpoint_release, }; static ssize_t -show_ep_handle(struct device *dev, struct device_attribute *attr, char *buf) +show_ep_handle(struct class_device *cdev, char *buf) { - struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); + struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(cdev); return sprintf(buf, "%llu\n", (unsigned long long) ep->id); } -static ISCSI_ATTR(ep, handle, S_IRUGO, show_ep_handle, NULL); +static struct class_device_attribute class_device_attr_ep_handle = + __ATTR(handle, S_IRUGO, show_ep_handle, NULL); static struct attribute *iscsi_endpoint_attrs[] = { - &dev_attr_ep_handle.attr, + &class_device_attr_ep_handle.attr, NULL, }; @@ -185,26 +184,15 @@ static struct attribute_group iscsi_endpoint_group = { #define ISCSI_MAX_EPID -1 -static int iscsi_match_epid(struct device *dev, void *data) -{ - struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); - uint64_t *epid = (uint64_t *) data; - - return *epid == ep->id; -} - struct iscsi_endpoint * iscsi_create_endpoint(int dd_size) { - struct device *dev; struct iscsi_endpoint *ep; uint64_t id; int err; for (id = 1; id < ISCSI_MAX_EPID; id++) { - dev = class_find_device(&iscsi_endpoint_class, NULL, &id, - iscsi_match_epid); - if (!dev) + if (!iscsi_lookup_endpoint(id)) break; } if (id == ISCSI_MAX_EPID) { @@ -219,8 +207,9 @@ iscsi_create_endpoint(int dd_size) ep->id = id; ep->dev.class = &iscsi_endpoint_class; - dev_set_name(&ep->dev, "ep-%llu", (unsigned long long) id); - err = device_register(&ep->dev); + snprintf(ep->dev.class_id, BUS_ID_SIZE, "ep-%llu", + (unsigned long long) id); + err = class_device_register(&ep->dev); if (err) goto free_ep; @@ -233,7 +222,7 @@ iscsi_create_endpoint(int dd_size) return ep; unregister_dev: - device_unregister(&ep->dev); + class_device_unregister(&ep->dev); return NULL; free_ep: @@ -245,32 +234,38 @@ EXPORT_SYMBOL_GPL(iscsi_create_endpoint); void iscsi_destroy_endpoint(struct iscsi_endpoint *ep) { sysfs_remove_group(&ep->dev.kobj, &iscsi_endpoint_group); - device_unregister(&ep->dev); + class_device_unregister(&ep->dev); } EXPORT_SYMBOL_GPL(iscsi_destroy_endpoint); struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) { - struct iscsi_endpoint *ep; - struct device *dev; - - dev = class_find_device(&iscsi_endpoint_class, NULL, &handle, - iscsi_match_epid); - if (!dev) - return NULL; + struct iscsi_endpoint *ep = NULL; + struct class_device *cdev; + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22) + down_read(&iscsi_endpoint_class.subsys.rwsem); +#else + spin_lock(&iscsi_endpoint_class.subsys.list_lock); +#endif + list_for_each_entry(cdev, &iscsi_endpoint_class.children, node) { + ep = iscsi_dev_to_endpoint(cdev); + if (ep->id == handle) + break; + ep = NULL; + } +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22) + up_read(&iscsi_endpoint_class.subsys.rwsem); +#else + spin_unlock(&iscsi_endpoint_class.subsys.list_lock); +#endif - ep = iscsi_dev_to_endpoint(dev); - /* - * we can drop this now because the interface will prevent - * removals and lookups from racing. - */ - put_device(dev); return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); static int iscsi_setup_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -571,8 +566,6 @@ static void __iscsi_unblock_session(struct work_struct *work) struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, unblock_work); - struct Scsi_Host *shost = iscsi_session_to_shost(session); - struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; ISCSI_DBG_TRANS_SESSION(session, "Unblocking session\n"); @@ -586,15 +579,6 @@ static void __iscsi_unblock_session(struct work_struct *work) spin_unlock_irqrestore(&session->lock, flags); /* start IO */ scsi_target_unblock(&session->dev); - /* - * Only do kernel scanning if the driver is properly hooked into - * the async scanning code (drivers like iscsi_tcp do login and - * scanning from userspace). - */ - if (shost->hostt->scan_finished) { - if (scsi_queue_work(shost, &session->scan_work)) - atomic_inc(&ihost->nr_scans); - } ISCSI_DBG_TRANS_SESSION(session, "Completed unblocking session\n"); } @@ -750,7 +734,7 @@ int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id) } session->target_id = id; - dev_set_name(&session->dev, "session%u", session->sid); + snprintf(session->dev.bus_id, BUS_ID_SIZE, "session%u", session->sid); err = device_add(&session->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, @@ -930,7 +914,8 @@ iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid) if (!get_device(&session->dev)) goto free_conn; - dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid); + snprintf(conn->dev.bus_id, BUS_ID_SIZE, "connection%d:%u", + session->sid, cid); conn->dev.parent = &session->dev; conn->dev.release = iscsi_conn_release; err = device_register(&conn->dev); @@ -1003,7 +988,15 @@ iscsi_if_transport_lookup(struct iscsi_transport *tt) static int iscsi_multicast_skb(struct sk_buff *skb, uint32_t group, gfp_t gfp) { - return nlmsg_multicast(nls, skb, 0, group, gfp); + int err; + + NETLINK_CB(skb).dst_group = group; + + err = netlink_broadcast(nls, skb, 0, group, gfp); + if (err > 0) + err = 0; + + return err; } int iscsi_recv_pdu(struct iscsi_cls_conn *conn, struct iscsi_hdr *hdr, @@ -1643,51 +1636,65 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) * Malformed skbs with wrong lengths or invalid creds are not processed. */ static void -iscsi_if_rx(struct sk_buff *skb) +iscsi_if_rx(struct sock *sk, int len) { - mutex_lock(&rx_queue_mutex); - while (skb->len >= NLMSG_SPACE(0)) { - int err; - uint32_t rlen; - struct nlmsghdr *nlh; - struct iscsi_uevent *ev; - uint32_t group; - - nlh = nlmsg_hdr(skb); - if (nlh->nlmsg_len < sizeof(*nlh) || - skb->len < nlh->nlmsg_len) { - break; - } - - ev = NLMSG_DATA(nlh); - rlen = NLMSG_ALIGN(nlh->nlmsg_len); - if (rlen > skb->len) - rlen = skb->len; + struct sk_buff *skb; - err = iscsi_if_recv_msg(skb, nlh, &group); - if (err) { - ev->type = ISCSI_KEVENT_IF_ERROR; - ev->iferror = err; + mutex_lock(&rx_queue_mutex); + while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { + if (NETLINK_CREDS(skb)->uid) { + skb_pull(skb, skb->len); + goto free_skb; } - do { - /* - * special case for GET_STATS: - * on success - sending reply and stats from - * inside of if_recv_msg(), - * on error - fall through. - */ - if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + + while (skb->len >= NLMSG_SPACE(0)) { + int err; + uint32_t rlen; + struct nlmsghdr *nlh; + struct iscsi_uevent *ev; + uint32_t group; + + nlh = nlmsg_hdr(skb); + if (nlh->nlmsg_len < sizeof(*nlh) || + skb->len < nlh->nlmsg_len) { break; - err = iscsi_if_send_reply(group, nlh->nlmsg_seq, - nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); - } while (err < 0 && err != -ECONNREFUSED); - skb_pull(skb, rlen); + } + + ev = NLMSG_DATA(nlh); + rlen = NLMSG_ALIGN(nlh->nlmsg_len); + if (rlen > skb->len) + rlen = skb->len; + + err = iscsi_if_recv_msg(skb, nlh, &group); + if (err) { + ev->type = ISCSI_KEVENT_IF_ERROR; + ev->iferror = err; + } + do { + /* + * special case for GET_STATS: + * on success - sending reply and stats from + * inside of if_recv_msg(), + * on error - fall through. + */ + if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + break; + err = iscsi_if_send_reply(group, nlh->nlmsg_seq, + nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); + } while (err < 0 && err != -ECONNREFUSED); + skb_pull(skb, rlen); + } +free_skb: + kfree_skb(skb); } mutex_unlock(&rx_queue_mutex); } +#define iscsi_cdev_to_conn(_cdev) \ + iscsi_dev_to_conn(_cdev->dev) + #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ -struct device_attribute dev_attr_##_prefix##_##_name = \ +struct class_device_attribute class_device_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* @@ -1695,10 +1702,9 @@ struct device_attribute dev_attr_##_prefix##_##_name = \ */ #define iscsi_conn_attr_show(param) \ static ssize_t \ -show_conn_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_conn_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ + struct iscsi_cls_conn *conn = iscsi_cdev_to_conn(cdev); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } @@ -1722,16 +1728,18 @@ iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); +#define iscsi_cdev_to_session(_cdev) \ + iscsi_dev_to_session(_cdev->dev) + /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ -show_session_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_session_param_##param(struct class_device *cdev, char *buf) \ { \ struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + iscsi_cdev_to_session(cdev); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ @@ -1766,10 +1774,9 @@ iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t -show_priv_session_state(struct device *dev, struct device_attribute *attr, - char *buf) +show_priv_session_state(struct class_device *cdev, char *buf) { - struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, @@ -1777,11 +1784,10 @@ static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ -show_priv_session_##field(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_priv_session_##field(struct class_device *cdev, char *buf) \ { \ struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + iscsi_cdev_to_session(cdev); \ return sprintf(buf, format"\n", session->field); \ } @@ -1796,10 +1802,9 @@ iscsi_priv_session_attr(recovery_tmo, "%d"); */ #define iscsi_host_attr_show(param) \ static ssize_t \ -show_host_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_host_param_##param(struct class_device *cdev, char *buf) \ { \ - struct Scsi_Host *shost = transport_class_to_shost(dev); \ + struct Scsi_Host *shost = transport_class_to_shost(cdev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } @@ -1816,7 +1821,7 @@ iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ - priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_priv_sess_##field; \ count++; \ } while (0) @@ -1824,7 +1829,7 @@ do { \ #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->session_attrs[count] = &dev_attr_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_sess_##field; \ count++; \ } \ } while (0) @@ -1832,7 +1837,7 @@ do { \ #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->conn_attrs[count] = &dev_attr_conn_##field; \ + priv->conn_attrs[count] = &class_device_attr_conn_##field; \ count++; \ } \ } while (0) @@ -1840,7 +1845,7 @@ do { \ #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ - priv->host_attrs[count] = &dev_attr_host_##field; \ + priv->host_attrs[count] = &class_device_attr_host_##field; \ count++; \ } \ } while (0) @@ -1931,15 +1936,15 @@ iscsi_register_transport(struct iscsi_transport *tt) priv->t.user_scan = iscsi_user_scan; priv->t.create_work_queue = 1; - priv->dev.class = &iscsi_transport_class; - dev_set_name(&priv->dev, "%s", tt->name); - err = device_register(&priv->dev); + priv->cdev.class = &iscsi_transport_class; + snprintf(priv->cdev.class_id, BUS_ID_SIZE, "%s", tt->name); + err = class_device_register(&priv->cdev); if (err) goto free_priv; - err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); + err = sysfs_create_group(&priv->cdev.kobj, &iscsi_transport_group); if (err) - goto unregister_dev; + goto unregister_cdev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; @@ -2019,8 +2024,8 @@ iscsi_register_transport(struct iscsi_transport *tt) printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; -unregister_dev: - device_unregister(&priv->dev); +unregister_cdev: + class_device_unregister(&priv->cdev); return NULL; free_priv: kfree(priv); @@ -2048,8 +2053,8 @@ int iscsi_unregister_transport(struct iscsi_transport *tt) transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); - sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); - device_unregister(&priv->dev); + sysfs_remove_group(&priv->cdev.kobj, &iscsi_transport_group); + class_device_unregister(&priv->cdev); mutex_unlock(&rx_queue_mutex); return 0; diff --git a/scsi_transport_iscsi.h b/scsi_transport_iscsi.h index ef4b697..a633ee0 100644 --- a/scsi_transport_iscsi.h +++ b/scsi_transport_iscsi.h @@ -27,6 +27,7 @@ #include #include #include "iscsi_if.h" +#include "open_iscsi_compat.h" struct scsi_transport_template; struct iscsi_transport; @@ -219,7 +220,7 @@ extern void iscsi_host_for_each_session(struct Scsi_Host *shost, struct iscsi_endpoint { void *dd_data; /* LLD private data */ - struct device dev; + struct class_device dev; uint64_t id; }; -- 1.6.6.1 open-iscsi-2.0.873/kernel/2.6.16-suse.patch000066400000000000000000000706631175631155400200000ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 908b541..dfd8e31 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -426,6 +426,17 @@ iscsi_segment_seek_sg(struct iscsi_segment *segment, debug_scsi("iscsi_segment_seek_sg offset %u size %llu\n", offset, size); + + /* + * older kernels could send use_sg=0 for commands like sgio + * or scsi-ml commands. + */ + if (!sg_count) { + iscsi_segment_init_linear(segment, (void *)sg_list + offset, + size, done, hash); + return 0; + } + __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { debug_scsi("sg %d, len %u offset %u\n", i, sg->length, @@ -536,7 +547,7 @@ iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_task *task) struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; int datasn = be32_to_cpu(rhdr->datasn); - unsigned total_in_length = scsi_in(sc)->length; + unsigned total_in_length = scsi_bufflen(sc); iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr); if (tcp_conn->in.datalen == 0) @@ -568,7 +579,7 @@ iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || res_count <= total_in_length)) - scsi_in(sc)->resid = res_count; + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; @@ -679,11 +690,11 @@ iscsi_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); - if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { + if (r2t->data_offset + r2t->data_length > scsi_bufflen(task->sc)) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, - r2t->data_offset, scsi_out(task->sc)->length); + r2t->data_offset, scsi_bufflen(task->sc)); __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; @@ -783,7 +794,6 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; - struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd @@ -801,8 +811,8 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) tcp_task->data_offset, tcp_conn->in.datalen); rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, - sdb->table.sgl, - sdb->table.nents, + scsi_sglist(task->sc), + scsi_sg_count(task->sc), tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, @@ -1369,8 +1379,8 @@ iscsi_tcp_task_init(struct iscsi_task *task) return 0; /* If we have immediate data, attach a payload */ - err = iscsi_tcp_send_data_prep(conn, scsi_out(sc)->table.sgl, - scsi_out(sc)->table.nents, + err = iscsi_tcp_send_data_prep(conn, scsi_sglist(sc), + scsi_sg_count(sc), 0, task->imm_count); if (err) return err; @@ -1393,7 +1403,6 @@ iscsi_tcp_task_xmit(struct iscsi_task *task) struct iscsi_conn *conn = task->conn; struct iscsi_tcp_task *tcp_task = task->dd_data; struct scsi_cmnd *sc = task->sc; - struct scsi_data_buffer *sdb; int rc = 0; flush: @@ -1413,7 +1422,6 @@ flush: if (sc->sc_data_direction != DMA_TO_DEVICE) return 0; - sdb = scsi_out(sc); if (task->unsol_count != 0) { struct iscsi_data *hdr = &tcp_task->unsol_dtask.hdr; @@ -1428,8 +1436,8 @@ flush: task->itt, tcp_task->sent, task->data_count); iscsi_tcp_send_hdr_prep(conn, hdr, sizeof(*hdr)); - rc = iscsi_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, tcp_task->sent, + rc = iscsi_tcp_send_data_prep(conn, scsi_sglist(sc), + scsi_sg_count(sc), tcp_task->sent, task->data_count); if (rc) goto fail; @@ -1475,8 +1483,8 @@ flush: iscsi_tcp_send_hdr_prep(conn, &r2t->dtask.hdr, sizeof(struct iscsi_hdr)); - rc = iscsi_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, + rc = iscsi_tcp_send_data_prep(conn, scsi_sglist(sc), + scsi_sg_count(sc), r2t->data_offset + r2t->sent, r2t->data_count); if (rc) @@ -1864,7 +1872,11 @@ iscsi_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, shost->max_lun = iscsi_max_lun; shost->max_id = 0; shost->max_channel = 0; +#ifndef SCSI_MAX_VARLEN_CDB_SIZE + shost->max_cmd_len = 16; +#else shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE; +#endif if (iscsi_host_add(shost, NULL)) goto free_host; @@ -1917,6 +1929,9 @@ static int iscsi_tcp_slave_configure(struct scsi_device *sdev) } static struct scsi_host_template iscsi_sht = { +#if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,24) + .use_sg_chaining = ENABLE_SG_CHAINING, +#endif .module = THIS_MODULE, .name = "iSCSI Initiator over TCP/IP", .queuecommand = iscsi_queuecommand, diff --git a/iscsi_tcp.h b/iscsi_tcp.h index 68423e8..1796c96 100644 --- a/iscsi_tcp.h +++ b/iscsi_tcp.h @@ -24,6 +24,8 @@ #include "libiscsi.h" +#include "open_iscsi_compat.h" + struct crypto_hash; struct socket; struct iscsi_tcp_conn; diff --git a/libiscsi.c b/libiscsi.c index dfeaed3..0fb0705 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -24,7 +24,10 @@ #include #include #include +#include +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) #include +#endif #include #include #include @@ -187,7 +190,7 @@ static int iscsi_prep_bidi_ahs(struct iscsi_task *task) sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; - rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); + rlen_ahdr->read_length = cpu_to_be32(scsi_bufflen(sc)); debug_scsi("bidi-in rlen_ahdr->read_length(%d) " "rlen_ahdr->ahslength(%d)\n", @@ -242,7 +245,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { - unsigned out_len = scsi_out(sc)->length; + unsigned out_len = scsi_bufflen(sc); hdr->data_length = cpu_to_be32(out_len); hdr->flags |= ISCSI_FLAG_CMD_WRITE; /* @@ -286,7 +289,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); - hdr->data_length = cpu_to_be32(scsi_in(sc)->length); + hdr->data_length = cpu_to_be32(scsi_bufflen(sc)); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; @@ -314,7 +317,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), - scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, + scsi_bidi_cmnd(sc) ? scsi_bufflen(sc) : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; } @@ -412,12 +415,7 @@ static void fail_command(struct iscsi_conn *conn, struct iscsi_task *task, return; sc->result = err; - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); if (conn->task == task) conn->task = NULL; @@ -592,7 +590,7 @@ invalid_datalen: goto out; } - senselen = get_unaligned_be16(data); + senselen = be16_to_cpu(get_unaligned((__be16 *) data)); if (datalen < senselen) goto invalid_datalen; @@ -608,8 +606,8 @@ invalid_datalen: if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -1127,10 +1125,9 @@ again: return rc; } -static void iscsi_xmitworker(struct work_struct *work) +static void iscsi_xmitworker(void *data) { - struct iscsi_conn *conn = - container_of(work, struct iscsi_conn, xmitwork); + struct iscsi_conn *conn = data; int rc; /* * serialize Xmit worker on a per-connection basis. @@ -1273,12 +1270,7 @@ reject: fault: spin_unlock(&session->lock); debug_scsi("iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); done(sc); spin_lock(host->host_lock); return 0; @@ -2099,7 +2091,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, INIT_LIST_HEAD(&conn->mgmtqueue); INIT_LIST_HEAD(&conn->xmitqueue); INIT_LIST_HEAD(&conn->requeue); - INIT_WORK(&conn->xmitwork, iscsi_xmitworker); + INIT_WORK(&conn->xmitwork, iscsi_xmitworker, conn); /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); diff --git a/libiscsi.h b/libiscsi.h index cfc5fa6..64508d8 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -32,6 +32,8 @@ #include "iscsi_proto.h" #include "iscsi_if.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct scsi_host_template; struct scsi_device; diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index 535e461..1ae65fb 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -41,13 +41,13 @@ struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; - struct device dev; + struct class_device cdev; - struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; + struct class_device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; - struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; + struct class_device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; - struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; + struct class_device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ @@ -64,12 +64,12 @@ static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) -#define dev_to_iscsi_internal(_dev) \ - container_of(_dev, struct iscsi_internal, dev) +#define cdev_to_iscsi_internal(_cdev) \ + container_of(_cdev, struct iscsi_internal, cdev) -static void iscsi_transport_release(struct device *dev) +static void iscsi_transport_release(struct class_device *cdev) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); kfree(priv); } @@ -79,33 +79,31 @@ static void iscsi_transport_release(struct device *dev) */ static struct class iscsi_transport_class = { .name = "iscsi_transport", - .dev_release = iscsi_transport_release, + .release = iscsi_transport_release, }; static ssize_t -show_transport_handle(struct device *dev, struct device_attribute *attr, - char *buf) +show_transport_handle(struct class_device *cdev, char *buf) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } -static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); +static CLASS_DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ -show_transport_##name(struct device *dev, \ - struct device_attribute *attr,char *buf) \ +show_transport_##name(struct class_device *cdev, char *buf) \ { \ - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ -static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); +static CLASS_DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { - &dev_attr_handle.attr, - &dev_attr_caps.attr, + &class_device_attr_handle.attr, + &class_device_attr_caps.attr, NULL, }; @@ -113,6 +111,7 @@ static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; +#if 0 /* * iSCSI endpoint attrs */ @@ -229,9 +228,10 @@ struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) return iscsi_dev_to_endpoint(dev); } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); +#endif static int iscsi_setup_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -250,7 +250,7 @@ static int iscsi_setup_host(struct transport_container *tc, struct device *dev, } static int iscsi_remove_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -490,10 +490,9 @@ static int iscsi_user_scan(struct Scsi_Host *shost, uint channel, iscsi_user_scan_session); } -static void iscsi_scan_session(struct work_struct *work) +static void iscsi_scan_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, scan_work); + struct iscsi_cls_session *session = data; struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; struct iscsi_scan_data scan_data; @@ -506,11 +505,9 @@ static void iscsi_scan_session(struct work_struct *work) atomic_dec(&ihost->nr_scans); } -static void session_recovery_timedout(struct work_struct *work) +static void session_recovery_timedout(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - recovery_work.work); + struct iscsi_cls_session *session = data; unsigned long flags; iscsi_cls_session_printk(KERN_INFO, session, @@ -536,13 +533,13 @@ static void session_recovery_timedout(struct work_struct *work) scsi_target_unblock(&session->dev); } -static void __iscsi_unblock_session(struct work_struct *work) +static void __iscsi_unblock_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - unblock_work); + struct iscsi_cls_session *session = data; +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; +#endif unsigned long flags; /* @@ -560,10 +557,12 @@ static void __iscsi_unblock_session(struct work_struct *work) * the async scanning code (drivers like iscsi_tcp do login and * scanning from userspace). */ +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19) if (shost->hostt->scan_finished) { if (queue_work(ihost->scan_workq, &session->scan_work)) atomic_inc(&ihost->nr_scans); } +#endif } /** @@ -583,11 +582,9 @@ void iscsi_unblock_session(struct iscsi_cls_session *session) } EXPORT_SYMBOL_GPL(iscsi_unblock_session); -static void __iscsi_block_session(struct work_struct *work) +static void __iscsi_block_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - block_work); + struct iscsi_cls_session *session = data; unsigned long flags; spin_lock_irqsave(&session->lock, flags); @@ -604,11 +601,9 @@ void iscsi_block_session(struct iscsi_cls_session *session) } EXPORT_SYMBOL_GPL(iscsi_block_session); -static void __iscsi_unbind_session(struct work_struct *work) +static void __iscsi_unbind_session(void *data) { - struct iscsi_cls_session *session = - container_of(work, struct iscsi_cls_session, - unbind_work); + struct iscsi_cls_session *session = data; struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; @@ -651,12 +646,12 @@ iscsi_alloc_session(struct Scsi_Host *shost, struct iscsi_transport *transport, session->transport = transport; session->recovery_tmo = 120; session->state = ISCSI_SESSION_FREE; - INIT_DELAYED_WORK(&session->recovery_work, session_recovery_timedout); + INIT_WORK(&session->recovery_work, session_recovery_timedout, session); INIT_LIST_HEAD(&session->sess_list); - INIT_WORK(&session->unblock_work, __iscsi_unblock_session); - INIT_WORK(&session->block_work, __iscsi_block_session); - INIT_WORK(&session->unbind_work, __iscsi_unbind_session); - INIT_WORK(&session->scan_work, iscsi_scan_session); + INIT_WORK(&session->unblock_work, __iscsi_unblock_session, session); + INIT_WORK(&session->block_work, __iscsi_block_session, session); + INIT_WORK(&session->unbind_work, __iscsi_unbind_session, session); + INIT_WORK(&session->scan_work, iscsi_scan_session, session); spin_lock_init(&session->lock); /* this is released in the dev's release function */ @@ -1300,6 +1295,8 @@ static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { + return -ENOSYS; +#if 0 struct iscsi_endpoint *ep; struct sockaddr *dst_addr; int rc = 0; @@ -1340,6 +1337,8 @@ iscsi_if_transport_ep(struct iscsi_transport *transport, break; } return rc; + +#endif } static int @@ -1421,6 +1420,9 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: + err = -ENOSYS; + break; +#if 0 ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; @@ -1432,6 +1434,7 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; +#endif case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) @@ -1514,55 +1517,70 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) } /* - * Get message from skb. Each message is processed by iscsi_if_recv_msg. - * Malformed skbs with wrong lengths or invalid creds are not processed. + * Get message from skb (based on rtnetlink_rcv_skb). Each message is + * processed by iscsi_if_recv_msg. Malformed skbs with wrong lengths or + * invalid creds are discarded silently. */ static void -iscsi_if_rx(struct sk_buff *skb) +iscsi_if_rx(struct sock *sk, int len) { + struct sk_buff *skb; + mutex_lock(&rx_queue_mutex); - while (skb->len >= NLMSG_SPACE(0)) { - int err; - uint32_t rlen; - struct nlmsghdr *nlh; - struct iscsi_uevent *ev; - - nlh = nlmsg_hdr(skb); - if (nlh->nlmsg_len < sizeof(*nlh) || - skb->len < nlh->nlmsg_len) { - break; + while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { + if (NETLINK_CREDS(skb)->uid) { + skb_pull(skb, skb->len); + goto free_skb; } - ev = NLMSG_DATA(nlh); - rlen = NLMSG_ALIGN(nlh->nlmsg_len); - if (rlen > skb->len) - rlen = skb->len; + while (skb->len >= NLMSG_SPACE(0)) { + int err; + uint32_t rlen; + struct nlmsghdr *nlh; + struct iscsi_uevent *ev; - err = iscsi_if_recv_msg(skb, nlh); - if (err) { - ev->type = ISCSI_KEVENT_IF_ERROR; - ev->iferror = err; - } - do { - /* - * special case for GET_STATS: - * on success - sending reply and stats from - * inside of if_recv_msg(), - * on error - fall through. - */ - if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + nlh = nlmsg_hdr(skb); + if (nlh->nlmsg_len < sizeof(*nlh) || + skb->len < nlh->nlmsg_len) { break; - err = iscsi_if_send_reply( - NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, - nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); - } while (err < 0 && err != -ECONNREFUSED); - skb_pull(skb, rlen); + } + + ev = NLMSG_DATA(nlh); + rlen = NLMSG_ALIGN(nlh->nlmsg_len); + if (rlen > skb->len) + rlen = skb->len; + + err = iscsi_if_recv_msg(skb, nlh); + if (err) { + ev->type = ISCSI_KEVENT_IF_ERROR; + ev->iferror = err; + } + do { + /* + * special case for GET_STATS: + * on success - sending reply and stats from + * inside of if_recv_msg(), + * on error - fall through. + */ + if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + break; + err = iscsi_if_send_reply( + NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, + nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); + } while (err < 0 && err != -ECONNREFUSED); + skb_pull(skb, rlen); + } +free_skb: + kfree_skb(skb); } mutex_unlock(&rx_queue_mutex); } +#define iscsi_cdev_to_conn(_cdev) \ + iscsi_dev_to_conn(_cdev->dev) + #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ -struct device_attribute dev_attr_##_prefix##_##_name = \ +struct class_device_attribute class_device_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* @@ -1570,10 +1588,9 @@ struct device_attribute dev_attr_##_prefix##_##_name = \ */ #define iscsi_conn_attr_show(param) \ static ssize_t \ -show_conn_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_conn_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ + struct iscsi_cls_conn *conn = iscsi_cdev_to_conn(cdev); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } @@ -1597,16 +1614,17 @@ iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); +#define iscsi_cdev_to_session(_cdev) \ + iscsi_dev_to_session(_cdev->dev) + /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ -show_session_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_session_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ @@ -1640,10 +1658,9 @@ iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t -show_priv_session_state(struct device *dev, struct device_attribute *attr, - char *buf) +show_priv_session_state(struct class_device *cdev, char *buf) { - struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, @@ -1651,11 +1668,9 @@ static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ -show_priv_session_##field(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_priv_session_##field(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev);\ return sprintf(buf, format"\n", session->field); \ } @@ -1670,10 +1685,9 @@ iscsi_priv_session_attr(recovery_tmo, "%d"); */ #define iscsi_host_attr_show(param) \ static ssize_t \ -show_host_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_host_param_##param(struct class_device *cdev, char *buf) \ { \ - struct Scsi_Host *shost = transport_class_to_shost(dev); \ + struct Scsi_Host *shost = transport_class_to_shost(cdev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } @@ -1690,7 +1704,7 @@ iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ - priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_priv_sess_##field; \ count++; \ } while (0) @@ -1698,7 +1712,7 @@ do { \ #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->session_attrs[count] = &dev_attr_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_sess_##field; \ count++; \ } \ } while (0) @@ -1706,7 +1720,7 @@ do { \ #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->conn_attrs[count] = &dev_attr_conn_##field; \ + priv->conn_attrs[count] = &class_device_attr_conn_##field; \ count++; \ } \ } while (0) @@ -1714,7 +1728,7 @@ do { \ #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ - priv->host_attrs[count] = &dev_attr_host_##field; \ + priv->host_attrs[count] = &class_device_attr_host_##field; \ count++; \ } \ } while (0) @@ -1807,15 +1821,15 @@ iscsi_register_transport(struct iscsi_transport *tt) if (!(tt->caps & CAP_DATA_PATH_OFFLOAD)) priv->t.create_work_queue = 1; - priv->dev.class = &iscsi_transport_class; - snprintf(priv->dev.bus_id, BUS_ID_SIZE, "%s", tt->name); - err = device_register(&priv->dev); + priv->cdev.class = &iscsi_transport_class; + snprintf(priv->cdev.class_id, BUS_ID_SIZE, "%s", tt->name); + err = class_device_register(&priv->cdev); if (err) goto free_priv; - err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); + err = sysfs_create_group(&priv->cdev.kobj, &iscsi_transport_group); if (err) - goto unregister_dev; + goto unregister_cdev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; @@ -1894,9 +1908,8 @@ iscsi_register_transport(struct iscsi_transport *tt) printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; -unregister_dev: - device_unregister(&priv->dev); - return NULL; +unregister_cdev: + class_device_unregister(&priv->cdev); free_priv: kfree(priv); return NULL; @@ -1923,8 +1936,8 @@ int iscsi_unregister_transport(struct iscsi_transport *tt) transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); - sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); - device_unregister(&priv->dev); + sysfs_remove_group(&priv->cdev.kobj, &iscsi_transport_group); + class_device_unregister(&priv->cdev); mutex_unlock(&rx_queue_mutex); return 0; @@ -1944,13 +1957,14 @@ static __init int iscsi_transport_init(void) if (err) return err; +#if 0 err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; - +#endif err = transport_class_register(&iscsi_host_class); if (err) - goto unregister_endpoint_class; + goto unregister_transport_class; err = transport_class_register(&iscsi_connection_class); if (err) @@ -1981,8 +1995,10 @@ unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); +#if 0 unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); +#endif unregister_transport_class: class_unregister(&iscsi_transport_class); return err; @@ -1995,7 +2011,9 @@ static void __exit iscsi_transport_exit(void) transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); +#if 0 class_unregister(&iscsi_endpoint_class); +#endif class_unregister(&iscsi_transport_class); } diff --git a/scsi_transport_iscsi.h b/scsi_transport_iscsi.h index b7652e3..3978551 100644 --- a/scsi_transport_iscsi.h +++ b/scsi_transport_iscsi.h @@ -28,6 +28,8 @@ #include #include "iscsi_if.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct iscsi_transport; struct iscsi_endpoint; @@ -175,7 +177,7 @@ struct iscsi_cls_session { /* recovery fields */ int recovery_tmo; - struct delayed_work recovery_work; + struct work_struct recovery_work; unsigned int target_id; open-iscsi-2.0.873/kernel/2.6.20-21_compat.patch000066400000000000000000000742131175631155400205740ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 6214055..8563545 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -444,11 +444,9 @@ static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task, if (!task->sc) iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count); else { - struct scsi_data_buffer *sdb = scsi_out(task->sc); - - err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, offset, - count); + err = iscsi_sw_tcp_send_data_prep(conn, scsi_sglist(task->sc), + scsi_sg_count(task->sc), + offset, count); } if (err) { @@ -773,7 +771,11 @@ iscsi_sw_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, shost->max_lun = iscsi_max_lun; shost->max_id = 0; shost->max_channel = 0; +#ifndef SCSI_MAX_VARLEN_CDB_SIZE + shost->max_cmd_len = 16; +#else shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE; +#endif if (iscsi_host_add(shost, NULL)) goto free_host; @@ -821,6 +823,9 @@ static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev) } static struct scsi_host_template iscsi_sw_tcp_sht = { +#if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,24) + .use_sg_chaining = ENABLE_SG_CHAINING, +#endif .module = THIS_MODULE, .name = "iSCSI Initiator over TCP/IP", .queuecommand = iscsi_queuecommand, @@ -831,7 +836,7 @@ static struct scsi_host_template iscsi_sw_tcp_sht = { .cmd_per_lun = ISCSI_DEF_CMD_PER_LUN, .eh_abort_handler = iscsi_eh_abort, .eh_device_reset_handler= iscsi_eh_device_reset, - .eh_target_reset_handler= iscsi_eh_target_reset, + .eh_host_reset_handler = iscsi_eh_target_reset, .use_clustering = DISABLE_CLUSTERING, .slave_configure = iscsi_sw_tcp_slave_configure, .proc_name = "iscsi_tcp", diff --git a/iscsi_tcp.h b/iscsi_tcp.h index f9a4044..ab20530 100644 --- a/iscsi_tcp.h +++ b/iscsi_tcp.h @@ -22,6 +22,8 @@ #ifndef ISCSI_SW_TCP_H #define ISCSI_SW_TCP_H +#include "open_iscsi_compat.h" + #include "libiscsi.h" #include "libiscsi_tcp.h" diff --git a/libiscsi.c b//libiscsi.c index 5ac73fb..0b22b75 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -38,6 +38,8 @@ #include "scsi_transport_iscsi.h" #include "libiscsi.h" +#include "open_iscsi_compat.h" + /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */ #define SNA32_CHECK 2147483648UL @@ -199,7 +201,7 @@ static int iscsi_prep_bidi_ahs(struct iscsi_task *task) sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; - rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); + rlen_ahdr->read_length = cpu_to_be32(scsi_bufflen(sc)); debug_scsi("bidi-in rlen_ahdr->read_length(%d) " "rlen_ahdr->ahslength(%d)\n", @@ -267,7 +269,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { - unsigned out_len = scsi_out(sc)->length; + unsigned out_len = scsi_bufflen(sc); struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->data_length = cpu_to_be32(out_len); @@ -313,7 +315,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); - hdr->data_length = cpu_to_be32(scsi_in(sc)->length); + hdr->data_length = cpu_to_be32(scsi_bufflen(sc)); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; @@ -340,7 +342,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), - scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, + scsi_bidi_cmnd(sc) ? scsi_bufflen(sc) : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; } @@ -432,12 +434,7 @@ static void fail_command(struct iscsi_conn *conn, struct iscsi_task *task, conn->session->queued_cmdsn--; sc->result = err; - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); if (conn->task == task) conn->task = NULL; @@ -631,7 +628,7 @@ invalid_datalen: goto out; } - senselen = get_unaligned_be16(data); + senselen = be16_to_cpu(get_unaligned((__be16 *) data)); if (datalen < senselen) goto invalid_datalen; @@ -647,8 +644,8 @@ invalid_datalen: if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -697,8 +694,8 @@ iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -1408,12 +1405,7 @@ prepd_fault: fault: spin_unlock(&session->lock); debug_scsi("iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); done(sc); spin_lock(host->host_lock); return 0; diff --git a/libiscsi.h b/libiscsi.h index a261e2c..96fd795 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -32,6 +32,8 @@ #include "iscsi_if.h" #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct scsi_host_template; struct scsi_device; diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 92cb13d..ea7dd8d 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -357,6 +357,17 @@ iscsi_segment_seek_sg(struct iscsi_segment *segment, debug_scsi("iscsi_segment_seek_sg offset %u size %llu\n", offset, size); + + /* + * older kernels could send use_sg=0 for commands like sgio + * or scsi-ml commands. + */ + if (!sg_count) { + iscsi_segment_init_linear(segment, (void *)sg_list + offset, + size, done, hash); + return 0; + } + __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { debug_scsi("sg %d, len %u offset %u\n", i, sg->length, @@ -469,7 +480,7 @@ static int iscsi_tcp_data_in(struct iscsi_conn *conn, struct iscsi_task *task) struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr; int datasn = be32_to_cpu(rhdr->datasn); - unsigned total_in_length = scsi_in(task->sc)->length; + unsigned total_in_length = scsi_bufflen(task->sc); iscsi_update_cmdsn(conn->session, (struct iscsi_nopin*)rhdr); if (tcp_conn->in.datalen == 0) @@ -557,11 +568,11 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); - if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { + if (r2t->data_offset + r2t->data_length > scsi_bufflen(task->sc)) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, - r2t->data_offset, scsi_out(task->sc)->length); + r2t->data_offset, scsi_bufflen(task->sc)); __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; @@ -660,7 +671,6 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; - struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd @@ -679,8 +689,8 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) tcp_task->data_offset, tcp_conn->in.datalen); rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, - sdb->table.sgl, - sdb->table.nents, + scsi_sglist(task->sc), + scsi_sg_count(task->sc), tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index 3bacef5..5ea284d 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -21,6 +21,7 @@ #ifndef LIBISCSI_TCP_H #define LIBISCSI_TCP_H +#include "open_iscsi_compat.h" #include "libiscsi.h" struct iscsi_tcp_conn; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..fd9ef7b --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,266 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index 4781d81..023daf5 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -41,13 +41,13 @@ struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; - struct device dev; + struct class_device cdev; - struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; + struct class_device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; - struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; + struct class_device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; - struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; + struct class_device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ @@ -64,12 +64,12 @@ static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) -#define dev_to_iscsi_internal(_dev) \ - container_of(_dev, struct iscsi_internal, dev) +#define cdev_to_iscsi_internal(_cdev) \ + container_of(_cdev, struct iscsi_internal, cdev) -static void iscsi_transport_release(struct device *dev) +static void iscsi_transport_release(struct class_device *cdev) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); kfree(priv); } @@ -79,33 +79,31 @@ static void iscsi_transport_release(struct device *dev) */ static struct class iscsi_transport_class = { .name = "iscsi_transport", - .dev_release = iscsi_transport_release, + .release = iscsi_transport_release, }; static ssize_t -show_transport_handle(struct device *dev, struct device_attribute *attr, - char *buf) +show_transport_handle(struct class_device *cdev, char *buf) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } -static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); +static CLASS_DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ -show_transport_##name(struct device *dev, \ - struct device_attribute *attr,char *buf) \ +show_transport_##name(struct class_device *cdev, char *buf) \ { \ - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ -static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); +static CLASS_DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { - &dev_attr_handle.attr, - &dev_attr_caps.attr, + &class_device_attr_handle.attr, + &class_device_attr_caps.attr, NULL, }; @@ -113,6 +111,7 @@ static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; +#if 0 /* * iSCSI endpoint attrs */ @@ -236,9 +235,10 @@ struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); +#endif static int iscsi_setup_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -257,7 +257,7 @@ static int iscsi_setup_host(struct transport_container *tc, struct device *dev, } static int iscsi_remove_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -723,7 +723,8 @@ int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id) } session->target_id = id; - dev_set_name(&session->dev, "session%u", session->sid); + snprintf(session->dev.bus_id, BUS_ID_SIZE, "session%u", + session->sid); err = device_add(&session->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, @@ -896,7 +897,8 @@ iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid) if (!get_device(&session->dev)) goto free_conn; - dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid); + snprintf(conn->dev.bus_id, BUS_ID_SIZE, "connection%d:%u", + session->sid, cid); conn->dev.parent = &session->dev; conn->dev.release = iscsi_conn_release; err = device_register(&conn->dev); @@ -1305,6 +1307,8 @@ static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { + return -ENOSYS; +#if 0 struct iscsi_endpoint *ep; struct sockaddr *dst_addr; int rc = 0; @@ -1345,6 +1349,8 @@ iscsi_if_transport_ep(struct iscsi_transport *transport, break; } return rc; + +#endif } static int @@ -1426,6 +1432,9 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: + err = -ENOSYS; + break; +#if 0 ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; @@ -1437,6 +1446,7 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; +#endif case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) @@ -1519,55 +1529,70 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) } /* - * Get message from skb. Each message is processed by iscsi_if_recv_msg. - * Malformed skbs with wrong lengths or invalid creds are not processed. + * Get message from skb (based on rtnetlink_rcv_skb). Each message is + * processed by iscsi_if_recv_msg. Malformed skbs with wrong lengths or + * invalid creds are discarded silently. */ static void -iscsi_if_rx(struct sk_buff *skb) +iscsi_if_rx(struct sock *sk, int len) { + struct sk_buff *skb; + mutex_lock(&rx_queue_mutex); - while (skb->len >= NLMSG_SPACE(0)) { - int err; - uint32_t rlen; - struct nlmsghdr *nlh; - struct iscsi_uevent *ev; - - nlh = nlmsg_hdr(skb); - if (nlh->nlmsg_len < sizeof(*nlh) || - skb->len < nlh->nlmsg_len) { - break; + while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { + if (NETLINK_CREDS(skb)->uid) { + skb_pull(skb, skb->len); + goto free_skb; } - ev = NLMSG_DATA(nlh); - rlen = NLMSG_ALIGN(nlh->nlmsg_len); - if (rlen > skb->len) - rlen = skb->len; + while (skb->len >= NLMSG_SPACE(0)) { + int err; + uint32_t rlen; + struct nlmsghdr *nlh; + struct iscsi_uevent *ev; - err = iscsi_if_recv_msg(skb, nlh); - if (err) { - ev->type = ISCSI_KEVENT_IF_ERROR; - ev->iferror = err; - } - do { - /* - * special case for GET_STATS: - * on success - sending reply and stats from - * inside of if_recv_msg(), - * on error - fall through. - */ - if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + nlh = nlmsg_hdr(skb); + if (nlh->nlmsg_len < sizeof(*nlh) || + skb->len < nlh->nlmsg_len) { break; - err = iscsi_if_send_reply( - NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, - nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); - } while (err < 0 && err != -ECONNREFUSED); - skb_pull(skb, rlen); + } + + ev = NLMSG_DATA(nlh); + rlen = NLMSG_ALIGN(nlh->nlmsg_len); + if (rlen > skb->len) + rlen = skb->len; + + err = iscsi_if_recv_msg(skb, nlh); + if (err) { + ev->type = ISCSI_KEVENT_IF_ERROR; + ev->iferror = err; + } + do { + /* + * special case for GET_STATS: + * on success - sending reply and stats from + * inside of if_recv_msg(), + * on error - fall through. + */ + if (ev->type == ISCSI_UEVENT_GET_STATS && !err) + break; + err = iscsi_if_send_reply( + NETLINK_CREDS(skb)->pid, nlh->nlmsg_seq, + nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); + } while (err < 0 && err != -ECONNREFUSED); + skb_pull(skb, rlen); + } +free_skb: + kfree_skb(skb); } mutex_unlock(&rx_queue_mutex); } +#define iscsi_cdev_to_conn(_cdev) \ + iscsi_dev_to_conn(_cdev->dev) + #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ -struct device_attribute dev_attr_##_prefix##_##_name = \ +struct class_device_attribute class_device_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* @@ -1575,10 +1600,9 @@ struct device_attribute dev_attr_##_prefix##_##_name = \ */ #define iscsi_conn_attr_show(param) \ static ssize_t \ -show_conn_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_conn_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ + struct iscsi_cls_conn *conn = iscsi_cdev_to_conn(cdev); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } @@ -1602,16 +1626,17 @@ iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); +#define iscsi_cdev_to_session(_cdev) \ + iscsi_dev_to_session(_cdev->dev) + /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ -show_session_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_session_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ @@ -1645,10 +1670,9 @@ iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t -show_priv_session_state(struct device *dev, struct device_attribute *attr, - char *buf) +show_priv_session_state(struct class_device *cdev, char *buf) { - struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, @@ -1656,11 +1680,9 @@ static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ -show_priv_session_##field(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_priv_session_##field(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev);\ return sprintf(buf, format"\n", session->field); \ } @@ -1675,10 +1697,9 @@ iscsi_priv_session_attr(recovery_tmo, "%d"); */ #define iscsi_host_attr_show(param) \ static ssize_t \ -show_host_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_host_param_##param(struct class_device *cdev, char *buf) \ { \ - struct Scsi_Host *shost = transport_class_to_shost(dev); \ + struct Scsi_Host *shost = transport_class_to_shost(cdev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } @@ -1695,7 +1716,7 @@ iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ - priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_priv_sess_##field; \ count++; \ } while (0) @@ -1703,7 +1724,7 @@ do { \ #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->session_attrs[count] = &dev_attr_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_sess_##field; \ count++; \ } \ } while (0) @@ -1711,7 +1732,7 @@ do { \ #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->conn_attrs[count] = &dev_attr_conn_##field; \ + priv->conn_attrs[count] = &class_device_attr_conn_##field; \ count++; \ } \ } while (0) @@ -1719,7 +1740,7 @@ do { \ #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ - priv->host_attrs[count] = &dev_attr_host_##field; \ + priv->host_attrs[count] = &class_device_attr_host_##field; \ count++; \ } \ } while (0) @@ -1812,15 +1833,15 @@ iscsi_register_transport(struct iscsi_transport *tt) if (!(tt->caps & CAP_DATA_PATH_OFFLOAD)) priv->t.create_work_queue = 1; - priv->dev.class = &iscsi_transport_class; - dev_set_name(&priv->dev, "%s", tt->name); - err = device_register(&priv->dev); + priv->cdev.class = &iscsi_transport_class; + snprintf(priv->cdev.class_id, BUS_ID_SIZE, "%s", tt->name); + err = class_device_register(&priv->cdev); if (err) goto free_priv; - err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); + err = sysfs_create_group(&priv->cdev.kobj, &iscsi_transport_group); if (err) - goto unregister_dev; + goto unregister_cdev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; @@ -1899,9 +1920,8 @@ iscsi_register_transport(struct iscsi_transport *tt) printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; -unregister_dev: - device_unregister(&priv->dev); - return NULL; +unregister_cdev: + class_device_unregister(&priv->cdev); free_priv: kfree(priv); return NULL; @@ -1928,8 +1948,8 @@ int iscsi_unregister_transport(struct iscsi_transport *tt) transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); - sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); - device_unregister(&priv->dev); + sysfs_remove_group(&priv->cdev.kobj, &iscsi_transport_group); + class_device_unregister(&priv->cdev); mutex_unlock(&rx_queue_mutex); return 0; @@ -1949,13 +1969,14 @@ static __init int iscsi_transport_init(void) if (err) return err; +#if 0 err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; - +#endif err = transport_class_register(&iscsi_host_class); if (err) - goto unregister_endpoint_class; + goto unregister_transport_class; err = transport_class_register(&iscsi_connection_class); if (err) @@ -1986,8 +2007,10 @@ unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); +#if 0 unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); +#endif unregister_transport_class: class_unregister(&iscsi_transport_class); return err; @@ -2000,7 +2023,9 @@ static void __exit iscsi_transport_exit(void) transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); +#if 0 class_unregister(&iscsi_endpoint_class); +#endif class_unregister(&iscsi_transport_class); } diff --git a/scsi_transport_iscsi.h b/scsi_transport_iscsi.h index 27d067a..41a54c8 100644 --- a/scsi_transport_iscsi.h +++ b//scsi_transport_iscsi.h @@ -28,6 +28,8 @@ #include #include "iscsi_if.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct iscsi_transport; struct iscsi_endpoint; -- 1.6.0.4 open-iscsi-2.0.873/kernel/2.6.24_compat.patch000066400000000000000000001076031175631155400203600ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..bb027e4 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " @@ -480,11 +481,9 @@ static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task, if (!task->sc) iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count); else { - struct scsi_data_buffer *sdb = scsi_out(task->sc); - - err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl, - sdb->table.nents, offset, - count); + err = iscsi_sw_tcp_send_data_prep(conn, scsi_sglist(task->sc), + scsi_sg_count(task->sc), + offset, count); } if (err) { @@ -821,7 +820,11 @@ iscsi_sw_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, shost->max_lun = iscsi_max_lun; shost->max_id = 0; shost->max_channel = 0; +#ifndef SCSI_MAX_VARLEN_CDB_SIZE + shost->max_cmd_len = 16; +#else shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE; +#endif if (iscsi_host_add(shost, NULL)) goto free_host; @@ -874,6 +877,9 @@ static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev) } static struct scsi_host_template iscsi_sw_tcp_sht = { +#if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,24) + .use_sg_chaining = ENABLE_SG_CHAINING, +#endif .module = THIS_MODULE, .name = "iSCSI Initiator over TCP/IP", .queuecommand = iscsi_queuecommand, @@ -884,7 +890,7 @@ static struct scsi_host_template iscsi_sw_tcp_sht = { .cmd_per_lun = ISCSI_DEF_CMD_PER_LUN, .eh_abort_handler = iscsi_eh_abort, .eh_device_reset_handler= iscsi_eh_device_reset, - .eh_target_reset_handler = iscsi_eh_recover_target, + .eh_host_reset_handler = iscsi_eh_recover_target, .use_clustering = DISABLE_CLUSTERING, .slave_alloc = iscsi_sw_tcp_slave_alloc, .slave_configure = iscsi_sw_tcp_slave_configure, diff --git a/iscsi_tcp.h b/iscsi_tcp.h index 2a1cf23..32d7edd 100644 --- a/iscsi_tcp.h +++ b/iscsi_tcp.h @@ -22,6 +22,8 @@ #ifndef ISCSI_SW_TCP_H #define ISCSI_SW_TCP_H +#include "open_iscsi_compat.h" + #include "libiscsi.h" #include "libiscsi_tcp.h" diff --git a/libiscsi.c b/libiscsi.c index 59e3a5f..1c8d00d 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -84,6 +84,8 @@ MODULE_PARM_DESC(debug_libiscsi_eh, __func__, ##arg); \ } while (0); +#include "open_iscsi_compat.h" + /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */ #define SNA32_CHECK 2147483648UL @@ -256,7 +258,7 @@ static int iscsi_prep_bidi_ahs(struct iscsi_task *task) sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; - rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); + rlen_ahdr->read_length = cpu_to_be32(scsi_bufflen(sc)); ISCSI_DBG_SESSION(task->conn->session, "bidi-in rlen_ahdr->read_length(%d) " @@ -411,7 +413,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { - unsigned out_len = scsi_out(sc)->length; + unsigned out_len = scsi_bufflen(sc); struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->data_length = cpu_to_be32(out_len); @@ -457,7 +459,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); - hdr->data_length = cpu_to_be32(scsi_in(sc)->length); + hdr->data_length = cpu_to_be32(scsi_bufflen(sc)); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; @@ -486,7 +488,7 @@ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), - scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, + scsi_bidi_cmnd(sc) ? scsi_bufflen(sc) : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; @@ -518,7 +520,7 @@ static void iscsi_free_task(struct iscsi_task *task) if (conn->login_task == task) return; - kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); + __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; @@ -648,12 +650,7 @@ static void fail_scsi_task(struct iscsi_task *task, int err) state = ISCSI_TASK_ABRT_TMF; sc->result = err << 16; - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); iscsi_complete_task(task, state); } @@ -738,7 +735,7 @@ __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } @@ -853,7 +850,7 @@ invalid_datalen: goto out; } - senselen = get_unaligned_be16(data); + senselen = be16_to_cpu(get_unaligned((__be16 *) data)); if (datalen < senselen) goto invalid_datalen; @@ -870,8 +867,8 @@ invalid_datalen: if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -920,8 +917,8 @@ iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || - res_count <= scsi_in(sc)->length)) - scsi_in(sc)->resid = res_count; + res_count <= scsi_bufflen(sc))) + scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } @@ -1568,7 +1565,7 @@ static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, { struct iscsi_task *task; - if (!kfifo_out(&conn->session->cmdpool.queue, + if (!__kfifo_get(conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; @@ -1726,33 +1723,16 @@ fault: spin_unlock(&session->lock); ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); - if (!scsi_bidi_cmnd(sc)) - scsi_set_resid(sc, scsi_bufflen(sc)); - else { - scsi_out(sc)->resid = scsi_out(sc)->length; - scsi_in(sc)->resid = scsi_in(sc)->length; - } + scsi_set_resid(sc, scsi_bufflen(sc)); done(sc); spin_lock(host->host_lock); return 0; } EXPORT_SYMBOL_GPL(iscsi_queuecommand); -int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) +int iscsi_change_queue_depth(struct scsi_device *sdev, int depth) { - switch (reason) { - case SCSI_QDEPTH_DEFAULT: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - case SCSI_QDEPTH_QFULL: - scsi_track_queue_full(sdev, depth); - break; - case SCSI_QDEPTH_RAMP_UP: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - default: - return -EOPNOTSUPP; - } + scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); @@ -2524,7 +2504,12 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) if (q->pool == NULL) return -ENOMEM; - kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); + q->queue = kfifo_init((void*)q->pool, max * sizeof(void*), + GFP_KERNEL, NULL); + if (IS_ERR(q->queue)) { + q->queue = NULL; + goto enomem; + } for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); @@ -2532,7 +2517,7 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) q->max = i; goto enomem; } - kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); + __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { @@ -2555,6 +2540,7 @@ void iscsi_pool_free(struct iscsi_pool *q) for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); + kfree(q->queue); } EXPORT_SYMBOL_GPL(iscsi_pool_free); @@ -2882,7 +2868,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); @@ -2902,7 +2888,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, return cls_conn; login_task_data_alloc_fail: - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); @@ -2965,7 +2951,7 @@ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; diff --git a/libiscsi.h b/libiscsi.h index 0563539..d74385c 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -32,6 +32,8 @@ #include "iscsi_if.h" #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct scsi_host_template; struct scsi_device; @@ -231,7 +233,7 @@ struct iscsi_conn { }; struct iscsi_pool { - struct kfifo queue; /* FIFO Queue */ + struct kfifo *queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; @@ -334,8 +336,7 @@ struct iscsi_host { /* * scsi host template */ -extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, - int reason); +extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 1122de4..a0307e1 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -361,6 +361,16 @@ iscsi_segment_seek_sg(struct iscsi_segment *segment, struct scatterlist *sg; unsigned int i; + /* + * older kernels could send use_sg=0 for commands like sgio + * or scsi-ml commands. + */ + if (!sg_count) { + iscsi_segment_init_linear(segment, (void *)sg_list + offset, + size, done, hash); + return 0; + } + __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { if (offset < sg->length) { @@ -446,15 +456,15 @@ void iscsi_tcp_cleanup_task(struct iscsi_task *task) return; /* flush task's r2t queues */ - while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + while (__kfifo_get(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } @@ -472,7 +482,7 @@ static int iscsi_tcp_data_in(struct iscsi_conn *conn, struct iscsi_task *task) struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr; int datasn = be32_to_cpu(rhdr->datasn); - unsigned total_in_length = scsi_in(task->sc)->length; + unsigned total_in_length = scsi_bufflen(task->sc); /* * lib iscsi will update this in the completion handling if there @@ -542,7 +552,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) return 0; } - rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); + rc = __kfifo_get(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " @@ -555,7 +565,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -566,12 +576,12 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); - if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { + if (r2t->data_offset + r2t->data_length > scsi_bufflen(task->sc)) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, - r2t->data_offset, scsi_out(task->sc)->length); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + r2t->data_offset, scsi_bufflen(task->sc)); + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -581,7 +591,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; - kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); + __kfifo_put(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); @@ -669,7 +679,6 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; - struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd @@ -689,8 +698,8 @@ iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) tcp_conn->in.datalen); task->last_xfer = jiffies; rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, - sdb->table.sgl, - sdb->table.nents, + scsi_sglist(task->sc), + scsi_sg_count(task->sc), tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, @@ -952,7 +961,7 @@ int iscsi_tcp_task_init(struct iscsi_task *task) return conn->session->tt->init_pdu(task, 0, task->data_count); } - BUG_ON(kfifo_len(&tcp_task->r2tqueue)); + BUG_ON(__kfifo_len(tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ @@ -983,7 +992,7 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); - kfifo_in(&tcp_task->r2tpool.queue, + __kfifo_put(tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; @@ -991,12 +1000,9 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) } if (r2t == NULL) { - if (kfifo_out(&tcp_task->r2tqueue, - (void *)&tcp_task->r2t, sizeof(void *)) != - sizeof(void *)) - r2t = NULL; - else - r2t = tcp_task->r2t; + __kfifo_get(tcp_task->r2tqueue, + (void *)&tcp_task->r2t, sizeof(void *)); + r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } @@ -1131,8 +1137,9 @@ int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) } /* R2T xmit queue */ - if (kfifo_alloc(&tcp_task->r2tqueue, - session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { + tcp_task->r2tqueue = kfifo_alloc( + session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL); + if (tcp_task->r2tqueue == ERR_PTR(-ENOMEM)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } @@ -1145,7 +1152,7 @@ r2t_alloc_fail: struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; @@ -1160,7 +1167,7 @@ void iscsi_tcp_r2tpool_free(struct iscsi_session *session) struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index c020eee..5ea284d 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -21,6 +21,7 @@ #ifndef LIBISCSI_TCP_H #define LIBISCSI_TCP_H +#include "open_iscsi_compat.h" #include "libiscsi.h" struct iscsi_tcp_conn; @@ -80,7 +81,7 @@ struct iscsi_tcp_task { int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; - struct kfifo r2tqueue; + struct kfifo *r2tqueue; void *dd_data; }; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..50ab84d --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,276 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index fed8c9e..01bf46c 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -73,13 +73,13 @@ struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; - struct device dev; + struct class_device cdev; - struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; + struct class_device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; - struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; + struct class_device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; - struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; + struct class_device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ @@ -96,12 +96,12 @@ static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) -#define dev_to_iscsi_internal(_dev) \ - container_of(_dev, struct iscsi_internal, dev) +#define cdev_to_iscsi_internal(_cdev) \ + container_of(_cdev, struct iscsi_internal, cdev) -static void iscsi_transport_release(struct device *dev) +static void iscsi_transport_release(struct class_device *cdev) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); kfree(priv); } @@ -111,33 +111,31 @@ static void iscsi_transport_release(struct device *dev) */ static struct class iscsi_transport_class = { .name = "iscsi_transport", - .dev_release = iscsi_transport_release, + .release = iscsi_transport_release, }; static ssize_t -show_transport_handle(struct device *dev, struct device_attribute *attr, - char *buf) +show_transport_handle(struct class_device *cdev, char *buf) { - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } -static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); +static CLASS_DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ -show_transport_##name(struct device *dev, \ - struct device_attribute *attr,char *buf) \ +show_transport_##name(struct class_device *cdev, char *buf) \ { \ - struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ + struct iscsi_internal *priv = cdev_to_iscsi_internal(cdev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ -static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); +static CLASS_DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { - &dev_attr_handle.attr, - &dev_attr_caps.attr, + &class_device_attr_handle.attr, + &class_device_attr_caps.attr, NULL, }; @@ -145,6 +143,7 @@ static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; +#if 0 /* * iSCSI endpoint attrs */ @@ -268,9 +267,10 @@ struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); +#endif static int iscsi_setup_host(struct transport_container *tc, struct device *dev, - struct device *cdev) + struct class_device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; @@ -750,7 +750,8 @@ int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id) } session->target_id = id; - dev_set_name(&session->dev, "session%u", session->sid); + snprintf(session->dev.bus_id, BUS_ID_SIZE, "session%u", + session->sid); err = device_add(&session->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, @@ -930,7 +931,8 @@ iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid) if (!get_device(&session->dev)) goto free_conn; - dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid); + snprintf(conn->dev.bus_id, BUS_ID_SIZE, "connection%d:%u", + session->sid, cid); conn->dev.parent = &session->dev; conn->dev.release = iscsi_conn_release; err = device_register(&conn->dev); @@ -1402,6 +1404,8 @@ static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { + return -ENOSYS; +#if 0 struct iscsi_endpoint *ep; int rc = 0; @@ -1433,6 +1437,8 @@ iscsi_if_transport_ep(struct iscsi_transport *transport, break; } return rc; + +#endif } static int @@ -1541,6 +1547,9 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: + err = -ENOSYS; + break; +#if 0 ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; @@ -1552,6 +1561,7 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; +#endif case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) @@ -1686,8 +1696,11 @@ iscsi_if_rx(struct sk_buff *skb) mutex_unlock(&rx_queue_mutex); } +#define iscsi_cdev_to_conn(_cdev) \ + iscsi_dev_to_conn(_cdev->dev) + #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ -struct device_attribute dev_attr_##_prefix##_##_name = \ +struct class_device_attribute class_device_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* @@ -1695,10 +1708,9 @@ struct device_attribute dev_attr_##_prefix##_##_name = \ */ #define iscsi_conn_attr_show(param) \ static ssize_t \ -show_conn_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_conn_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ + struct iscsi_cls_conn *conn = iscsi_cdev_to_conn(cdev); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } @@ -1722,16 +1734,17 @@ iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); +#define iscsi_cdev_to_session(_cdev) \ + iscsi_dev_to_session(_cdev->dev) + /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ -show_session_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_session_param_##param(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ @@ -1766,10 +1779,9 @@ iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t -show_priv_session_state(struct device *dev, struct device_attribute *attr, - char *buf) +show_priv_session_state(struct class_device *cdev, char *buf) { - struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, @@ -1777,11 +1789,9 @@ static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ -show_priv_session_##field(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_priv_session_##field(struct class_device *cdev, char *buf) \ { \ - struct iscsi_cls_session *session = \ - iscsi_dev_to_session(dev->parent); \ + struct iscsi_cls_session *session = iscsi_cdev_to_session(cdev);\ return sprintf(buf, format"\n", session->field); \ } @@ -1796,10 +1806,9 @@ iscsi_priv_session_attr(recovery_tmo, "%d"); */ #define iscsi_host_attr_show(param) \ static ssize_t \ -show_host_param_##param(struct device *dev, \ - struct device_attribute *attr, char *buf) \ +show_host_param_##param(struct class_device *cdev, char *buf) \ { \ - struct Scsi_Host *shost = transport_class_to_shost(dev); \ + struct Scsi_Host *shost = transport_class_to_shost(cdev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } @@ -1816,7 +1825,7 @@ iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ - priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_priv_sess_##field; \ count++; \ } while (0) @@ -1824,7 +1833,7 @@ do { \ #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->session_attrs[count] = &dev_attr_sess_##field; \ + priv->session_attrs[count] = &class_device_attr_sess_##field; \ count++; \ } \ } while (0) @@ -1832,7 +1841,7 @@ do { \ #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ - priv->conn_attrs[count] = &dev_attr_conn_##field; \ + priv->conn_attrs[count] = &class_device_attr_conn_##field; \ count++; \ } \ } while (0) @@ -1840,7 +1849,7 @@ do { \ #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ - priv->host_attrs[count] = &dev_attr_host_##field; \ + priv->host_attrs[count] = &class_device_attr_host_##field; \ count++; \ } \ } while (0) @@ -1931,15 +1940,15 @@ iscsi_register_transport(struct iscsi_transport *tt) priv->t.user_scan = iscsi_user_scan; priv->t.create_work_queue = 1; - priv->dev.class = &iscsi_transport_class; - dev_set_name(&priv->dev, "%s", tt->name); - err = device_register(&priv->dev); + priv->cdev.class = &iscsi_transport_class; + snprintf(priv->cdev.class_id, BUS_ID_SIZE, "%s", tt->name); + err = class_device_register(&priv->cdev); if (err) goto free_priv; - err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); + err = sysfs_create_group(&priv->cdev.kobj, &iscsi_transport_group); if (err) - goto unregister_dev; + goto unregister_cdev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; @@ -2019,9 +2028,8 @@ iscsi_register_transport(struct iscsi_transport *tt) printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; -unregister_dev: - device_unregister(&priv->dev); - return NULL; +unregister_cdev: + class_device_unregister(&priv->cdev); free_priv: kfree(priv); return NULL; @@ -2048,8 +2056,8 @@ int iscsi_unregister_transport(struct iscsi_transport *tt) transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); - sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); - device_unregister(&priv->dev); + sysfs_remove_group(&priv->cdev.kobj, &iscsi_transport_group); + class_device_unregister(&priv->cdev); mutex_unlock(&rx_queue_mutex); return 0; @@ -2069,13 +2077,14 @@ static __init int iscsi_transport_init(void) if (err) return err; +#if 0 err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; - +#endif err = transport_class_register(&iscsi_host_class); if (err) - goto unregister_endpoint_class; + goto unregister_transport_class; err = transport_class_register(&iscsi_connection_class); if (err) @@ -2106,8 +2115,10 @@ unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); +#if 0 unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); +#endif unregister_transport_class: class_unregister(&iscsi_transport_class); return err; @@ -2120,7 +2131,9 @@ static void __exit iscsi_transport_exit(void) transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); +#if 0 class_unregister(&iscsi_endpoint_class); +#endif class_unregister(&iscsi_transport_class); } diff --git a/scsi_transport_iscsi.h b/scsi_transport_iscsi.h index ef4b697..d62fd13 100644 --- a/scsi_transport_iscsi.h +++ b/scsi_transport_iscsi.h @@ -28,6 +28,8 @@ #include #include "iscsi_if.h" +#include "open_iscsi_compat.h" + struct scsi_transport_template; struct iscsi_transport; struct iscsi_endpoint; -- 1.6.6.1 open-iscsi-2.0.873/kernel/2.6.26_compat.patch000066400000000000000000000447001175631155400203600ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..197d314 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " diff --git a/libiscsi.c b/libiscsi.c index 59e3a5f..d0e41d9 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -39,6 +39,8 @@ #include "scsi_transport_iscsi.h" #include "libiscsi.h" +#include "open_iscsi_compat.h" + static int iscsi_dbg_lib_conn; module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int, S_IRUGO | S_IWUSR); @@ -518,7 +520,7 @@ static void iscsi_free_task(struct iscsi_task *task) if (conn->login_task == task) return; - kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); + __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; @@ -738,7 +740,7 @@ __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } @@ -1568,7 +1570,7 @@ static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, { struct iscsi_task *task; - if (!kfifo_out(&conn->session->cmdpool.queue, + if (!__kfifo_get(conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; @@ -1738,21 +1740,9 @@ fault: } EXPORT_SYMBOL_GPL(iscsi_queuecommand); -int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) +int iscsi_change_queue_depth(struct scsi_device *sdev, int depth) { - switch (reason) { - case SCSI_QDEPTH_DEFAULT: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - case SCSI_QDEPTH_QFULL: - scsi_track_queue_full(sdev, depth); - break; - case SCSI_QDEPTH_RAMP_UP: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - default: - return -EOPNOTSUPP; - } + scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); @@ -2524,7 +2514,12 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) if (q->pool == NULL) return -ENOMEM; - kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); + q->queue = kfifo_init((void*)q->pool, max * sizeof(void*), + GFP_KERNEL, NULL); + if (IS_ERR(q->queue)) { + q->queue = NULL; + goto enomem; + } for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); @@ -2532,7 +2527,7 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) q->max = i; goto enomem; } - kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); + __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { @@ -2555,6 +2550,7 @@ void iscsi_pool_free(struct iscsi_pool *q) for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); + kfree(q->queue); } EXPORT_SYMBOL_GPL(iscsi_pool_free); @@ -2882,7 +2878,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); @@ -2902,7 +2898,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, return cls_conn; login_task_data_alloc_fail: - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); @@ -2965,7 +2961,7 @@ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; diff --git a/libiscsi.h b/libiscsi.h index 0563539..4be9333 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -231,7 +231,7 @@ struct iscsi_conn { }; struct iscsi_pool { - struct kfifo queue; /* FIFO Queue */ + struct kfifo *queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; @@ -334,8 +334,7 @@ struct iscsi_host { /* * scsi host template */ -extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, - int reason); +extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 1122de4..c3ff728 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -446,15 +446,15 @@ void iscsi_tcp_cleanup_task(struct iscsi_task *task) return; /* flush task's r2t queues */ - while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + while (__kfifo_get(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } @@ -542,7 +542,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) return 0; } - rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); + rc = __kfifo_get(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " @@ -555,7 +555,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -571,7 +571,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, r2t->data_offset, scsi_out(task->sc)->length); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -581,7 +581,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; - kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); + __kfifo_put(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); @@ -952,7 +952,7 @@ int iscsi_tcp_task_init(struct iscsi_task *task) return conn->session->tt->init_pdu(task, 0, task->data_count); } - BUG_ON(kfifo_len(&tcp_task->r2tqueue)); + BUG_ON(__kfifo_len(tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ @@ -983,7 +983,7 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); - kfifo_in(&tcp_task->r2tpool.queue, + __kfifo_put(tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; @@ -991,12 +991,9 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) } if (r2t == NULL) { - if (kfifo_out(&tcp_task->r2tqueue, - (void *)&tcp_task->r2t, sizeof(void *)) != - sizeof(void *)) - r2t = NULL; - else - r2t = tcp_task->r2t; + __kfifo_get(tcp_task->r2tqueue, + (void *)&tcp_task->r2t, sizeof(void *)); + r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } @@ -1131,8 +1128,9 @@ int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) } /* R2T xmit queue */ - if (kfifo_alloc(&tcp_task->r2tqueue, - session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { + tcp_task->r2tqueue = kfifo_alloc( + session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL); + if (tcp_task->r2tqueue == ERR_PTR(-ENOMEM)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } @@ -1145,7 +1143,7 @@ r2t_alloc_fail: struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; @@ -1160,7 +1158,7 @@ void iscsi_tcp_r2tpool_free(struct iscsi_session *session) struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index c020eee..3bacef5 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -80,7 +80,7 @@ struct iscsi_tcp_task { int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; - struct kfifo r2tqueue; + struct kfifo *r2tqueue; void *dd_data; }; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..50ab84d --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,276 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index fed8c9e..c187e5d 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -31,6 +31,8 @@ #include "scsi_transport_iscsi.h" #include "iscsi_if.h" +#include "open_iscsi_compat.h" + #define ISCSI_SESSION_ATTRS 22 #define ISCSI_CONN_ATTRS 13 #define ISCSI_HOST_ATTRS 4 @@ -145,6 +147,7 @@ static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; +#if 0 /* * iSCSI endpoint attrs */ @@ -268,6 +271,7 @@ struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); +#endif static int iscsi_setup_host(struct transport_container *tc, struct device *dev, struct device *cdev) @@ -1402,6 +1406,8 @@ static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { + return -ENOSYS; +#if 0 struct iscsi_endpoint *ep; int rc = 0; @@ -1433,6 +1439,8 @@ iscsi_if_transport_ep(struct iscsi_transport *transport, break; } return rc; + +#endif } static int @@ -1541,6 +1549,9 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: + err = -ENOSYS; + break; +#if 0 ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; @@ -1552,6 +1563,7 @@ iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; +#endif case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) @@ -2069,13 +2081,14 @@ static __init int iscsi_transport_init(void) if (err) return err; +#if 0 err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; - +#endif err = transport_class_register(&iscsi_host_class); if (err) - goto unregister_endpoint_class; + goto unregister_transport_class; err = transport_class_register(&iscsi_connection_class); if (err) @@ -2106,8 +2119,10 @@ unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); +#if 0 unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); +#endif unregister_transport_class: class_unregister(&iscsi_transport_class); return err; @@ -2120,7 +2135,9 @@ static void __exit iscsi_transport_exit(void) transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); +#if 0 class_unregister(&iscsi_endpoint_class); +#endif class_unregister(&iscsi_transport_class); } -- 1.6.6.1 open-iscsi-2.0.873/kernel/2.6.27_compat.patch000066400000000000000000000400141175631155400203530ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..197d314 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " diff --git a/libiscsi.c b/libiscsi.c index 59e3a5f..d0e41d9 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -39,6 +39,8 @@ #include "scsi_transport_iscsi.h" #include "libiscsi.h" +#include "open_iscsi_compat.h" + static int iscsi_dbg_lib_conn; module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int, S_IRUGO | S_IWUSR); @@ -518,7 +520,7 @@ static void iscsi_free_task(struct iscsi_task *task) if (conn->login_task == task) return; - kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); + __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; @@ -738,7 +740,7 @@ __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } @@ -1568,7 +1570,7 @@ static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, { struct iscsi_task *task; - if (!kfifo_out(&conn->session->cmdpool.queue, + if (!__kfifo_get(conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; @@ -1738,21 +1740,9 @@ fault: } EXPORT_SYMBOL_GPL(iscsi_queuecommand); -int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) +int iscsi_change_queue_depth(struct scsi_device *sdev, int depth) { - switch (reason) { - case SCSI_QDEPTH_DEFAULT: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - case SCSI_QDEPTH_QFULL: - scsi_track_queue_full(sdev, depth); - break; - case SCSI_QDEPTH_RAMP_UP: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - default: - return -EOPNOTSUPP; - } + scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); @@ -2524,7 +2514,12 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) if (q->pool == NULL) return -ENOMEM; - kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); + q->queue = kfifo_init((void*)q->pool, max * sizeof(void*), + GFP_KERNEL, NULL); + if (IS_ERR(q->queue)) { + q->queue = NULL; + goto enomem; + } for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); @@ -2532,7 +2527,7 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) q->max = i; goto enomem; } - kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); + __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { @@ -2555,6 +2550,7 @@ void iscsi_pool_free(struct iscsi_pool *q) for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); + kfree(q->queue); } EXPORT_SYMBOL_GPL(iscsi_pool_free); @@ -2882,7 +2878,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); @@ -2902,7 +2898,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, return cls_conn; login_task_data_alloc_fail: - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); @@ -2965,7 +2961,7 @@ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; diff --git a/libiscsi.h b/libiscsi.h index 0563539..4be9333 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -231,7 +231,7 @@ struct iscsi_conn { }; struct iscsi_pool { - struct kfifo queue; /* FIFO Queue */ + struct kfifo *queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; @@ -334,8 +334,7 @@ struct iscsi_host { /* * scsi host template */ -extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, - int reason); +extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 1122de4..c3ff728 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -446,15 +446,15 @@ void iscsi_tcp_cleanup_task(struct iscsi_task *task) return; /* flush task's r2t queues */ - while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + while (__kfifo_get(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } @@ -542,7 +542,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) return 0; } - rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); + rc = __kfifo_get(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " @@ -555,7 +555,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -571,7 +571,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, r2t->data_offset, scsi_out(task->sc)->length); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -581,7 +581,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; - kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); + __kfifo_put(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); @@ -952,7 +952,7 @@ int iscsi_tcp_task_init(struct iscsi_task *task) return conn->session->tt->init_pdu(task, 0, task->data_count); } - BUG_ON(kfifo_len(&tcp_task->r2tqueue)); + BUG_ON(__kfifo_len(tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ @@ -983,7 +983,7 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); - kfifo_in(&tcp_task->r2tpool.queue, + __kfifo_put(tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; @@ -991,12 +991,9 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) } if (r2t == NULL) { - if (kfifo_out(&tcp_task->r2tqueue, - (void *)&tcp_task->r2t, sizeof(void *)) != - sizeof(void *)) - r2t = NULL; - else - r2t = tcp_task->r2t; + __kfifo_get(tcp_task->r2tqueue, + (void *)&tcp_task->r2t, sizeof(void *)); + r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } @@ -1131,8 +1128,9 @@ int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) } /* R2T xmit queue */ - if (kfifo_alloc(&tcp_task->r2tqueue, - session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { + tcp_task->r2tqueue = kfifo_alloc( + session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL); + if (tcp_task->r2tqueue == ERR_PTR(-ENOMEM)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } @@ -1145,7 +1143,7 @@ r2t_alloc_fail: struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; @@ -1160,7 +1158,7 @@ void iscsi_tcp_r2tpool_free(struct iscsi_session *session) struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index c020eee..3bacef5 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -80,7 +80,7 @@ struct iscsi_tcp_task { int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; - struct kfifo r2tqueue; + struct kfifo *r2tqueue; void *dd_data; }; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..50ab84d --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,276 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif diff --git a/scsi_transport_iscsi.c b/scsi_transport_iscsi.c index fed8c9e..3b28918 100644 --- a/scsi_transport_iscsi.c +++ b/scsi_transport_iscsi.c @@ -31,6 +31,8 @@ #include "scsi_transport_iscsi.h" #include "iscsi_if.h" +#include "open_iscsi_compat.h" + #define ISCSI_SESSION_ATTRS 22 #define ISCSI_CONN_ATTRS 13 #define ISCSI_HOST_ATTRS 4 -- 1.6.6.1 open-iscsi-2.0.873/kernel/2.6.28-32_compat.patch000066400000000000000000000367021175631155400206070ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..197d314 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " diff --git a/libiscsi.c b/libiscsi.c index 59e3a5f..b79453a 100644 --- a/libiscsi.c +++ b/libiscsi.c @@ -518,7 +518,7 @@ static void iscsi_free_task(struct iscsi_task *task) if (conn->login_task == task) return; - kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); + __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; @@ -738,7 +738,7 @@ __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } @@ -1568,7 +1568,7 @@ static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, { struct iscsi_task *task; - if (!kfifo_out(&conn->session->cmdpool.queue, + if (!__kfifo_get(conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; @@ -1738,21 +1738,9 @@ fault: } EXPORT_SYMBOL_GPL(iscsi_queuecommand); -int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) +int iscsi_change_queue_depth(struct scsi_device *sdev, int depth) { - switch (reason) { - case SCSI_QDEPTH_DEFAULT: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - case SCSI_QDEPTH_QFULL: - scsi_track_queue_full(sdev, depth); - break; - case SCSI_QDEPTH_RAMP_UP: - scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); - break; - default: - return -EOPNOTSUPP; - } + scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); @@ -2524,7 +2512,12 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) if (q->pool == NULL) return -ENOMEM; - kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); + q->queue = kfifo_init((void*)q->pool, max * sizeof(void*), + GFP_KERNEL, NULL); + if (IS_ERR(q->queue)) { + q->queue = NULL; + goto enomem; + } for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); @@ -2532,7 +2525,7 @@ iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) q->max = i; goto enomem; } - kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); + __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { @@ -2555,6 +2548,7 @@ void iscsi_pool_free(struct iscsi_pool *q) for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); + kfree(q->queue); } EXPORT_SYMBOL_GPL(iscsi_pool_free); @@ -2882,7 +2876,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); - if (!kfifo_out(&session->cmdpool.queue, + if (!__kfifo_get(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); @@ -2902,7 +2896,7 @@ iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, return cls_conn; login_task_data_alloc_fail: - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); @@ -2965,7 +2959,7 @@ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); - kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, + __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; diff --git a/libiscsi.h b/libiscsi.h index 0563539..4be9333 100644 --- a/libiscsi.h +++ b/libiscsi.h @@ -231,7 +231,7 @@ struct iscsi_conn { }; struct iscsi_pool { - struct kfifo queue; /* FIFO Queue */ + struct kfifo *queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; @@ -334,8 +334,7 @@ struct iscsi_host { /* * scsi host template */ -extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, - int reason); +extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); diff --git a/libiscsi_tcp.c b/libiscsi_tcp.c index 1122de4..c3ff728 100644 --- a/libiscsi_tcp.c +++ b/libiscsi_tcp.c @@ -446,15 +446,15 @@ void iscsi_tcp_cleanup_task(struct iscsi_task *task) return; /* flush task's r2t queues */ - while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + while (__kfifo_get(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } @@ -542,7 +542,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) return 0; } - rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); + rc = __kfifo_get(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " @@ -555,7 +555,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -571,7 +571,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, r2t->data_offset, scsi_out(task->sc)->length); - kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, + __kfifo_put(tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } @@ -581,7 +581,7 @@ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; - kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); + __kfifo_put(tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); @@ -952,7 +952,7 @@ int iscsi_tcp_task_init(struct iscsi_task *task) return conn->session->tt->init_pdu(task, 0, task->data_count); } - BUG_ON(kfifo_len(&tcp_task->r2tqueue)); + BUG_ON(__kfifo_len(tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ @@ -983,7 +983,7 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); - kfifo_in(&tcp_task->r2tpool.queue, + __kfifo_put(tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; @@ -991,12 +991,9 @@ static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) } if (r2t == NULL) { - if (kfifo_out(&tcp_task->r2tqueue, - (void *)&tcp_task->r2t, sizeof(void *)) != - sizeof(void *)) - r2t = NULL; - else - r2t = tcp_task->r2t; + __kfifo_get(tcp_task->r2tqueue, + (void *)&tcp_task->r2t, sizeof(void *)); + r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } @@ -1131,8 +1128,9 @@ int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) } /* R2T xmit queue */ - if (kfifo_alloc(&tcp_task->r2tqueue, - session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { + tcp_task->r2tqueue = kfifo_alloc( + session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL); + if (tcp_task->r2tqueue == ERR_PTR(-ENOMEM)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } @@ -1145,7 +1143,7 @@ r2t_alloc_fail: struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; @@ -1160,7 +1158,7 @@ void iscsi_tcp_r2tpool_free(struct iscsi_session *session) struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; - kfifo_free(&tcp_task->r2tqueue); + kfifo_free(tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } diff --git a/libiscsi_tcp.h b/libiscsi_tcp.h index c020eee..3bacef5 100644 --- a/libiscsi_tcp.h +++ b/libiscsi_tcp.h @@ -80,7 +80,7 @@ struct iscsi_tcp_task { int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; - struct kfifo r2tqueue; + struct kfifo *r2tqueue; void *dd_data; }; diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..50ab84d --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,276 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif -- 1.6.6.1 open-iscsi-2.0.873/kernel/2.6.33-34_compat.patch000066400000000000000000000145641175631155400206070ustar00rootroot00000000000000diff --git a/iscsi_tcp.c b/iscsi_tcp.c index 2a401b9..197d314 100644 --- a/iscsi_tcp.c +++ b/iscsi_tcp.c @@ -43,6 +43,7 @@ #include #include "scsi_transport_iscsi.h" +#include "open_iscsi_compat.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " diff --git a/open_iscsi_compat.h b/open_iscsi_compat.h new file mode 100644 index 0000000..50ab84d --- /dev/null +++ b/open_iscsi_compat.h @@ -0,0 +1,276 @@ +#include +#include +#include +#include + +#ifndef OPEN_ISCSI_COMPAT +#define OPEN_ISCSI_COMPAT + +#ifndef SCAN_WILD_CARD +#define SCAN_WILD_CARD ~0 +#endif + +#ifndef NIPQUAD_FMT +#define NIPQUAD_FMT "%u.%u.%u.%u" +#endif + +#ifndef NIP6_FMT +#define NIP6_FMT "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" +#endif + +#ifndef DEFINE_MUTEX + +/* mutex changes from 2.6.16-rc1 and up */ +#define DEFINE_MUTEX DECLARE_MUTEX +#define mutex_lock down +#define mutex_unlock up +#define mutex semaphore +#define mutex_init init_MUTEX +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12) + +void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun) +{ + int i; + + memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun)); + + for (i = 0; i < sizeof(lun); i += 2) { + scsilun->scsi_lun[i] = (lun >> 8) & 0xFF; + scsilun->scsi_lun[i+1] = lun & 0xFF; + lun = lun >> 16; + } +} + +#define __nlmsg_put(skb, daemon_pid, seq, type, len, flags) \ + __nlmsg_put(skb, daemon_pid, 0, 0, len) + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define gfp_t unsigned + +void *kzalloc(size_t size, gfp_t flags) +{ + void *ret = kmalloc(size, flags); + if (ret) + memset(ret, 0, size); +} + +#endif + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19) + +#include "linux/crypto.h" + +#define CRYPTO_ALG_ASYNC 0x00000080 +struct hash_desc +{ + struct crypto_tfm *tfm; + u32 flags; +}; + +static inline int crypto_hash_init(struct hash_desc *desc) +{ + crypto_digest_init(desc->tfm); + return 0; +} + +static inline int crypto_hash_digest(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes, u8 *out) +{ + crypto_digest_digest(desc->tfm, sg, 1, out); + return nbytes; +} + +static inline int crypto_hash_update(struct hash_desc *desc, + struct scatterlist *sg, + unsigned int nbytes) +{ + crypto_digest_update(desc->tfm, sg, 1); + return nbytes; +} + +static inline int crypto_hash_final(struct hash_desc *desc, u8 *out) +{ + crypto_digest_final(desc->tfm, out); + return 0; +} + +static inline struct crypto_tfm *crypto_alloc_hash(const char *alg_name, + u32 type, u32 mask) +{ + struct crypto_tfm *ret = crypto_alloc_tfm(alg_name ,type); + return ret ? ret : ERR_PTR(-ENOMEM); +} + +static inline void crypto_free_hash(struct crypto_tfm *tfm) +{ + crypto_free_tfm(tfm); +} + +int kernel_getsockname(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 0); +} + +int kernel_getpeername(struct socket *sock, struct sockaddr *addr, + int *addrlen) +{ + return sock->ops->getname(sock, addr, addrlen, 1); +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,20) + +static inline int is_power_of_2(unsigned long n) +{ + return (n != 0 && ((n & (n - 1)) == 0)); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +static inline struct nlmsghdr *nlmsg_hdr(const struct sk_buff *skb) +{ + return (struct nlmsghdr *)skb->data; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +static inline void *shost_priv(struct Scsi_Host *shost) +{ + return (void *)shost->hostdata; +} + +/* + * Note: We do not support bidi for the compat modules if the kernel + * does not have support. + */ +#define scsi_sg_count(cmd) ((cmd)->use_sg) +#define scsi_sglist(cmd) ((struct scatterlist *)(cmd)->request_buffer) +#define scsi_bufflen(cmd) ((cmd)->request_bufflen) + +static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid) +{ + cmd->resid = resid; +} + +static inline int scsi_get_resid(struct scsi_cmnd *cmd) +{ + return cmd->resid; +} + +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +static inline unsigned long rounddown_pow_of_two(unsigned long n) +{ + return 1UL << (fls_long(n) - 1); +} + + +static inline struct scatterlist *sg_next(struct scatterlist *sg) +{ + if (!sg) { + BUG(); + return NULL; + } + return sg + 1; +} + +#define for_each_sg(sglist, sg, nr, __i) \ + for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg)) + +#define sg_page(_sg) _sg->page + +static inline void sg_set_page(struct scatterlist *sg, struct page *page, + unsigned int len, unsigned int offset) +{ + sg->page = page; + sg->offset = offset; + sg->length = len; +} + +static inline void sg_init_table(struct scatterlist *sgl, unsigned int nents) +{ + memset(sgl, 0, sizeof(*sgl) * nents); +} +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,24) + +static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd) +{ + return 0; +} + +#define netlink_kernel_release(_nls) \ + sock_release(_nls->sk_socket) + + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, input) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23) + +#define netlink_kernel_create(net, uint, groups, input, cb_mutex, mod) \ + netlink_kernel_create(uint, groups, input, cb_mutex, mod) + +#endif + +#ifndef DID_TRANSPORT_DISRUPTED +#define DID_TRANSPORT_DISRUPTED DID_BUS_BUSY +#endif + +#ifndef DID_TRANSPORT_FAILFAST +#define DID_TRANSPORT_FAILFAST DID_NO_CONNECT +#endif + +#ifndef SCSI_MLQUEUE_TARGET_BUSY +#define SCSI_MLQUEUE_TARGET_BUSY SCSI_MLQUEUE_HOST_BUSY +#endif + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,27) + +#define BLK_EH_NOT_HANDLED EH_NOT_HANDLED +#define BLK_EH_RESET_TIMER EH_RESET_TIMER + +#define blk_eh_timer_return scsi_eh_timer_return + +#endif + + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,34) + +static inline wait_queue_head_t *sk_sleep(struct sock *sk) +{ + return sk->sk_sleep; +} + +#endif + +#endif -- 1.6.6.1 open-iscsi-2.0.873/kernel/Makefile000066400000000000000000000135401175631155400166770ustar00rootroot00000000000000# # Makefile for the Linux Kernel iSCSI Initiator # # This Makefile invokes KBuild from outside the kernel directory when # used from the main open-iscsi package. It also contains all of the # KBuild stuff needed to build the modules. # # Kbuild stuff, the following is the only part of this file that KBuild # actually uses itself. EXTRA_CFLAGS += -I$(obj) -I$(obj)/../include ifeq ($(DEBUG_SCSI), 1) EXTRA_CFLAGS += -DDEBUG_SCSI=1 endif ifeq ($(DEBUG_TCP), 1) EXTRA_CFLAGS += -DDEBUG_TCP=1 endif obj-m += scsi_transport_iscsi.o obj-m += libiscsi.o obj-m += libiscsi_tcp.o obj-m += iscsi_tcp.o # Everything beyond this point is used to call KBuild or handle support # for multiple kernel versions. # Kbuild verbosity V ?= 0 # allow users to override these # eg to compile for a kernel that you aren't currently running KERNELRELEASE ?= $(shell uname -r) KSRC ?= /lib/modules/$(KERNELRELEASE)/build KBUILD_OUTPUT ?= # this is the basic Kbuild invocation, just append your make target KBUILD_BASE = +$(MAKE) -C $(KSRC) M=`pwd` KBUILD_OUTPUT=$(KBUILD_OUTPUT) $(KARCH) V=$(V) all: kernel_check $(KBUILD_BASE) modules # ============ BEGIN code for kernel_check and source patching ================ # We calculate the Linux version for compilation. Than according to version, # if needed, we patch source-code to match the compiling kernel. # if you need a new kernel sub-version just add a target below. # # IMPORTANT: do "make clean" before submitting to SVN so source is in unpatched # form. #some constants 14to23_patch=2.6.14-23_compat.patch 24_patch=2.6.24_compat.patch 26_patch=2.6.26_compat.patch 27_patch=2.6.27_compat.patch 28to32_patch=2.6.28-32_compat.patch 33to34_patch=2.6.33-34_compat.patch all_patches=14to21_patch 20to21_patch 24_patch 26_patch 27_patch 28to32_patch 33to34_patch cur_patched=cur_patched ## fun stuff for maintaining multiple versions # check to see if code is unpatched unpatch_code=$(shell test -e $(cur_patched) && echo do_unpatch_code ) KSUBLEVEL = $(shell cat $(KSRC)/Makefile | awk -F= '/^SUBLEVEL =/ {print $$2}' | \ sed 's/^[ \t]*//;s/[ \t]*$$//') KERNEL_TARGET=linux_2_6_$(KSUBLEVEL) kernel_check: $(KERNEL_TARGET) linux_2_6_14: has_14to23_patch linux_2_6_15: has_14to23_patch linux_2_6_16: has_14to23_patch linux_2_6_17: has_14to23_patch linux_2_6_18: has_14to23_patch linux_2_6_19: has_14to23_patch linux_2_6_20: has_14to23_patch linux_2_6_21: has_14to23_patch linux_2_6_22: has_14to23_patch linux_2_6_23: has_14to23_patch linux_2_6_24: has_24_patch linux_2_6_25: has_24_patch linux_2_6_26: has_26_patch linux_2_6_27: has_27_patch linux_2_6_28: has_28to32_patch linux_2_6_29: has_28to32_patch linux_2_6_30: has_28to32_patch linux_2_6_31: has_28to32_patch linux_2_6_32: has_28to32_patch linux_2_6_33: has_33to34_patch linux_2_6_34: has_33to34_patch linux_2_6_35: $(unpatch_code) do_unpatch_code: echo "Un-patching source code for use with linux-2.6.14 and up ..." patch -R -E -p1 < $(cur_patched) rm -f `readlink $(cur_patched)` rm -f $(cur_patched) # these below targets must be the same as the variable name prefixed by has_ # otherwise below compat_patch: target will not work has_14to23_patch: $(14to23_patch) echo "Patching source code for linux-2.6.14-23 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(14to23_patch) cp $(14to23_patch) $@ ln -s $@ $(cur_patched) has_24_patch: $(24_patch) echo "Patching source code for linux-2.6.24-25 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(24_patch) cp $(24_patch) $@ ln -s $@ $(cur_patched) has_26_patch: $(26_patch) echo "Patching source code for linux-2.6.26 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(26_patch) cp $(26_patch) $@ ln -s $@ $(cur_patched) has_27_patch: $(27_patch) echo "Patching source code for linux-2.6.27 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(27_patch) cp $(27_patch) $@ ln -s $@ $(cur_patched) has_28to32_patch: $(28to32_patch) echo "Patching source code for linux-2.6.28-33 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(28to32_patch) cp $(28to32_patch) $@ ln -s $@ $(cur_patched) has_33to34_patch: $(33to34_patch) echo "Patching source code for linux-2.6.33-34 ..." if [ -e $(cur_patched) ]; then \ make -C . clean; \ fi patch -p1 < $(33to34_patch) cp $(33to34_patch) $@ ln -s $@ $(cur_patched) # ============ END code for kernel_check and source patching ================= clean: $(unpatch_code) $(KBUILD_BASE) clean rm -f Module.symvers ## The folowing compat_patch target is what we need to do to prepare a clean # compat_patch set after new code is check-in to svn. To keep patches fuzzless. # the new patches are writen into .new files so svn diff of next file will # not trip on them. compat_patch: $(unpatch_code) test -z "$(svn diff|head)" || { \ echo "please run make compat_patch after changse are submited to svn"; \ exit 1; \ } for the_patch in all_patches ; do \ make -C . has_$(the_patch); \ svn diff > ${!the_patch}.new; \ done # the following is only for convienience # do not submit to Linus # it's also called from the toplevel makefile # INSTALL_MOD_DIR is set so that the drivers go into the correct location using Kbuild # it defaults to 'extra' otherwise INSTALL_MOD_DIR ?= kernel/drivers/scsi # this allows packaging of modules ifdef DESTDIR INSTALL_MOD_PATH=$(DESTDIR) else INSTALL_MOD_PATH= endif # this evil rule ensures that the modules get build if you specify $(ko) # as a dependancy. ko = $(patsubst %.o,%.ko,$(obj-m)) $(ko): all # now the actual command install_kernel: $(ko) $(KBUILD_BASE) modules_install INSTALL_MOD_DIR=$(INSTALL_MOD_DIR) INSTALL_MOD_PATH=$(INSTALL_MOD_PATH) dpkg_divert: for module in $(ko) ; do \ dpkg-divert --rename /lib/modules/$(KERNELRELEASE)/$(INSTALL_MOD_DIR)/$$module ; \ done # vim: ft=make tw=72 sw=4 ts=4: open-iscsi-2.0.873/kernel/iscsi_tcp.c000066400000000000000000000660651175631155400173750ustar00rootroot00000000000000/* * iSCSI Initiator over TCP/IP Data-Path * * Copyright (C) 2004 Dmitry Yusupov * Copyright (C) 2004 Alex Aizman * Copyright (C) 2005 - 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. * * Credits: * Christoph Hellwig * FUJITA Tomonori * Arne Redlich * Zhenyu Wang */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "scsi_transport_iscsi.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " "Dmitry Yusupov , " "Alex Aizman "); MODULE_DESCRIPTION("iSCSI/TCP data-path"); MODULE_LICENSE("GPL"); static struct scsi_transport_template *iscsi_sw_tcp_scsi_transport; static struct scsi_host_template iscsi_sw_tcp_sht; static struct iscsi_transport iscsi_sw_tcp_transport; static unsigned int iscsi_max_lun = 512; module_param_named(max_lun, iscsi_max_lun, uint, S_IRUGO); static int iscsi_sw_tcp_dbg; module_param_named(debug_iscsi_tcp, iscsi_sw_tcp_dbg, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_iscsi_tcp, "Turn on debugging for iscsi_tcp module " "Set to 1 to turn on, and zero to turn off. Default is off."); #define ISCSI_SW_TCP_DBG(_conn, dbg_fmt, arg...) \ do { \ if (iscsi_sw_tcp_dbg) \ iscsi_conn_printk(KERN_INFO, _conn, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); /** * iscsi_sw_tcp_recv - TCP receive in sendfile fashion * @rd_desc: read descriptor * @skb: socket buffer * @offset: offset in skb * @len: skb->len - offset */ static int iscsi_sw_tcp_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len) { struct iscsi_conn *conn = rd_desc->arg.data; unsigned int consumed, total_consumed = 0; int status; ISCSI_SW_TCP_DBG(conn, "in %d bytes\n", skb->len - offset); do { status = 0; consumed = iscsi_tcp_recv_skb(conn, skb, offset, 0, &status); offset += consumed; total_consumed += consumed; } while (consumed != 0 && status != ISCSI_TCP_SKB_DONE); ISCSI_SW_TCP_DBG(conn, "read %d bytes status %d\n", skb->len - offset, status); return total_consumed; } /** * iscsi_sw_sk_state_check - check socket state * @sk: socket * * If the socket is in CLOSE or CLOSE_WAIT we should * not close the connection if there is still some * data pending. */ static inline int iscsi_sw_sk_state_check(struct sock *sk) { struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data; if ((sk->sk_state == TCP_CLOSE_WAIT || sk->sk_state == TCP_CLOSE) && !atomic_read(&sk->sk_rmem_alloc)) { ISCSI_SW_TCP_DBG(conn, "TCP_CLOSE|TCP_CLOSE_WAIT\n"); iscsi_conn_failure(conn, ISCSI_ERR_TCP_CONN_CLOSE); return -ECONNRESET; } return 0; } static void iscsi_sw_tcp_data_ready(struct sock *sk, int flag) { struct iscsi_conn *conn = sk->sk_user_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; read_descriptor_t rd_desc; read_lock(&sk->sk_callback_lock); /* * Use rd_desc to pass 'conn' to iscsi_tcp_recv. * We set count to 1 because we want the network layer to * hand us all the skbs that are available. iscsi_tcp_recv * handled pdus that cross buffers or pdus that still need data. */ rd_desc.arg.data = conn; rd_desc.count = 1; tcp_read_sock(sk, &rd_desc, iscsi_sw_tcp_recv); iscsi_sw_sk_state_check(sk); read_unlock(&sk->sk_callback_lock); /* If we had to (atomically) map a highmem page, * unmap it now. */ iscsi_tcp_segment_unmap(&tcp_conn->in.segment); } static void iscsi_sw_tcp_state_change(struct sock *sk) { struct iscsi_tcp_conn *tcp_conn; struct iscsi_sw_tcp_conn *tcp_sw_conn; struct iscsi_conn *conn; struct iscsi_session *session; void (*old_state_change)(struct sock *); read_lock(&sk->sk_callback_lock); conn = (struct iscsi_conn*)sk->sk_user_data; session = conn->session; iscsi_sw_sk_state_check(sk); tcp_conn = conn->dd_data; tcp_sw_conn = tcp_conn->dd_data; old_state_change = tcp_sw_conn->old_state_change; read_unlock(&sk->sk_callback_lock); old_state_change(sk); } /** * iscsi_write_space - Called when more output buffer space is available * @sk: socket space is available for **/ static void iscsi_sw_tcp_write_space(struct sock *sk) { struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; tcp_sw_conn->old_write_space(sk); ISCSI_SW_TCP_DBG(conn, "iscsi_write_space\n"); iscsi_conn_queue_work(conn); } static void iscsi_sw_tcp_conn_set_callbacks(struct iscsi_conn *conn) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct sock *sk = tcp_sw_conn->sock->sk; /* assign new callbacks */ write_lock_bh(&sk->sk_callback_lock); sk->sk_user_data = conn; tcp_sw_conn->old_data_ready = sk->sk_data_ready; tcp_sw_conn->old_state_change = sk->sk_state_change; tcp_sw_conn->old_write_space = sk->sk_write_space; sk->sk_data_ready = iscsi_sw_tcp_data_ready; sk->sk_state_change = iscsi_sw_tcp_state_change; sk->sk_write_space = iscsi_sw_tcp_write_space; write_unlock_bh(&sk->sk_callback_lock); } static void iscsi_sw_tcp_conn_restore_callbacks(struct iscsi_conn *conn) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct sock *sk = tcp_sw_conn->sock->sk; /* restore socket callbacks, see also: iscsi_conn_set_callbacks() */ write_lock_bh(&sk->sk_callback_lock); sk->sk_user_data = NULL; sk->sk_data_ready = tcp_sw_conn->old_data_ready; sk->sk_state_change = tcp_sw_conn->old_state_change; sk->sk_write_space = tcp_sw_conn->old_write_space; sk->sk_no_check = 0; write_unlock_bh(&sk->sk_callback_lock); } /** * iscsi_sw_tcp_xmit_segment - transmit segment * @tcp_conn: the iSCSI TCP connection * @segment: the buffer to transmnit * * This function transmits as much of the buffer as * the network layer will accept, and returns the number of * bytes transmitted. * * If CRC hashing is enabled, the function will compute the * hash as it goes. When the entire segment has been transmitted, * it will retrieve the hash value and send it as well. */ static int iscsi_sw_tcp_xmit_segment(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct socket *sk = tcp_sw_conn->sock; unsigned int copied = 0; int r = 0; while (!iscsi_tcp_segment_done(tcp_conn, segment, 0, r)) { struct scatterlist *sg; unsigned int offset, copy; int flags = 0; r = 0; offset = segment->copied; copy = segment->size - offset; if (segment->total_copied + segment->size < segment->total_size) flags |= MSG_MORE; /* Use sendpage if we can; else fall back to sendmsg */ if (!segment->data) { sg = segment->sg; offset += segment->sg_offset + sg->offset; r = tcp_sw_conn->sendpage(sk, sg_page(sg), offset, copy, flags); } else { struct msghdr msg = { .msg_flags = flags }; struct kvec iov = { .iov_base = segment->data + offset, .iov_len = copy }; r = kernel_sendmsg(sk, &msg, &iov, 1, copy); } if (r < 0) { iscsi_tcp_segment_unmap(segment); return r; } copied += r; } return copied; } /** * iscsi_sw_tcp_xmit - TCP transmit **/ static int iscsi_sw_tcp_xmit(struct iscsi_conn *conn) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct iscsi_segment *segment = &tcp_sw_conn->out.segment; unsigned int consumed = 0; int rc = 0; while (1) { rc = iscsi_sw_tcp_xmit_segment(tcp_conn, segment); /* * We may not have been able to send data because the conn * is getting stopped. libiscsi will know so propogate err * for it to do the right thing. */ if (rc == -EAGAIN) return rc; else if (rc < 0) { rc = ISCSI_ERR_XMIT_FAILED; goto error; } else if (rc == 0) break; consumed += rc; if (segment->total_copied >= segment->total_size) { if (segment->done != NULL) { rc = segment->done(tcp_conn, segment); if (rc != 0) goto error; } } } ISCSI_SW_TCP_DBG(conn, "xmit %d bytes\n", consumed); conn->txdata_octets += consumed; return consumed; error: /* Transmit error. We could initiate error recovery * here. */ ISCSI_SW_TCP_DBG(conn, "Error sending PDU, errno=%d\n", rc); iscsi_conn_failure(conn, rc); return -EIO; } /** * iscsi_tcp_xmit_qlen - return the number of bytes queued for xmit */ static inline int iscsi_sw_tcp_xmit_qlen(struct iscsi_conn *conn) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct iscsi_segment *segment = &tcp_sw_conn->out.segment; return segment->total_copied - segment->total_size; } static int iscsi_sw_tcp_pdu_xmit(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; int rc; while (iscsi_sw_tcp_xmit_qlen(conn)) { rc = iscsi_sw_tcp_xmit(conn); if (rc == 0) return -EAGAIN; if (rc < 0) return rc; } return 0; } /* * This is called when we're done sending the header. * Simply copy the data_segment to the send segment, and return. */ static int iscsi_sw_tcp_send_hdr_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; tcp_sw_conn->out.segment = tcp_sw_conn->out.data_segment; ISCSI_SW_TCP_DBG(tcp_conn->iscsi_conn, "Header done. Next segment size %u total_size %u\n", tcp_sw_conn->out.segment.size, tcp_sw_conn->out.segment.total_size); return 0; } static void iscsi_sw_tcp_send_hdr_prep(struct iscsi_conn *conn, void *hdr, size_t hdrlen) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; ISCSI_SW_TCP_DBG(conn, "%s\n", conn->hdrdgst_en ? "digest enabled" : "digest disabled"); /* Clear the data segment - needs to be filled in by the * caller using iscsi_tcp_send_data_prep() */ memset(&tcp_sw_conn->out.data_segment, 0, sizeof(struct iscsi_segment)); /* If header digest is enabled, compute the CRC and * place the digest into the same buffer. We make * sure that both iscsi_tcp_task and mtask have * sufficient room. */ if (conn->hdrdgst_en) { iscsi_tcp_dgst_header(&tcp_sw_conn->tx_hash, hdr, hdrlen, hdr + hdrlen); hdrlen += ISCSI_DIGEST_SIZE; } /* Remember header pointer for later, when we need * to decide whether there's a payload to go along * with the header. */ tcp_sw_conn->out.hdr = hdr; iscsi_segment_init_linear(&tcp_sw_conn->out.segment, hdr, hdrlen, iscsi_sw_tcp_send_hdr_done, NULL); } /* * Prepare the send buffer for the payload data. * Padding and checksumming will all be taken care * of by the iscsi_segment routines. */ static int iscsi_sw_tcp_send_data_prep(struct iscsi_conn *conn, struct scatterlist *sg, unsigned int count, unsigned int offset, unsigned int len) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct hash_desc *tx_hash = NULL; unsigned int hdr_spec_len; ISCSI_SW_TCP_DBG(conn, "offset=%d, datalen=%d %s\n", offset, len, conn->datadgst_en ? "digest enabled" : "digest disabled"); /* Make sure the datalen matches what the caller said he would send. */ hdr_spec_len = ntoh24(tcp_sw_conn->out.hdr->dlength); WARN_ON(iscsi_padded(len) != iscsi_padded(hdr_spec_len)); if (conn->datadgst_en) tx_hash = &tcp_sw_conn->tx_hash; return iscsi_segment_seek_sg(&tcp_sw_conn->out.data_segment, sg, count, offset, len, NULL, tx_hash); } static void iscsi_sw_tcp_send_linear_data_prep(struct iscsi_conn *conn, void *data, size_t len) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct hash_desc *tx_hash = NULL; unsigned int hdr_spec_len; ISCSI_SW_TCP_DBG(conn, "datalen=%zd %s\n", len, conn->datadgst_en ? "digest enabled" : "digest disabled"); /* Make sure the datalen matches what the caller said he would send. */ hdr_spec_len = ntoh24(tcp_sw_conn->out.hdr->dlength); WARN_ON(iscsi_padded(len) != iscsi_padded(hdr_spec_len)); if (conn->datadgst_en) tx_hash = &tcp_sw_conn->tx_hash; iscsi_segment_init_linear(&tcp_sw_conn->out.data_segment, data, len, NULL, tx_hash); } static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task, unsigned int offset, unsigned int count) { struct iscsi_conn *conn = task->conn; int err = 0; iscsi_sw_tcp_send_hdr_prep(conn, task->hdr, task->hdr_len); if (!count) return 0; if (!task->sc) iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count); else { struct scsi_data_buffer *sdb = scsi_out(task->sc); err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl, sdb->table.nents, offset, count); } if (err) { /* got invalid offset/len */ return -EIO; } return 0; } static int iscsi_sw_tcp_pdu_alloc(struct iscsi_task *task, uint8_t opcode) { struct iscsi_tcp_task *tcp_task = task->dd_data; task->hdr = task->dd_data + sizeof(*tcp_task); task->hdr_max = sizeof(struct iscsi_sw_tcp_hdrbuf) - ISCSI_DIGEST_SIZE; return 0; } static struct iscsi_cls_conn * iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx) { struct iscsi_conn *conn; struct iscsi_cls_conn *cls_conn; struct iscsi_tcp_conn *tcp_conn; struct iscsi_sw_tcp_conn *tcp_sw_conn; cls_conn = iscsi_tcp_conn_setup(cls_session, sizeof(*tcp_sw_conn), conn_idx); if (!cls_conn) return NULL; conn = cls_conn->dd_data; tcp_conn = conn->dd_data; tcp_sw_conn = tcp_conn->dd_data; tcp_sw_conn->tx_hash.tfm = crypto_alloc_hash("crc32c", 0, CRYPTO_ALG_ASYNC); tcp_sw_conn->tx_hash.flags = 0; if (IS_ERR(tcp_sw_conn->tx_hash.tfm)) goto free_conn; tcp_sw_conn->rx_hash.tfm = crypto_alloc_hash("crc32c", 0, CRYPTO_ALG_ASYNC); tcp_sw_conn->rx_hash.flags = 0; if (IS_ERR(tcp_sw_conn->rx_hash.tfm)) goto free_tx_tfm; tcp_conn->rx_hash = &tcp_sw_conn->rx_hash; return cls_conn; free_tx_tfm: crypto_free_hash(tcp_sw_conn->tx_hash.tfm); free_conn: iscsi_conn_printk(KERN_ERR, conn, "Could not create connection due to crc32c " "loading error. Make sure the crc32c " "module is built as a module or into the " "kernel\n"); iscsi_tcp_conn_teardown(cls_conn); return NULL; } static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct socket *sock = tcp_sw_conn->sock; if (!sock) return; sock_hold(sock->sk); iscsi_sw_tcp_conn_restore_callbacks(conn); sock_put(sock->sk); spin_lock_bh(&session->lock); tcp_sw_conn->sock = NULL; spin_unlock_bh(&session->lock); sockfd_put(sock); } static void iscsi_sw_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; iscsi_sw_tcp_release_conn(conn); if (tcp_sw_conn->tx_hash.tfm) crypto_free_hash(tcp_sw_conn->tx_hash.tfm); if (tcp_sw_conn->rx_hash.tfm) crypto_free_hash(tcp_sw_conn->rx_hash.tfm); iscsi_tcp_conn_teardown(cls_conn); } static void iscsi_sw_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct socket *sock = tcp_sw_conn->sock; /* userspace may have goofed up and not bound us */ if (!sock) return; /* * Make sure our recv side is stopped. * Older tools called conn stop before ep_disconnect * so IO could still be coming in. */ write_lock_bh(&tcp_sw_conn->sock->sk->sk_callback_lock); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx); write_unlock_bh(&tcp_sw_conn->sock->sk->sk_callback_lock); sock->sk->sk_err = EIO; wake_up_interruptible(sk_sleep(sock->sk)); iscsi_conn_stop(cls_conn, flag); iscsi_sw_tcp_release_conn(conn); } static int iscsi_sw_tcp_get_addr(struct iscsi_conn *conn, struct socket *sock, char *buf, int *port, int (*getname)(struct socket *, struct sockaddr *, int *addrlen)) { struct sockaddr_storage *addr; struct sockaddr_in6 *sin6; struct sockaddr_in *sin; int rc = 0, len; addr = kmalloc(sizeof(*addr), GFP_KERNEL); if (!addr) return -ENOMEM; if (getname(sock, (struct sockaddr *) addr, &len)) { rc = -ENODEV; goto free_addr; } switch (addr->ss_family) { case AF_INET: sin = (struct sockaddr_in *)addr; spin_lock_bh(&conn->session->lock); #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,28) sprintf(buf, "%pI4", &sin->sin_addr.s_addr); #else sprintf(buf, NIPQUAD_FMT, NIPQUAD(sin->sin_addr.s_addr)); #endif *port = be16_to_cpu(sin->sin_port); spin_unlock_bh(&conn->session->lock); break; case AF_INET6: sin6 = (struct sockaddr_in6 *)addr; spin_lock_bh(&conn->session->lock); #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,28) sprintf(buf, "%pI6", &sin6->sin6_addr); #else sprintf(buf, NIP6_FMT, NIP6(sin6->sin6_addr)); #endif *port = be16_to_cpu(sin6->sin6_port); spin_unlock_bh(&conn->session->lock); break; } free_addr: kfree(addr); return rc; } static int iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session, struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, int is_leading) { struct Scsi_Host *shost = iscsi_session_to_shost(cls_session); struct iscsi_host *ihost = shost_priv(shost); struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; struct sock *sk; struct socket *sock; int err; /* lookup for existing socket */ sock = sockfd_lookup((int)transport_eph, &err); if (!sock) { iscsi_conn_printk(KERN_ERR, conn, "sockfd_lookup failed %d\n", err); return -EEXIST; } /* * copy these values now because if we drop the session * userspace may still want to query the values since we will * be using them for the reconnect */ err = iscsi_sw_tcp_get_addr(conn, sock, conn->portal_address, &conn->portal_port, kernel_getpeername); if (err) goto free_socket; err = iscsi_sw_tcp_get_addr(conn, sock, ihost->local_address, &ihost->local_port, kernel_getsockname); if (err) goto free_socket; err = iscsi_conn_bind(cls_session, cls_conn, is_leading); if (err) goto free_socket; /* bind iSCSI connection and socket */ tcp_sw_conn->sock = sock; /* setup Socket parameters */ sk = sock->sk; sk->sk_reuse = 1; sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */ sk->sk_allocation = GFP_ATOMIC; iscsi_sw_tcp_conn_set_callbacks(conn); tcp_sw_conn->sendpage = tcp_sw_conn->sock->ops->sendpage; /* * set receive state machine into initial state */ iscsi_tcp_hdr_recv_prep(tcp_conn); return 0; free_socket: sockfd_put(sock); return err; } static int iscsi_sw_tcp_conn_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf, int buflen) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; int value; switch(param) { case ISCSI_PARAM_HDRDGST_EN: iscsi_set_param(cls_conn, param, buf, buflen); break; case ISCSI_PARAM_DATADGST_EN: iscsi_set_param(cls_conn, param, buf, buflen); tcp_sw_conn->sendpage = conn->datadgst_en ? sock_no_sendpage : tcp_sw_conn->sock->ops->sendpage; break; case ISCSI_PARAM_MAX_R2T: sscanf(buf, "%d", &value); if (value <= 0 || !is_power_of_2(value)) return -EINVAL; if (session->max_r2t == value) break; iscsi_tcp_r2tpool_free(session); iscsi_set_param(cls_conn, param, buf, buflen); if (iscsi_tcp_r2tpool_alloc(session)) return -ENOMEM; break; default: return iscsi_set_param(cls_conn, param, buf, buflen); } return 0; } static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf) { struct iscsi_conn *conn = cls_conn->dd_data; int len; switch(param) { case ISCSI_PARAM_CONN_PORT: spin_lock_bh(&conn->session->lock); len = sprintf(buf, "%hu\n", conn->portal_port); spin_unlock_bh(&conn->session->lock); break; case ISCSI_PARAM_CONN_ADDRESS: spin_lock_bh(&conn->session->lock); len = sprintf(buf, "%s\n", conn->portal_address); spin_unlock_bh(&conn->session->lock); break; default: return iscsi_conn_get_param(cls_conn, param, buf); } return len; } static void iscsi_sw_tcp_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; stats->custom_length = 3; strcpy(stats->custom[0].desc, "tx_sendpage_failures"); stats->custom[0].value = tcp_sw_conn->sendpage_failures_cnt; strcpy(stats->custom[1].desc, "rx_discontiguous_hdr"); stats->custom[1].value = tcp_sw_conn->discontiguous_hdr_cnt; strcpy(stats->custom[2].desc, "eh_abort_cnt"); stats->custom[2].value = conn->eh_abort_cnt; iscsi_tcp_conn_get_stats(cls_conn, stats); } static struct iscsi_cls_session * iscsi_sw_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, uint16_t qdepth, uint32_t initial_cmdsn) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct Scsi_Host *shost; if (ep) { printk(KERN_ERR "iscsi_tcp: invalid ep %p.\n", ep); return NULL; } shost = iscsi_host_alloc(&iscsi_sw_tcp_sht, 0, 1); if (!shost) return NULL; shost->transportt = iscsi_sw_tcp_scsi_transport; shost->cmd_per_lun = qdepth; shost->max_lun = iscsi_max_lun; shost->max_id = 0; shost->max_channel = 0; shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE; if (iscsi_host_add(shost, NULL)) goto free_host; cls_session = iscsi_session_setup(&iscsi_sw_tcp_transport, shost, cmds_max, 0, sizeof(struct iscsi_tcp_task) + sizeof(struct iscsi_sw_tcp_hdrbuf), initial_cmdsn, 0); if (!cls_session) goto remove_host; session = cls_session->dd_data; shost->can_queue = session->scsi_cmds_max; if (iscsi_tcp_r2tpool_alloc(session)) goto remove_session; return cls_session; remove_session: iscsi_session_teardown(cls_session); remove_host: iscsi_host_remove(shost); free_host: iscsi_host_free(shost); return NULL; } static void iscsi_sw_tcp_session_destroy(struct iscsi_cls_session *cls_session) { struct Scsi_Host *shost = iscsi_session_to_shost(cls_session); iscsi_tcp_r2tpool_free(cls_session->dd_data); iscsi_session_teardown(cls_session); iscsi_host_remove(shost); iscsi_host_free(shost); } static int iscsi_sw_tcp_slave_alloc(struct scsi_device *sdev) { set_bit(QUEUE_FLAG_BIDI, &sdev->request_queue->queue_flags); return 0; } static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev) { blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_ANY); blk_queue_dma_alignment(sdev->request_queue, 0); return 0; } static struct scsi_host_template iscsi_sw_tcp_sht = { .module = THIS_MODULE, .name = "iSCSI Initiator over TCP/IP", .queuecommand = iscsi_queuecommand, .change_queue_depth = iscsi_change_queue_depth, .can_queue = ISCSI_DEF_XMIT_CMDS_MAX - 1, .sg_tablesize = 4096, .max_sectors = 0xFFFF, .cmd_per_lun = ISCSI_DEF_CMD_PER_LUN, .eh_abort_handler = iscsi_eh_abort, .eh_device_reset_handler= iscsi_eh_device_reset, .eh_target_reset_handler = iscsi_eh_recover_target, .use_clustering = DISABLE_CLUSTERING, .slave_alloc = iscsi_sw_tcp_slave_alloc, .slave_configure = iscsi_sw_tcp_slave_configure, .target_alloc = iscsi_target_alloc, .proc_name = "iscsi_tcp", .this_id = -1, }; static struct iscsi_transport iscsi_sw_tcp_transport = { .owner = THIS_MODULE, .name = "tcp", .caps = CAP_RECOVERY_L0 | CAP_MULTI_R2T | CAP_HDRDGST | CAP_DATADGST, .param_mask = ISCSI_MAX_RECV_DLENGTH | ISCSI_MAX_XMIT_DLENGTH | ISCSI_HDRDGST_EN | ISCSI_DATADGST_EN | ISCSI_INITIAL_R2T_EN | ISCSI_MAX_R2T | ISCSI_IMM_DATA_EN | ISCSI_FIRST_BURST | ISCSI_MAX_BURST | ISCSI_PDU_INORDER_EN | ISCSI_DATASEQ_INORDER_EN | ISCSI_ERL | ISCSI_CONN_PORT | ISCSI_CONN_ADDRESS | ISCSI_EXP_STATSN | ISCSI_PERSISTENT_PORT | ISCSI_PERSISTENT_ADDRESS | ISCSI_TARGET_NAME | ISCSI_TPGT | ISCSI_USERNAME | ISCSI_PASSWORD | ISCSI_USERNAME_IN | ISCSI_PASSWORD_IN | ISCSI_FAST_ABORT | ISCSI_ABORT_TMO | ISCSI_LU_RESET_TMO | ISCSI_TGT_RESET_TMO | ISCSI_PING_TMO | ISCSI_RECV_TMO | ISCSI_IFACE_NAME | ISCSI_INITIATOR_NAME, .host_param_mask = ISCSI_HOST_HWADDRESS | ISCSI_HOST_IPADDRESS | ISCSI_HOST_INITIATOR_NAME | ISCSI_HOST_NETDEV_NAME, /* session management */ .create_session = iscsi_sw_tcp_session_create, .destroy_session = iscsi_sw_tcp_session_destroy, /* connection management */ .create_conn = iscsi_sw_tcp_conn_create, .bind_conn = iscsi_sw_tcp_conn_bind, .destroy_conn = iscsi_sw_tcp_conn_destroy, .set_param = iscsi_sw_tcp_conn_set_param, .get_conn_param = iscsi_sw_tcp_conn_get_param, .get_session_param = iscsi_session_get_param, .start_conn = iscsi_conn_start, .stop_conn = iscsi_sw_tcp_conn_stop, /* iscsi host params */ .get_host_param = iscsi_host_get_param, .set_host_param = iscsi_host_set_param, /* IO */ .send_pdu = iscsi_conn_send_pdu, .get_stats = iscsi_sw_tcp_conn_get_stats, /* iscsi task/cmd helpers */ .init_task = iscsi_tcp_task_init, .xmit_task = iscsi_tcp_task_xmit, .cleanup_task = iscsi_tcp_cleanup_task, /* low level pdu helpers */ .xmit_pdu = iscsi_sw_tcp_pdu_xmit, .init_pdu = iscsi_sw_tcp_pdu_init, .alloc_pdu = iscsi_sw_tcp_pdu_alloc, /* recovery */ .session_recovery_timedout = iscsi_session_recovery_timedout, }; static int __init iscsi_sw_tcp_init(void) { if (iscsi_max_lun < 1) { printk(KERN_ERR "iscsi_tcp: Invalid max_lun value of %u\n", iscsi_max_lun); return -EINVAL; } iscsi_sw_tcp_scsi_transport = iscsi_register_transport( &iscsi_sw_tcp_transport); if (!iscsi_sw_tcp_scsi_transport) return -ENODEV; return 0; } static void __exit iscsi_sw_tcp_exit(void) { iscsi_unregister_transport(&iscsi_sw_tcp_transport); } module_init(iscsi_sw_tcp_init); module_exit(iscsi_sw_tcp_exit); open-iscsi-2.0.873/kernel/iscsi_tcp.h000066400000000000000000000035111175631155400173650ustar00rootroot00000000000000/* * iSCSI Initiator TCP Transport * Copyright (C) 2004 Dmitry Yusupov * Copyright (C) 2004 Alex Aizman * Copyright (C) 2005 - 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_SW_TCP_H #define ISCSI_SW_TCP_H #include "libiscsi.h" #include "libiscsi_tcp.h" struct socket; struct iscsi_tcp_conn; /* Socket connection send helper */ struct iscsi_sw_tcp_send { struct iscsi_hdr *hdr; struct iscsi_segment segment; struct iscsi_segment data_segment; }; struct iscsi_sw_tcp_conn { struct socket *sock; struct iscsi_sw_tcp_send out; /* old values for socket callbacks */ void (*old_data_ready)(struct sock *, int); void (*old_state_change)(struct sock *); void (*old_write_space)(struct sock *); /* data and header digests */ struct hash_desc tx_hash; /* CRC32C (Tx) */ struct hash_desc rx_hash; /* CRC32C (Rx) */ /* MIB custom statistics */ uint32_t sendpage_failures_cnt; uint32_t discontiguous_hdr_cnt; ssize_t (*sendpage)(struct socket *, struct page *, int, size_t, int); }; struct iscsi_sw_tcp_hdrbuf { struct iscsi_hdr hdrbuf; char hdrextbuf[ISCSI_MAX_AHS_SIZE + ISCSI_DIGEST_SIZE]; }; #endif /* ISCSI_SW_TCP_H */ open-iscsi-2.0.873/kernel/libiscsi.c000066400000000000000000002654111175631155400172120ustar00rootroot00000000000000/* * iSCSI lib functions * * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * Copyright (C) 2004 - 2006 Mike Christie * Copyright (C) 2004 - 2005 Dmitry Yusupov * Copyright (C) 2004 - 2005 Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "iscsi_proto.h" #include "scsi_transport_iscsi.h" #include "libiscsi.h" static int iscsi_dbg_lib_conn; module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_conn, "Turn on debugging for connections in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); static int iscsi_dbg_lib_session; module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_session, "Turn on debugging for sessions in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); static int iscsi_dbg_lib_eh; module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_eh, "Turn on debugging for error handling in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_conn) \ iscsi_conn_printk(KERN_INFO, _conn, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_session) \ iscsi_session_printk(KERN_INFO, _session, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); #define ISCSI_DBG_EH(_session, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_eh) \ iscsi_session_printk(KERN_INFO, _session, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */ #define SNA32_CHECK 2147483648UL static int iscsi_sna_lt(u32 n1, u32 n2) { return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) || (n1 > n2 && (n2 - n1 < SNA32_CHECK))); } /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */ static int iscsi_sna_lte(u32 n1, u32 n2) { return n1 == n2 || ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) || (n1 > n2 && (n2 - n1 < SNA32_CHECK))); } inline void iscsi_conn_queue_work(struct iscsi_conn *conn) { struct Scsi_Host *shost = conn->session->host; struct iscsi_host *ihost = shost_priv(shost); if (ihost->workq) queue_work(ihost->workq, &conn->xmitwork); } EXPORT_SYMBOL_GPL(iscsi_conn_queue_work); static void __iscsi_update_cmdsn(struct iscsi_session *session, uint32_t exp_cmdsn, uint32_t max_cmdsn) { /* * standard specifies this check for when to update expected and * max sequence numbers */ if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1)) return; if (exp_cmdsn != session->exp_cmdsn && !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn)) session->exp_cmdsn = exp_cmdsn; if (max_cmdsn != session->max_cmdsn && !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) { session->max_cmdsn = max_cmdsn; /* * if the window closed with IO queued, then kick the * xmit thread */ if (!list_empty(&session->leadconn->cmdqueue) || !list_empty(&session->leadconn->mgmtqueue)) iscsi_conn_queue_work(session->leadconn); } } void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr) { __iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn), be32_to_cpu(hdr->max_cmdsn)); } EXPORT_SYMBOL_GPL(iscsi_update_cmdsn); /** * iscsi_prep_data_out_pdu - initialize Data-Out * @task: scsi command task * @r2t: R2T info * @hdr: iscsi data in pdu * * Notes: * Initialize Data-Out within this R2T sequence and finds * proper data_offset within this SCSI command. * * This function is called with connection lock taken. **/ void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t, struct iscsi_data *hdr) { struct iscsi_conn *conn = task->conn; unsigned int left = r2t->data_length - r2t->sent; task->hdr_len = sizeof(struct iscsi_data); memset(hdr, 0, sizeof(struct iscsi_data)); hdr->ttt = r2t->ttt; hdr->datasn = cpu_to_be32(r2t->datasn); r2t->datasn++; hdr->opcode = ISCSI_OP_SCSI_DATA_OUT; memcpy(hdr->lun, task->lun, sizeof(hdr->lun)); hdr->itt = task->hdr_itt; hdr->exp_statsn = r2t->exp_statsn; hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent); if (left > conn->max_xmit_dlength) { hton24(hdr->dlength, conn->max_xmit_dlength); r2t->data_count = conn->max_xmit_dlength; hdr->flags = 0; } else { hton24(hdr->dlength, left); r2t->data_count = left; hdr->flags = ISCSI_FLAG_CMD_FINAL; } conn->dataout_pdus_cnt++; } EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu); static int iscsi_add_hdr(struct iscsi_task *task, unsigned len) { unsigned exp_len = task->hdr_len + len; if (exp_len > task->hdr_max) { WARN_ON(1); return -EINVAL; } WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */ task->hdr_len = exp_len; return 0; } /* * make an extended cdb AHS */ static int iscsi_prep_ecdb_ahs(struct iscsi_task *task) { struct scsi_cmnd *cmd = task->sc; unsigned rlen, pad_len; unsigned short ahslength; struct iscsi_ecdb_ahdr *ecdb_ahdr; int rc; ecdb_ahdr = iscsi_next_hdr(task); rlen = cmd->cmd_len - ISCSI_CDB_SIZE; BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb)); ahslength = rlen + sizeof(ecdb_ahdr->reserved); pad_len = iscsi_padding(rlen); rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) + sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len); if (rc) return rc; if (pad_len) memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len); ecdb_ahdr->ahslength = cpu_to_be16(ahslength); ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB; ecdb_ahdr->reserved = 0; memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen); ISCSI_DBG_SESSION(task->conn->session, "iscsi_prep_ecdb_ahs: varlen_cdb_len %d " "rlen %d pad_len %d ahs_length %d iscsi_headers_size " "%u\n", cmd->cmd_len, rlen, pad_len, ahslength, task->hdr_len); return 0; } static int iscsi_prep_bidi_ahs(struct iscsi_task *task) { struct scsi_cmnd *sc = task->sc; struct iscsi_rlength_ahdr *rlen_ahdr; int rc; rlen_ahdr = iscsi_next_hdr(task); rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr)); if (rc) return rc; rlen_ahdr->ahslength = cpu_to_be16(sizeof(rlen_ahdr->read_length) + sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); ISCSI_DBG_SESSION(task->conn->session, "bidi-in rlen_ahdr->read_length(%d) " "rlen_ahdr->ahslength(%d)\n", be32_to_cpu(rlen_ahdr->read_length), be16_to_cpu(rlen_ahdr->ahslength)); return 0; } /** * iscsi_check_tmf_restrictions - check if a task is affected by TMF * @task: iscsi task * @opcode: opcode to check for * * During TMF a task has to be checked if it's affected. * All unrelated I/O can be passed through, but I/O to the * affected LUN should be restricted. * If 'fast_abort' is set we won't be sending any I/O to the * affected LUN. * Otherwise the target is waiting for all TTTs to be completed, * so we have to send all outstanding Data-Out PDUs to the target. */ static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode) { struct iscsi_conn *conn = task->conn; struct iscsi_tm *tmf = &conn->tmhdr; unsigned int hdr_lun; if (conn->tmf_state == TMF_INITIAL) return 0; if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC) return 0; switch (ISCSI_TM_FUNC_VALUE(tmf)) { case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET: /* * Allow PDUs for unrelated LUNs */ hdr_lun = scsilun_to_int((struct scsi_lun *)tmf->lun); if (hdr_lun != task->sc->device->lun) return 0; /* fall through */ case ISCSI_TM_FUNC_TARGET_WARM_RESET: /* * Fail all SCSI cmd PDUs */ if (opcode != ISCSI_OP_SCSI_DATA_OUT) { iscsi_conn_printk(KERN_INFO, conn, "task [op %x/%x itt " "0x%x/0x%x] " "rejected.\n", task->hdr->opcode, opcode, task->itt, task->hdr_itt); return -EACCES; } /* * And also all data-out PDUs in response to R2T * if fast_abort is set. */ if (conn->session->fast_abort) { iscsi_conn_printk(KERN_INFO, conn, "task [op %x/%x itt " "0x%x/0x%x] fast abort.\n", task->hdr->opcode, opcode, task->itt, task->hdr_itt); return -EACCES; } break; case ISCSI_TM_FUNC_ABORT_TASK: /* * the caller has already checked if the task * they want to abort was in the pending queue so if * we are here the cmd pdu has gone out already, and * we will only hit this for data-outs */ if (opcode == ISCSI_OP_SCSI_DATA_OUT && task->hdr_itt == tmf->rtt) { ISCSI_DBG_SESSION(conn->session, "Preventing task %x/%x from sending " "data-out due to abort task in " "progress\n", task->itt, task->hdr_itt); return -EACCES; } break; } return 0; } /** * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu * @task: iscsi task * * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set * fields like dlength or final based on how much data it sends */ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; struct iscsi_cmd *hdr; unsigned hdrlength, cmd_len; itt_t itt; int rc; rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD); if (rc) return rc; if (conn->session->tt->alloc_pdu) { rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD); if (rc) return rc; } hdr = (struct iscsi_cmd *) task->hdr; itt = hdr->itt; memset(hdr, 0, sizeof(*hdr)); if (session->tt->parse_pdu_itt) hdr->itt = task->hdr_itt = itt; else hdr->itt = task->hdr_itt = build_itt(task->itt, task->conn->session->age); task->hdr_len = 0; rc = iscsi_add_hdr(task, sizeof(*hdr)); if (rc) return rc; hdr->opcode = ISCSI_OP_SCSI_CMD; hdr->flags = ISCSI_ATTR_SIMPLE; int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun); memcpy(task->lun, hdr->lun, sizeof(task->lun)); hdr->exp_statsn = cpu_to_be32(conn->exp_statsn); cmd_len = sc->cmd_len; if (cmd_len < ISCSI_CDB_SIZE) memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len); else if (cmd_len > ISCSI_CDB_SIZE) { rc = iscsi_prep_ecdb_ahs(task); if (rc) return rc; cmd_len = ISCSI_CDB_SIZE; } memcpy(hdr->cdb, sc->cmnd, cmd_len); task->imm_count = 0; if (scsi_bidi_cmnd(sc)) { hdr->flags |= ISCSI_FLAG_CMD_READ; rc = iscsi_prep_bidi_ahs(task); if (rc) return rc; } if (sc->sc_data_direction == DMA_TO_DEVICE) { unsigned out_len = scsi_out(sc)->length; struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->data_length = cpu_to_be32(out_len); hdr->flags |= ISCSI_FLAG_CMD_WRITE; /* * Write counters: * * imm_count bytes to be sent right after * SCSI PDU Header * * unsol_count bytes(as Data-Out) to be sent * without R2T ack right after * immediate data * * r2t data_length bytes to be sent via R2T ack's * * pad_count bytes to be sent as zero-padding */ memset(r2t, 0, sizeof(*r2t)); if (session->imm_data_en) { if (out_len >= session->first_burst) task->imm_count = min(session->first_burst, conn->max_xmit_dlength); else task->imm_count = min(out_len, conn->max_xmit_dlength); hton24(hdr->dlength, task->imm_count); } else zero_data(hdr->dlength); if (!session->initial_r2t_en) { r2t->data_length = min(session->first_burst, out_len) - task->imm_count; r2t->data_offset = task->imm_count; r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG); r2t->exp_statsn = cpu_to_be32(conn->exp_statsn); } if (!task->unsol_r2t.data_length) /* No unsolicit Data-Out's */ hdr->flags |= ISCSI_FLAG_CMD_FINAL; } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); hdr->data_length = cpu_to_be32(scsi_in(sc)->length); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; } /* calculate size of additional header segments (AHSs) */ hdrlength = task->hdr_len - sizeof(*hdr); WARN_ON(hdrlength & (ISCSI_PAD_LEN-1)); hdrlength /= ISCSI_PAD_LEN; WARN_ON(hdrlength >= 256); hdr->hlength = hdrlength & 0xFF; hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn); if (session->tt->init_task && session->tt->init_task(task)) return -EIO; task->state = ISCSI_TASK_RUNNING; session->cmdsn++; conn->scsicmd_pdus_cnt++; ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x " "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n", scsi_bidi_cmnd(sc) ? "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, scsi_bufflen(sc), scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; } /** * iscsi_free_task - free a task * @task: iscsi cmd task * * Must be called with session lock. * This function returns the scsi command to scsi-ml or cleans * up mgmt tasks then returns the task to the pool. */ static void iscsi_free_task(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n", task->itt, task->state, task->sc); session->tt->cleanup_task(task); task->state = ISCSI_TASK_FREE; task->sc = NULL; /* * login task is preallocated so do not free */ if (conn->login_task == task) return; kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { task->sc = NULL; /* SCSI eh reuses commands to verify us */ sc->SCp.ptr = NULL; /* * queue command may call this to free the task, but * not have setup the sc callback */ if (sc->scsi_done) sc->scsi_done(sc); } } void __iscsi_get_task(struct iscsi_task *task) { atomic_inc(&task->refcount); } EXPORT_SYMBOL_GPL(__iscsi_get_task); static void __iscsi_put_task(struct iscsi_task *task) { if (atomic_dec_and_test(&task->refcount)) iscsi_free_task(task); } void iscsi_put_task(struct iscsi_task *task) { struct iscsi_session *session = task->conn->session; spin_lock_bh(&session->lock); __iscsi_put_task(task); spin_unlock_bh(&session->lock); } EXPORT_SYMBOL_GPL(iscsi_put_task); /** * iscsi_complete_task - finish a task * @task: iscsi cmd task * @state: state to complete task with * * Must be called with session lock. */ static void iscsi_complete_task(struct iscsi_task *task, int state) { struct iscsi_conn *conn = task->conn; ISCSI_DBG_SESSION(conn->session, "complete task itt 0x%x state %d sc %p\n", task->itt, task->state, task->sc); if (task->state == ISCSI_TASK_COMPLETED || task->state == ISCSI_TASK_ABRT_TMF || task->state == ISCSI_TASK_ABRT_SESS_RECOV) return; WARN_ON_ONCE(task->state == ISCSI_TASK_FREE); task->state = state; if (!list_empty(&task->running)) list_del_init(&task->running); if (conn->task == task) conn->task = NULL; if (conn->ping_task == task) conn->ping_task = NULL; /* release get from queueing */ __iscsi_put_task(task); } /** * iscsi_complete_scsi_task - finish scsi task normally * @task: iscsi task for scsi cmd * @exp_cmdsn: expected cmd sn in cpu format * @max_cmdsn: max cmd sn in cpu format * * This is used when drivers do not need or cannot perform * lower level pdu processing. * * Called with session lock */ void iscsi_complete_scsi_task(struct iscsi_task *task, uint32_t exp_cmdsn, uint32_t max_cmdsn) { struct iscsi_conn *conn = task->conn; ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt); conn->last_recv = jiffies; __iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task); /* * session lock must be held and if not called for a task that is * still pending or from the xmit thread, then xmit thread must * be suspended. */ static void fail_scsi_task(struct iscsi_task *task, int err) { struct iscsi_conn *conn = task->conn; struct scsi_cmnd *sc; int state; /* * if a command completes and we get a successful tmf response * we will hit this because the scsi eh abort code does not take * a ref to the task. */ sc = task->sc; if (!sc) return; if (task->state == ISCSI_TASK_PENDING) { /* * cmd never made it to the xmit thread, so we should not count * the cmd in the sequencing */ conn->session->queued_cmdsn--; /* it was never sent so just complete like normal */ state = ISCSI_TASK_COMPLETED; } else if (err == DID_TRANSPORT_DISRUPTED) state = ISCSI_TASK_ABRT_SESS_RECOV; else state = ISCSI_TASK_ABRT_TMF; sc->result = err << 16; if (!scsi_bidi_cmnd(sc)) scsi_set_resid(sc, scsi_bufflen(sc)); else { scsi_out(sc)->resid = scsi_out(sc)->length; scsi_in(sc)->resid = scsi_in(sc)->length; } iscsi_complete_task(task, state); } static int iscsi_prep_mgmt_task(struct iscsi_conn *conn, struct iscsi_task *task) { struct iscsi_session *session = conn->session; struct iscsi_hdr *hdr = task->hdr; struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr; uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK; if (conn->session->state == ISCSI_STATE_LOGGING_OUT) return -ENOTCONN; if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT) nop->exp_statsn = cpu_to_be32(conn->exp_statsn); /* * pre-format CmdSN for outgoing PDU. */ nop->cmdsn = cpu_to_be32(session->cmdsn); if (hdr->itt != RESERVED_ITT) { /* * TODO: We always use immediate for normal session pdus. * If we start to send tmfs or nops as non-immediate then * we should start checking the cmdsn numbers for mgmt tasks. * * During discovery sessions iscsid sends TEXT as non immediate, * but we always only send one PDU at a time. */ if (conn->c_stage == ISCSI_CONN_STARTED && !(hdr->opcode & ISCSI_OP_IMMEDIATE)) { session->queued_cmdsn++; session->cmdsn++; } } if (session->tt->init_task && session->tt->init_task(task)) return -EIO; if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT) session->state = ISCSI_STATE_LOGGING_OUT; task->state = ISCSI_TASK_RUNNING; ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x " "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK, hdr->itt, task->data_count); return 0; } static struct iscsi_task * __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size) { struct iscsi_session *session = conn->session; struct iscsi_host *ihost = shost_priv(session->host); uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK; struct iscsi_task *task; itt_t itt; if (session->state == ISCSI_STATE_TERMINATE) return NULL; if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) { /* * Login and Text are sent serially, in * request-followed-by-response sequence. * Same task can be used. Same ITT must be used. * Note that login_task is preallocated at conn_create(). */ if (conn->login_task->state != ISCSI_TASK_FREE) { iscsi_conn_printk(KERN_ERR, conn, "Login/Text in " "progress. Cannot start new task.\n"); return NULL; } task = conn->login_task; } else { if (session->state != ISCSI_STATE_LOGGED_IN) return NULL; BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); if (!kfifo_out(&session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } /* * released in complete pdu for task we expect a response for, and * released by the lld when it has transmitted the task for * pdus we do not expect a response for. */ atomic_set(&task->refcount, 1); task->conn = conn; task->sc = NULL; INIT_LIST_HEAD(&task->running); task->state = ISCSI_TASK_PENDING; if (data_size) { memcpy(task->data, data, data_size); task->data_count = data_size; } else task->data_count = 0; if (conn->session->tt->alloc_pdu) { if (conn->session->tt->alloc_pdu(task, hdr->opcode)) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate " "pdu for mgmt task.\n"); goto free_task; } } itt = task->hdr->itt; task->hdr_len = sizeof(struct iscsi_hdr); memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr)); if (hdr->itt != RESERVED_ITT) { if (session->tt->parse_pdu_itt) task->hdr->itt = itt; else task->hdr->itt = build_itt(task->itt, task->conn->session->age); } if (!ihost->workq) { if (iscsi_prep_mgmt_task(conn, task)) goto free_task; if (session->tt->xmit_task(task)) goto free_task; } else { list_add_tail(&task->running, &conn->mgmtqueue); iscsi_conn_queue_work(conn); } return task; free_task: __iscsi_put_task(task); return NULL; } int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; int err = 0; spin_lock_bh(&session->lock); if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size)) err = -EPERM; spin_unlock_bh(&session->lock); return err; } EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu); /** * iscsi_cmd_rsp - SCSI Command Response processing * @conn: iscsi connection * @hdr: iscsi header * @task: scsi command task * @data: cmd data buffer * @datalen: len of buffer * * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and * then completes the command and task. **/ static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, struct iscsi_task *task, char *data, int datalen) { struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr); conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1; sc->result = (DID_OK << 16) | rhdr->cmd_status; if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) { sc->result = DID_ERROR << 16; goto out; } if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) { uint16_t senselen; if (datalen < 2) { invalid_datalen: iscsi_conn_printk(KERN_ERR, conn, "Got CHECK_CONDITION but invalid data " "buffer size of %d\n", datalen); sc->result = DID_BAD_TARGET << 16; goto out; } senselen = get_unaligned_be16(data); if (datalen < senselen) goto invalid_datalen; memcpy(sc->sense_buffer, data + 2, min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE)); ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n", min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE)); } if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW | ISCSI_FLAG_CMD_BIDI_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->bi_residual_count); if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || res_count <= scsi_in(sc)->length)) scsi_in(sc)->resid = res_count; else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW | ISCSI_FLAG_CMD_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->residual_count); if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || res_count <= scsi_bufflen(sc))) /* write side for bidi or uni-io set_resid */ scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } out: ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n", sc, sc->result, task->itt); conn->scsirsp_pdus_cnt++; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } /** * iscsi_data_in_rsp - SCSI Data-In Response processing * @conn: iscsi connection * @hdr: iscsi pdu * @task: scsi command task **/ static void iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, struct iscsi_task *task) { struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr; struct scsi_cmnd *sc = task->sc; if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS)) return; iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr); sc->result = (DID_OK << 16) | rhdr->cmd_status; conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1; if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW | ISCSI_FLAG_DATA_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->residual_count); if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || res_count <= scsi_in(sc)->length)) scsi_in(sc)->resid = res_count; else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } ISCSI_DBG_SESSION(conn->session, "data in with status done " "[sc %p res %d itt 0x%x]\n", sc, sc->result, task->itt); conn->scsirsp_pdus_cnt++; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr) { struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr; conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; conn->tmfrsp_pdus_cnt++; if (conn->tmf_state != TMF_QUEUED) return; if (tmf->response == ISCSI_TMF_RSP_COMPLETE) conn->tmf_state = TMF_SUCCESS; else if (tmf->response == ISCSI_TMF_RSP_NO_TASK) conn->tmf_state = TMF_NOT_FOUND; else conn->tmf_state = TMF_FAILED; wake_up(&conn->ehwait); } static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr) { struct iscsi_nopout hdr; struct iscsi_task *task; if (!rhdr && conn->ping_task) return; memset(&hdr, 0, sizeof(struct iscsi_nopout)); hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE; hdr.flags = ISCSI_FLAG_CMD_FINAL; if (rhdr) { memcpy(hdr.lun, rhdr->lun, 8); hdr.ttt = rhdr->ttt; hdr.itt = RESERVED_ITT; } else hdr.ttt = RESERVED_ITT; task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0); if (!task) iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n"); else if (!rhdr) { /* only track our nops */ conn->ping_task = task; conn->last_ping = jiffies; } } static int iscsi_nop_out_rsp(struct iscsi_task *task, struct iscsi_nopin *nop, char *data, int datalen) { struct iscsi_conn *conn = task->conn; int rc = 0; if (conn->ping_task != task) { /* * If this is not in response to one of our * nops then it must be from userspace. */ if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; } else mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); return rc; } static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { struct iscsi_reject *reject = (struct iscsi_reject *)hdr; struct iscsi_hdr rejected_pdu; int opcode, rc = 0; conn->exp_statsn = be32_to_cpu(reject->statsn) + 1; if (ntoh24(reject->dlength) > datalen || ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) { iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected " "pdu. Invalid data length (pdu dlength " "%u, datalen %d\n", ntoh24(reject->dlength), datalen); return ISCSI_ERR_PROTO; } memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr)); opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK; switch (reject->reason) { case ISCSI_REASON_DATA_DIGEST_ERROR: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected " "due to DataDigest error.\n", rejected_pdu.itt, opcode); break; case ISCSI_REASON_IMM_CMD_REJECT: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected. Too many " "immediate commands.\n", rejected_pdu.itt, opcode); /* * We only send one TMF at a time so if the target could not * handle it, then it should get fixed (RFC mandates that * a target can handle one immediate TMF per conn). * * For nops-outs, we could have sent more than one if * the target is sending us lots of nop-ins */ if (opcode != ISCSI_OP_NOOP_OUT) return 0; if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG)) /* * nop-out in response to target's nop-out rejected. * Just resend. */ iscsi_send_nopout(conn, (struct iscsi_nopin*)&rejected_pdu); else { struct iscsi_task *task; /* * Our nop as ping got dropped. We know the target * and transport are ok so just clean up */ task = iscsi_itt_to_task(conn, rejected_pdu.itt); if (!task) { iscsi_conn_printk(KERN_ERR, conn, "Invalid pdu reject. Could " "not lookup rejected task.\n"); rc = ISCSI_ERR_BAD_ITT; } else rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)&rejected_pdu, NULL, 0); } break; default: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected. Reason " "code 0x%x\n", rejected_pdu.itt, rejected_pdu.opcode, reject->reason); break; } return rc; } /** * iscsi_itt_to_task - look up task by itt * @conn: iscsi connection * @itt: itt * * This should be used for mgmt tasks like login and nops, or if * the LDD's itt space does not include the session age. * * The session lock must be held. */ struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt) { struct iscsi_session *session = conn->session; int i; if (itt == RESERVED_ITT) return NULL; if (session->tt->parse_pdu_itt) session->tt->parse_pdu_itt(conn, itt, &i, NULL); else i = get_itt(itt); if (i >= session->cmds_max) return NULL; return session->cmds[i]; } EXPORT_SYMBOL_GPL(iscsi_itt_to_task); /** * __iscsi_complete_pdu - complete pdu * @conn: iscsi conn * @hdr: iscsi header * @data: data buffer * @datalen: len of data buffer * * Completes pdu processing by freeing any resources allocated at * queuecommand or send generic. session lock must be held and verify * itt must have been called. */ int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { struct iscsi_session *session = conn->session; int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0; struct iscsi_task *task; uint32_t itt; conn->last_recv = jiffies; rc = iscsi_verify_itt(conn, hdr->itt); if (rc) return rc; if (hdr->itt != RESERVED_ITT) itt = get_itt(hdr->itt); else itt = ~0U; ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n", opcode, conn->id, itt, datalen); if (itt == ~0U) { iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); switch(opcode) { case ISCSI_OP_NOOP_IN: if (datalen) { rc = ISCSI_ERR_PROTO; break; } if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG)) break; iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr); break; case ISCSI_OP_REJECT: rc = iscsi_handle_reject(conn, hdr, data, datalen); break; case ISCSI_OP_ASYNC_EVENT: conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; break; default: rc = ISCSI_ERR_BAD_OPCODE; break; } goto out; } switch(opcode) { case ISCSI_OP_SCSI_CMD_RSP: case ISCSI_OP_SCSI_DATA_IN: task = iscsi_itt_to_ctask(conn, hdr->itt); if (!task) return ISCSI_ERR_BAD_ITT; task->last_xfer = jiffies; break; case ISCSI_OP_R2T: /* * LLD handles R2Ts if they need to. */ return 0; case ISCSI_OP_LOGOUT_RSP: case ISCSI_OP_LOGIN_RSP: case ISCSI_OP_TEXT_RSP: case ISCSI_OP_SCSI_TMFUNC_RSP: case ISCSI_OP_NOOP_IN: task = iscsi_itt_to_task(conn, hdr->itt); if (!task) return ISCSI_ERR_BAD_ITT; break; default: return ISCSI_ERR_BAD_OPCODE; } switch(opcode) { case ISCSI_OP_SCSI_CMD_RSP: iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen); break; case ISCSI_OP_SCSI_DATA_IN: iscsi_data_in_rsp(conn, hdr, task); break; case ISCSI_OP_LOGOUT_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (datalen) { rc = ISCSI_ERR_PROTO; break; } conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; goto recv_pdu; case ISCSI_OP_LOGIN_RSP: case ISCSI_OP_TEXT_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); /* * login related PDU's exp_statsn is handled in * userspace */ goto recv_pdu; case ISCSI_OP_SCSI_TMFUNC_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (datalen) { rc = ISCSI_ERR_PROTO; break; } iscsi_tmf_rsp(conn, hdr); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); break; case ISCSI_OP_NOOP_IN: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) { rc = ISCSI_ERR_PROTO; break; } conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr, data, datalen); break; default: rc = ISCSI_ERR_BAD_OPCODE; break; } out: return rc; recv_pdu: if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); return rc; } EXPORT_SYMBOL_GPL(__iscsi_complete_pdu); int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { int rc; spin_lock(&conn->session->lock); rc = __iscsi_complete_pdu(conn, hdr, data, datalen); spin_unlock(&conn->session->lock); return rc; } EXPORT_SYMBOL_GPL(iscsi_complete_pdu); int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt) { struct iscsi_session *session = conn->session; int age = 0, i = 0; if (itt == RESERVED_ITT) return 0; if (session->tt->parse_pdu_itt) session->tt->parse_pdu_itt(conn, itt, &i, &age); else { i = get_itt(itt); age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK; } if (age != session->age) { iscsi_conn_printk(KERN_ERR, conn, "received itt %x expected session age (%x)\n", (__force u32)itt, session->age); return ISCSI_ERR_BAD_ITT; } if (i >= session->cmds_max) { iscsi_conn_printk(KERN_ERR, conn, "received invalid itt index %u (max cmds " "%u.\n", i, session->cmds_max); return ISCSI_ERR_BAD_ITT; } return 0; } EXPORT_SYMBOL_GPL(iscsi_verify_itt); /** * iscsi_itt_to_ctask - look up ctask by itt * @conn: iscsi connection * @itt: itt * * This should be used for cmd tasks. * * The session lock must be held. */ struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt) { struct iscsi_task *task; if (iscsi_verify_itt(conn, itt)) return NULL; task = iscsi_itt_to_task(conn, itt); if (!task || !task->sc) return NULL; if (task->sc->SCp.phase != conn->session->age) { iscsi_session_printk(KERN_ERR, conn->session, "task's session age %d, expected %d\n", task->sc->SCp.phase, conn->session->age); return NULL; } return task; } EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask); void iscsi_session_failure(struct iscsi_session *session, enum iscsi_err err) { struct iscsi_conn *conn; struct device *dev; unsigned long flags; spin_lock_irqsave(&session->lock, flags); conn = session->leadconn; if (session->state == ISCSI_STATE_TERMINATE || !conn) { spin_unlock_irqrestore(&session->lock, flags); return; } dev = get_device(&conn->cls_conn->dev); spin_unlock_irqrestore(&session->lock, flags); if (!dev) return; /* * if the host is being removed bypass the connection * recovery initialization because we are going to kill * the session. */ if (err == ISCSI_ERR_INVALID_HOST) iscsi_conn_error_event(conn->cls_conn, err); else iscsi_conn_failure(conn, err); put_device(dev); } EXPORT_SYMBOL_GPL(iscsi_session_failure); void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err) { struct iscsi_session *session = conn->session; unsigned long flags; spin_lock_irqsave(&session->lock, flags); if (session->state == ISCSI_STATE_FAILED) { spin_unlock_irqrestore(&session->lock, flags); return; } if (conn->stop_stage == 0) session->state = ISCSI_STATE_FAILED; spin_unlock_irqrestore(&session->lock, flags); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx); iscsi_conn_error_event(conn->cls_conn, err); } EXPORT_SYMBOL_GPL(iscsi_conn_failure); static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; /* * Check for iSCSI window and take care of CmdSN wrap-around */ if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) { ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn " "%u MaxCmdSN %u CmdSN %u/%u\n", session->exp_cmdsn, session->max_cmdsn, session->cmdsn, session->queued_cmdsn); return -ENOSPC; } return 0; } static int iscsi_xmit_task(struct iscsi_conn *conn) { struct iscsi_task *task = conn->task; int rc; if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) return -ENODATA; __iscsi_get_task(task); spin_unlock_bh(&conn->session->lock); rc = conn->session->tt->xmit_task(task); spin_lock_bh(&conn->session->lock); if (!rc) { /* done with this task */ task->last_xfer = jiffies; conn->task = NULL; } __iscsi_put_task(task); return rc; } /** * iscsi_requeue_task - requeue task to run from session workqueue * @task: task to requeue * * LLDs that need to run a task from the session workqueue should call * this. The session lock must be held. This should only be called * by software drivers. */ void iscsi_requeue_task(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; /* * this may be on the requeue list already if the xmit_task callout * is handling the r2ts while we are adding new ones */ if (list_empty(&task->running)) list_add_tail(&task->running, &conn->requeue); iscsi_conn_queue_work(conn); } EXPORT_SYMBOL_GPL(iscsi_requeue_task); /** * iscsi_data_xmit - xmit any command into the scheduled connection * @conn: iscsi connection * * Notes: * The function can return -EAGAIN in which case the caller must * re-schedule it again later or recover. '0' return code means * successful xmit. **/ static int iscsi_data_xmit(struct iscsi_conn *conn) { struct iscsi_task *task; int rc = 0; spin_lock_bh(&conn->session->lock); if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) { ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n"); spin_unlock_bh(&conn->session->lock); return -ENODATA; } if (conn->task) { rc = iscsi_xmit_task(conn); if (rc) goto done; } /* * process mgmt pdus like nops before commands since we should * only have one nop-out as a ping from us and targets should not * overflow us with nop-ins */ check_mgmt: while (!list_empty(&conn->mgmtqueue)) { conn->task = list_entry(conn->mgmtqueue.next, struct iscsi_task, running); list_del_init(&conn->task->running); if (iscsi_prep_mgmt_task(conn, conn->task)) { __iscsi_put_task(conn->task); conn->task = NULL; continue; } rc = iscsi_xmit_task(conn); if (rc) goto done; } /* process pending command queue */ while (!list_empty(&conn->cmdqueue)) { conn->task = list_entry(conn->cmdqueue.next, struct iscsi_task, running); list_del_init(&conn->task->running); if (conn->session->state == ISCSI_STATE_LOGGING_OUT) { fail_scsi_task(conn->task, DID_IMM_RETRY); continue; } rc = iscsi_prep_scsi_cmd_pdu(conn->task); if (rc) { if (rc == -ENOMEM || rc == -EACCES) { list_add_tail(&conn->task->running, &conn->cmdqueue); conn->task = NULL; goto done; } else fail_scsi_task(conn->task, DID_ABORT); continue; } rc = iscsi_xmit_task(conn); if (rc) goto done; /* * we could continuously get new task requests so * we need to check the mgmt queue for nops that need to * be sent to aviod starvation */ if (!list_empty(&conn->mgmtqueue)) goto check_mgmt; } while (!list_empty(&conn->requeue)) { /* * we always do fastlogout - conn stop code will clean up. */ if (conn->session->state == ISCSI_STATE_LOGGING_OUT) break; task = list_entry(conn->requeue.next, struct iscsi_task, running); if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT)) break; conn->task = task; list_del_init(&conn->task->running); conn->task->state = ISCSI_TASK_RUNNING; rc = iscsi_xmit_task(conn); if (rc) goto done; if (!list_empty(&conn->mgmtqueue)) goto check_mgmt; } spin_unlock_bh(&conn->session->lock); return -ENODATA; done: spin_unlock_bh(&conn->session->lock); return rc; } static void iscsi_xmitworker(struct work_struct *work) { struct iscsi_conn *conn = container_of(work, struct iscsi_conn, xmitwork); int rc; /* * serialize Xmit worker on a per-connection basis. */ do { rc = iscsi_data_xmit(conn); } while (rc >= 0 || rc == -EAGAIN); } static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, struct scsi_cmnd *sc) { struct iscsi_task *task; if (!kfifo_out(&conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; sc->SCp.phase = conn->session->age; sc->SCp.ptr = (char *) task; atomic_set(&task->refcount, 1); task->state = ISCSI_TASK_PENDING; task->conn = conn; task->sc = sc; task->have_checked_conn = 0; task->last_timeout = jiffies; task->last_xfer = jiffies; INIT_LIST_HEAD(&task->running); return task; } enum { FAILURE_BAD_HOST = 1, FAILURE_SESSION_FAILED, FAILURE_SESSION_FREED, FAILURE_WINDOW_CLOSED, FAILURE_OOM, FAILURE_SESSION_TERMINATE, FAILURE_SESSION_IN_RECOVERY, FAILURE_SESSION_RECOVERY_TIMEOUT, FAILURE_SESSION_LOGGING_OUT, FAILURE_SESSION_NOT_READY, }; int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *)) { struct iscsi_cls_session *cls_session; struct Scsi_Host *host; struct iscsi_host *ihost; int reason = 0; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_task *task = NULL; sc->scsi_done = done; sc->result = 0; sc->SCp.ptr = NULL; host = sc->device->host; ihost = shost_priv(host); spin_unlock(host->host_lock); cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; spin_lock(&session->lock); reason = iscsi_session_chkready(cls_session); if (reason) { sc->result = reason; goto fault; } if (session->state != ISCSI_STATE_LOGGED_IN) { /* * to handle the race between when we set the recovery state * and block the session we requeue here (commands could * be entering our queuecommand while a block is starting * up because the block code is not locked) */ switch (session->state) { case ISCSI_STATE_FAILED: case ISCSI_STATE_IN_RECOVERY: reason = FAILURE_SESSION_IN_RECOVERY; sc->result = DID_IMM_RETRY << 16; break; case ISCSI_STATE_LOGGING_OUT: reason = FAILURE_SESSION_LOGGING_OUT; sc->result = DID_IMM_RETRY << 16; break; case ISCSI_STATE_RECOVERY_FAILED: reason = FAILURE_SESSION_RECOVERY_TIMEOUT; sc->result = DID_TRANSPORT_FAILFAST << 16; break; case ISCSI_STATE_TERMINATE: reason = FAILURE_SESSION_TERMINATE; sc->result = DID_NO_CONNECT << 16; break; default: reason = FAILURE_SESSION_FREED; sc->result = DID_NO_CONNECT << 16; } goto fault; } conn = session->leadconn; if (!conn) { reason = FAILURE_SESSION_FREED; sc->result = DID_NO_CONNECT << 16; goto fault; } if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) { reason = FAILURE_SESSION_IN_RECOVERY; sc->result = DID_REQUEUE; goto fault; } if (iscsi_check_cmdsn_window_closed(conn)) { reason = FAILURE_WINDOW_CLOSED; goto reject; } task = iscsi_alloc_task(conn, sc); if (!task) { reason = FAILURE_OOM; goto reject; } if (!ihost->workq) { reason = iscsi_prep_scsi_cmd_pdu(task); if (reason) { if (reason == -ENOMEM || reason == -EACCES) { reason = FAILURE_OOM; goto prepd_reject; } else { sc->result = DID_ABORT << 16; goto prepd_fault; } } if (session->tt->xmit_task(task)) { session->cmdsn--; reason = FAILURE_SESSION_NOT_READY; goto prepd_reject; } } else { list_add_tail(&task->running, &conn->cmdqueue); iscsi_conn_queue_work(conn); } session->queued_cmdsn++; spin_unlock(&session->lock); spin_lock(host->host_lock); return 0; prepd_reject: sc->scsi_done = NULL; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); reject: spin_unlock(&session->lock); ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason); spin_lock(host->host_lock); return SCSI_MLQUEUE_TARGET_BUSY; prepd_fault: sc->scsi_done = NULL; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); fault: spin_unlock(&session->lock); ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); if (!scsi_bidi_cmnd(sc)) scsi_set_resid(sc, scsi_bufflen(sc)); else { scsi_out(sc)->resid = scsi_out(sc)->length; scsi_in(sc)->resid = scsi_in(sc)->length; } done(sc); spin_lock(host->host_lock); return 0; } EXPORT_SYMBOL_GPL(iscsi_queuecommand); int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason) { switch (reason) { case SCSI_QDEPTH_DEFAULT: scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); break; case SCSI_QDEPTH_QFULL: scsi_track_queue_full(sdev, depth); break; case SCSI_QDEPTH_RAMP_UP: scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth); break; default: return -EOPNOTSUPP; } return sdev->queue_depth; } EXPORT_SYMBOL_GPL(iscsi_change_queue_depth); int iscsi_target_alloc(struct scsi_target *starget) { struct iscsi_cls_session *cls_session = starget_to_session(starget); struct iscsi_session *session = cls_session->dd_data; #if 0 starget->can_queue = session->scsi_cmds_max; #endif return 0; } EXPORT_SYMBOL_GPL(iscsi_target_alloc); static void iscsi_tmf_timedout(unsigned long data) { struct iscsi_conn *conn = (struct iscsi_conn *)data; struct iscsi_session *session = conn->session; spin_lock(&session->lock); if (conn->tmf_state == TMF_QUEUED) { conn->tmf_state = TMF_TIMEDOUT; ISCSI_DBG_EH(session, "tmf timedout\n"); /* unblock eh_abort() */ wake_up(&conn->ehwait); } spin_unlock(&session->lock); } static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn, struct iscsi_tm *hdr, int age, int timeout) { struct iscsi_session *session = conn->session; struct iscsi_task *task; task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr, NULL, 0); if (!task) { spin_unlock_bh(&session->lock); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); spin_lock_bh(&session->lock); ISCSI_DBG_EH(session, "tmf exec failure\n"); return -EPERM; } conn->tmfcmd_pdus_cnt++; conn->tmf_timer.expires = timeout * HZ + jiffies; conn->tmf_timer.function = iscsi_tmf_timedout; conn->tmf_timer.data = (unsigned long)conn; add_timer(&conn->tmf_timer); ISCSI_DBG_EH(session, "tmf set timeout\n"); spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); /* * block eh thread until: * * 1) tmf response * 2) tmf timeout * 3) session is terminated or restarted or userspace has * given up on recovery */ wait_event_interruptible(conn->ehwait, age != session->age || session->state != ISCSI_STATE_LOGGED_IN || conn->tmf_state != TMF_QUEUED); if (signal_pending(current)) flush_signals(current); del_timer_sync(&conn->tmf_timer); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); /* if the session drops it will clean up the task */ if (age != session->age || session->state != ISCSI_STATE_LOGGED_IN) return -ENOTCONN; return 0; } /* * Fail commands. session lock held and recv side suspended and xmit * thread flushed */ static void fail_scsi_tasks(struct iscsi_conn *conn, unsigned lun, int error) { struct iscsi_task *task; int i; for (i = 0; i < conn->session->cmds_max; i++) { task = conn->session->cmds[i]; if (!task->sc || task->state == ISCSI_TASK_FREE) continue; if (lun != -1 && lun != task->sc->device->lun) continue; ISCSI_DBG_SESSION(conn->session, "failing sc %p itt 0x%x state %d\n", task->sc, task->itt, task->state); fail_scsi_task(task, error); } } /** * iscsi_suspend_queue - suspend iscsi_queuecommand * @conn: iscsi conn to stop queueing IO on * * This grabs the session lock to make sure no one is in * xmit_task/queuecommand, and then sets suspend to prevent * new commands from being queued. This only needs to be called * by offload drivers that need to sync a path like ep disconnect * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi * will call iscsi_start_tx and iscsi_unblock_session when in FFP. */ void iscsi_suspend_queue(struct iscsi_conn *conn) { spin_lock_bh(&conn->session->lock); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); spin_unlock_bh(&conn->session->lock); } EXPORT_SYMBOL_GPL(iscsi_suspend_queue); /** * iscsi_suspend_tx - suspend iscsi_data_xmit * @conn: iscsi conn tp stop processing IO on. * * This function sets the suspend bit to prevent iscsi_data_xmit * from sending new IO, and if work is queued on the xmit thread * it will wait for it to be completed. */ void iscsi_suspend_tx(struct iscsi_conn *conn) { struct Scsi_Host *shost = conn->session->host; struct iscsi_host *ihost = shost_priv(shost); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); if (ihost->workq) flush_workqueue(ihost->workq); } EXPORT_SYMBOL_GPL(iscsi_suspend_tx); static void iscsi_start_tx(struct iscsi_conn *conn) { clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); iscsi_conn_queue_work(conn); } /* * We want to make sure a ping is in flight. It has timed out. * And we are not busy processing a pdu that is making * progress but got started before the ping and is taking a while * to complete so the ping is just stuck behind it in a queue. */ static int iscsi_has_ping_timed_out(struct iscsi_conn *conn) { if (conn->ping_task && time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) + (conn->ping_timeout * HZ), jiffies)) return 1; else return 0; } static enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc) { enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED; struct iscsi_task *task = NULL, *running_task; struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; int i; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc); spin_lock(&session->lock); if (session->state != ISCSI_STATE_LOGGED_IN) { /* * We are probably in the middle of iscsi recovery so let * that complete and handle the error. */ rc = BLK_EH_RESET_TIMER; goto done; } conn = session->leadconn; if (!conn) { /* In the middle of shuting down */ rc = BLK_EH_RESET_TIMER; goto done; } task = (struct iscsi_task *)sc->SCp.ptr; if (!task) { /* * Raced with completion. Just reset timer, and let it * complete normally */ rc = BLK_EH_RESET_TIMER; goto done; } /* * If we have sent (at least queued to the network layer) a pdu or * recvd one for the task since the last timeout ask for * more time. If on the next timeout we have not made progress * we can check if it is the task or connection when we send the * nop as a ping. */ if (time_after(task->last_xfer, task->last_timeout)) { ISCSI_DBG_EH(session, "Command making progress. Asking " "scsi-ml for more time to complete. " "Last data xfer at %lu. Last timeout was at " "%lu\n.", task->last_xfer, task->last_timeout); task->have_checked_conn = 0; rc = BLK_EH_RESET_TIMER; goto done; } if (!conn->recv_timeout && !conn->ping_timeout) goto done; /* * if the ping timedout then we are in the middle of cleaning up * and can let the iscsi eh handle it */ if (iscsi_has_ping_timed_out(conn)) { rc = BLK_EH_RESET_TIMER; goto done; } for (i = 0; i < conn->session->cmds_max; i++) { running_task = conn->session->cmds[i]; if (!running_task->sc || running_task == task || running_task->state != ISCSI_TASK_RUNNING) continue; /* * Only check if cmds started before this one have made * progress, or this could never fail */ if (time_after(running_task->sc->jiffies_at_alloc, task->sc->jiffies_at_alloc)) continue; if (time_after(running_task->last_xfer, task->last_timeout)) { /* * This task has not made progress, but a task * started before us has transferred data since * we started/last-checked. We could be queueing * too many tasks or the LU is bad. * * If the device is bad the cmds ahead of us on * other devs will complete, and this loop will * eventually fail starting the scsi eh. */ ISCSI_DBG_EH(session, "Command has not made progress " "but commands ahead of it have. " "Asking scsi-ml for more time to " "complete. Our last xfer vs running task " "last xfer %lu/%lu. Last check %lu.\n", task->last_xfer, running_task->last_xfer, task->last_timeout); rc = BLK_EH_RESET_TIMER; goto done; } } /* Assumes nop timeout is shorter than scsi cmd timeout */ if (task->have_checked_conn) goto done; /* * Checking the transport already or nop from a cmd timeout still * running */ if (conn->ping_task) { task->have_checked_conn = 1; rc = BLK_EH_RESET_TIMER; goto done; } /* Make sure there is a transport check done */ iscsi_send_nopout(conn, NULL); task->have_checked_conn = 1; rc = BLK_EH_RESET_TIMER; done: if (task) task->last_timeout = jiffies; spin_unlock(&session->lock); ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ? "timer reset" : "nh"); return rc; } static void iscsi_check_transport_timeouts(unsigned long data) { struct iscsi_conn *conn = (struct iscsi_conn *)data; struct iscsi_session *session = conn->session; unsigned long recv_timeout, next_timeout = 0, last_recv; spin_lock(&session->lock); if (session->state != ISCSI_STATE_LOGGED_IN) goto done; recv_timeout = conn->recv_timeout; if (!recv_timeout) goto done; recv_timeout *= HZ; last_recv = conn->last_recv; if (iscsi_has_ping_timed_out(conn)) { iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs " "expired, recv timeout %d, last rx %lu, " "last ping %lu, now %lu\n", conn->ping_timeout, conn->recv_timeout, last_recv, conn->last_ping, jiffies); spin_unlock(&session->lock); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); return; } if (time_before_eq(last_recv + recv_timeout, jiffies)) { /* send a ping to try to provoke some traffic */ ISCSI_DBG_CONN(conn, "Sending nopout as ping\n"); iscsi_send_nopout(conn, NULL); next_timeout = conn->last_ping + (conn->ping_timeout * HZ); } else next_timeout = last_recv + recv_timeout; ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout); mod_timer(&conn->transport_timer, next_timeout); done: spin_unlock(&session->lock); } static void iscsi_prep_abort_task_pdu(struct iscsi_task *task, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; memcpy(hdr->lun, task->lun, sizeof(hdr->lun)); hdr->rtt = task->hdr_itt; hdr->refcmdsn = task->cmdsn; } int iscsi_eh_abort(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_task *task; struct iscsi_tm *hdr; int rc, age; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "aborting sc %p\n", sc); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); /* * if session was ISCSI_STATE_IN_RECOVERY then we may not have * got the command. */ if (!sc->SCp.ptr) { ISCSI_DBG_EH(session, "sc never reached iscsi layer or " "it completed.\n"); spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); return SUCCESS; } /* * If we are not logged in or we have started a new session * then let the host reset code handle this */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN || sc->SCp.phase != session->age) { spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); ISCSI_DBG_EH(session, "failing abort due to dropped " "session.\n"); return FAILED; } conn = session->leadconn; conn->eh_abort_cnt++; age = session->age; task = (struct iscsi_task *)sc->SCp.ptr; ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n", sc, task->itt); /* task completed before time out */ if (!task->sc) { ISCSI_DBG_EH(session, "sc completed while abort in progress\n"); goto success; } if (task->state == ISCSI_TASK_PENDING) { fail_scsi_task(task, DID_ABORT); goto success; } /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto failed; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_abort_task_pdu(task, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) { rc = FAILED; goto failed; } switch (conn->tmf_state) { case TMF_SUCCESS: spin_unlock_bh(&session->lock); /* * stop tx side incase the target had sent a abort rsp but * the initiator was still writing out data. */ iscsi_suspend_tx(conn); /* * we do not stop the recv side because targets have been * good and have never sent us a successful tmf response * then sent more data for the cmd. */ spin_lock_bh(&session->lock); fail_scsi_task(task, DID_ABORT); conn->tmf_state = TMF_INITIAL; memset(hdr, 0, sizeof(*hdr)); spin_unlock_bh(&session->lock); iscsi_start_tx(conn); goto success_unlocked; case TMF_TIMEDOUT: spin_unlock_bh(&session->lock); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); goto failed_unlocked; case TMF_NOT_FOUND: if (!sc->SCp.ptr) { conn->tmf_state = TMF_INITIAL; memset(hdr, 0, sizeof(*hdr)); /* task completed before tmf abort response */ ISCSI_DBG_EH(session, "sc completed while abort in " "progress\n"); goto success; } /* fall through */ default: conn->tmf_state = TMF_INITIAL; goto failed; } success: spin_unlock_bh(&session->lock); success_unlocked: ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n", sc, task->itt); mutex_unlock(&session->eh_mutex); return SUCCESS; failed: spin_unlock_bh(&session->lock); failed_unlocked: ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc, task ? task->itt : 0); mutex_unlock(&session->eh_mutex); return FAILED; } EXPORT_SYMBOL_GPL(iscsi_eh_abort); static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun); hdr->rtt = RESERVED_ITT; } int iscsi_eh_device_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_tm *hdr; int rc = FAILED; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "LU Reset [sc %p lun %u]\n", sc, sc->device->lun); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); /* * Just check if we are not logged in. We cannot check for * the phase because the reset could come from a ioctl. */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN) goto unlock; conn = session->leadconn; /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto unlock; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_lun_reset_pdu(sc, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age, session->lu_reset_timeout)) { rc = FAILED; goto unlock; } switch (conn->tmf_state) { case TMF_SUCCESS: break; case TMF_TIMEDOUT: spin_unlock_bh(&session->lock); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); goto done; default: conn->tmf_state = TMF_INITIAL; goto unlock; } rc = SUCCESS; spin_unlock_bh(&session->lock); iscsi_suspend_tx(conn); spin_lock_bh(&session->lock); memset(hdr, 0, sizeof(*hdr)); fail_scsi_tasks(conn, sc->device->lun, DID_ERROR); conn->tmf_state = TMF_INITIAL; spin_unlock_bh(&session->lock); iscsi_start_tx(conn); goto done; unlock: spin_unlock_bh(&session->lock); done: ISCSI_DBG_EH(session, "dev reset result = %s\n", rc == SUCCESS ? "SUCCESS" : "FAILED"); mutex_unlock(&session->eh_mutex); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_device_reset); void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session) { struct iscsi_session *session = cls_session->dd_data; spin_lock_bh(&session->lock); if (session->state != ISCSI_STATE_LOGGED_IN) { session->state = ISCSI_STATE_RECOVERY_FAILED; if (session->leadconn) wake_up(&session->leadconn->ehwait); } spin_unlock_bh(&session->lock); } EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout); /** * iscsi_eh_session_reset - drop session and attempt relogin * @sc: scsi command * * This function will wait for a relogin, session termination from * userspace, or a recovery/replacement timeout. */ int iscsi_eh_session_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; conn = session->leadconn; mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); if (session->state == ISCSI_STATE_TERMINATE) { failed: ISCSI_DBG_EH(session, "failing session reset: Could not log back into " "%s, %s [age %d]\n", session->targetname, conn->persistent_address, session->age); spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); return FAILED; } spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); /* * we drop the lock here but the leadconn cannot be destoyed while * we are in the scsi eh */ iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); ISCSI_DBG_EH(session, "wait for relogin\n"); wait_event_interruptible(conn->ehwait, session->state == ISCSI_STATE_TERMINATE || session->state == ISCSI_STATE_LOGGED_IN || session->state == ISCSI_STATE_RECOVERY_FAILED); if (signal_pending(current)) flush_signals(current); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); if (session->state == ISCSI_STATE_LOGGED_IN) { ISCSI_DBG_EH(session, "session reset succeeded for %s,%s\n", session->targetname, conn->persistent_address); } else goto failed; spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); return SUCCESS; } EXPORT_SYMBOL_GPL(iscsi_eh_session_reset); static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; hdr->rtt = RESERVED_ITT; } /** * iscsi_eh_target_reset - reset target * @sc: scsi command * * This will attempt to send a warm target reset. */ int iscsi_eh_target_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_tm *hdr; int rc = FAILED; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc, session->targetname); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); /* * Just check if we are not logged in. We cannot check for * the phase because the reset could come from a ioctl. */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN) goto unlock; conn = session->leadconn; /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto unlock; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_tgt_reset_pdu(sc, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age, session->tgt_reset_timeout)) { rc = FAILED; goto unlock; } switch (conn->tmf_state) { case TMF_SUCCESS: break; case TMF_TIMEDOUT: spin_unlock_bh(&session->lock); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); goto done; default: conn->tmf_state = TMF_INITIAL; goto unlock; } rc = SUCCESS; spin_unlock_bh(&session->lock); iscsi_suspend_tx(conn); spin_lock_bh(&session->lock); memset(hdr, 0, sizeof(*hdr)); fail_scsi_tasks(conn, -1, DID_ERROR); conn->tmf_state = TMF_INITIAL; spin_unlock_bh(&session->lock); iscsi_start_tx(conn); goto done; unlock: spin_unlock_bh(&session->lock); done: ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname, rc == SUCCESS ? "SUCCESS" : "FAILED"); mutex_unlock(&session->eh_mutex); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_target_reset); /** * iscsi_eh_recover_target - reset target and possibly the session * @sc: scsi command * * This will attempt to send a warm target reset. If that fails, * we will escalate to ERL0 session recovery. */ int iscsi_eh_recover_target(struct scsi_cmnd *sc) { int rc; rc = iscsi_eh_target_reset(sc); if (rc == FAILED) rc = iscsi_eh_session_reset(sc); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_recover_target); /* * Pre-allocate a pool of @max items of @item_size. By default, the pool * should be accessed via kfifo_{get,put} on q->queue. * Optionally, the caller can obtain the array of object pointers * by passing in a non-NULL @items pointer */ int iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) { int i, num_arrays = 1; memset(q, 0, sizeof(*q)); q->max = max; /* If the user passed an items pointer, he wants a copy of * the array. */ if (items) num_arrays++; q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL); if (q->pool == NULL) return -ENOMEM; kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); if (q->pool[i] == NULL) { q->max = i; goto enomem; } kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { *items = q->pool + max; memcpy(*items, q->pool, max * sizeof(void *)); } return 0; enomem: iscsi_pool_free(q); return -ENOMEM; } EXPORT_SYMBOL_GPL(iscsi_pool_init); void iscsi_pool_free(struct iscsi_pool *q) { int i; for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); } EXPORT_SYMBOL_GPL(iscsi_pool_free); /** * iscsi_host_add - add host to system * @shost: scsi host * @pdev: parent device * * This should be called by partial offload and software iscsi drivers * to add a host to the system. */ int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev) { if (!shost->can_queue) shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX; if (!shost->cmd_per_lun) shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN; if (!shost->transportt->eh_timed_out) shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out; return scsi_add_host(shost, pdev); } EXPORT_SYMBOL_GPL(iscsi_host_add); /** * iscsi_host_alloc - allocate a host and driver data * @sht: scsi host template * @dd_data_size: driver host data size * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue * * This should be called by partial offload and software iscsi drivers. * To access the driver specific memory use the iscsi_host_priv() macro. */ struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht, int dd_data_size, bool xmit_can_sleep) { struct Scsi_Host *shost; struct iscsi_host *ihost; shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size); if (!shost) return NULL; ihost = shost_priv(shost); if (xmit_can_sleep) { snprintf(ihost->workq_name, sizeof(ihost->workq_name), "iscsi_q_%d", shost->host_no); ihost->workq = create_singlethread_workqueue(ihost->workq_name); if (!ihost->workq) goto free_host; } spin_lock_init(&ihost->lock); ihost->state = ISCSI_HOST_SETUP; ihost->num_sessions = 0; init_waitqueue_head(&ihost->session_removal_wq); return shost; free_host: scsi_host_put(shost); return NULL; } EXPORT_SYMBOL_GPL(iscsi_host_alloc); static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session) { iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST); } /** * iscsi_host_remove - remove host and sessions * @shost: scsi host * * If there are any sessions left, this will initiate the removal and wait * for the completion. */ void iscsi_host_remove(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); unsigned long flags; spin_lock_irqsave(&ihost->lock, flags); ihost->state = ISCSI_HOST_REMOVED; spin_unlock_irqrestore(&ihost->lock, flags); iscsi_host_for_each_session(shost, iscsi_notify_host_removed); wait_event_interruptible(ihost->session_removal_wq, ihost->num_sessions == 0); if (signal_pending(current)) flush_signals(current); scsi_remove_host(shost); if (ihost->workq) destroy_workqueue(ihost->workq); } EXPORT_SYMBOL_GPL(iscsi_host_remove); void iscsi_host_free(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); kfree(ihost->netdev); kfree(ihost->hwaddress); kfree(ihost->initiatorname); scsi_host_put(shost); } EXPORT_SYMBOL_GPL(iscsi_host_free); static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); unsigned long flags; shost = scsi_host_get(shost); if (!shost) { printk(KERN_ERR "Invalid state. Cannot notify host removal " "of session teardown event because host already " "removed.\n"); return; } spin_lock_irqsave(&ihost->lock, flags); ihost->num_sessions--; if (ihost->num_sessions == 0) wake_up(&ihost->session_removal_wq); spin_unlock_irqrestore(&ihost->lock, flags); scsi_host_put(shost); } /** * iscsi_session_setup - create iscsi cls session and host and session * @iscsit: iscsi transport template * @shost: scsi host * @cmds_max: session can queue * @cmd_task_size: LLD task private data size * @initial_cmdsn: initial CmdSN * * This can be used by software iscsi_transports that allocate * a session per scsi host. * * Callers should set cmds_max to the largest total numer (mgmt + scsi) of * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks * for nop handling and login/logout requests. */ struct iscsi_cls_session * iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost, uint16_t cmds_max, int dd_size, int cmd_task_size, uint32_t initial_cmdsn, unsigned int id) { struct iscsi_host *ihost = shost_priv(shost); struct iscsi_session *session; struct iscsi_cls_session *cls_session; int cmd_i, scsi_cmds, total_cmds = cmds_max; unsigned long flags; spin_lock_irqsave(&ihost->lock, flags); if (ihost->state == ISCSI_HOST_REMOVED) { spin_unlock_irqrestore(&ihost->lock, flags); return NULL; } ihost->num_sessions++; spin_unlock_irqrestore(&ihost->lock, flags); if (!total_cmds) total_cmds = ISCSI_DEF_XMIT_CMDS_MAX; /* * The iscsi layer needs some tasks for nop handling and tmfs, * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX * + 1 command for scsi IO. */ if (total_cmds < ISCSI_TOTAL_CMDS_MIN) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of two that is at least %d.\n", total_cmds, ISCSI_TOTAL_CMDS_MIN); goto dec_session_count; } if (total_cmds > ISCSI_TOTAL_CMDS_MAX) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of 2 less than or equal to %d.\n", cmds_max, ISCSI_TOTAL_CMDS_MAX); total_cmds = ISCSI_TOTAL_CMDS_MAX; } if (!is_power_of_2(total_cmds)) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of 2.\n", total_cmds); total_cmds = rounddown_pow_of_two(total_cmds); if (total_cmds < ISCSI_TOTAL_CMDS_MIN) return NULL; printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n", total_cmds); } scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX; cls_session = iscsi_alloc_session(shost, iscsit, sizeof(struct iscsi_session) + dd_size); if (!cls_session) goto dec_session_count; session = cls_session->dd_data; session->cls_session = cls_session; session->host = shost; session->state = ISCSI_STATE_FREE; session->fast_abort = 1; session->tgt_reset_timeout = 30; session->lu_reset_timeout = 15; session->abort_timeout = 10; session->scsi_cmds_max = scsi_cmds; session->cmds_max = total_cmds; session->queued_cmdsn = session->cmdsn = initial_cmdsn; session->exp_cmdsn = initial_cmdsn + 1; session->max_cmdsn = initial_cmdsn + 1; session->max_r2t = 1; session->tt = iscsit; session->dd_data = cls_session->dd_data + sizeof(*session); mutex_init(&session->eh_mutex); spin_lock_init(&session->lock); /* initialize SCSI PDU commands pool */ if (iscsi_pool_init(&session->cmdpool, session->cmds_max, (void***)&session->cmds, cmd_task_size + sizeof(struct iscsi_task))) goto cmdpool_alloc_fail; /* pre-format cmds pool with ITT */ for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) { struct iscsi_task *task = session->cmds[cmd_i]; if (cmd_task_size) task->dd_data = &task[1]; task->itt = cmd_i; task->state = ISCSI_TASK_FREE; INIT_LIST_HEAD(&task->running); } if (!try_module_get(iscsit->owner)) goto module_get_fail; if (iscsi_add_session(cls_session, id)) goto cls_session_fail; return cls_session; cls_session_fail: module_put(iscsit->owner); module_get_fail: iscsi_pool_free(&session->cmdpool); cmdpool_alloc_fail: iscsi_free_session(cls_session); dec_session_count: iscsi_host_dec_session_cnt(shost); return NULL; } EXPORT_SYMBOL_GPL(iscsi_session_setup); /** * iscsi_session_teardown - destroy session, host, and cls_session * @cls_session: iscsi session * * The driver must have called iscsi_remove_session before * calling this. */ void iscsi_session_teardown(struct iscsi_cls_session *cls_session) { struct iscsi_session *session = cls_session->dd_data; struct module *owner = cls_session->transport->owner; struct Scsi_Host *shost = session->host; iscsi_pool_free(&session->cmdpool); kfree(session->password); kfree(session->password_in); kfree(session->username); kfree(session->username_in); kfree(session->targetname); kfree(session->initiatorname); kfree(session->ifacename); iscsi_destroy_session(cls_session); iscsi_host_dec_session_cnt(shost); module_put(owner); } EXPORT_SYMBOL_GPL(iscsi_session_teardown); /** * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn * @cls_session: iscsi_cls_session * @dd_size: private driver data size * @conn_idx: cid */ struct iscsi_cls_conn * iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, uint32_t conn_idx) { struct iscsi_session *session = cls_session->dd_data; struct iscsi_conn *conn; struct iscsi_cls_conn *cls_conn; char *data; cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size, conn_idx); if (!cls_conn) return NULL; conn = cls_conn->dd_data; memset(conn, 0, sizeof(*conn) + dd_size); conn->dd_data = cls_conn->dd_data + sizeof(*conn); conn->session = session; conn->cls_conn = cls_conn; conn->c_stage = ISCSI_CONN_INITIAL_STAGE; conn->id = conn_idx; conn->exp_statsn = 0; conn->tmf_state = TMF_INITIAL; init_timer(&conn->transport_timer); conn->transport_timer.data = (unsigned long)conn; conn->transport_timer.function = iscsi_check_transport_timeouts; INIT_LIST_HEAD(&conn->mgmtqueue); INIT_LIST_HEAD(&conn->cmdqueue); INIT_LIST_HEAD(&conn->requeue); INIT_WORK(&conn->xmitwork, iscsi_xmitworker); /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->lock); if (!kfifo_out(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->lock); goto login_task_alloc_fail; } spin_unlock_bh(&session->lock); data = (char *) __get_free_pages(GFP_KERNEL, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); if (!data) goto login_task_data_alloc_fail; conn->login_task->data = conn->data = data; init_timer(&conn->tmf_timer); init_waitqueue_head(&conn->ehwait); return cls_conn; login_task_data_alloc_fail: kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); return NULL; } EXPORT_SYMBOL_GPL(iscsi_conn_setup); /** * iscsi_conn_teardown - teardown iscsi connection * cls_conn: iscsi class connection * * TODO: we may need to make this into a two step process * like scsi-mls remove + put host */ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; unsigned long flags; del_timer_sync(&conn->transport_timer); spin_lock_bh(&session->lock); conn->c_stage = ISCSI_CONN_CLEANUP_WAIT; if (session->leadconn == conn) { /* * leading connection? then give up on recovery. */ session->state = ISCSI_STATE_TERMINATE; wake_up(&conn->ehwait); } spin_unlock_bh(&session->lock); /* * Block until all in-progress commands for this connection * time out or fail. */ for (;;) { spin_lock_irqsave(session->host->host_lock, flags); if (!session->host->host_busy) { /* OK for ERL == 0 */ spin_unlock_irqrestore(session->host->host_lock, flags); break; } spin_unlock_irqrestore(session->host->host_lock, flags); msleep_interruptible(500); iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): " "host_busy %d host_failed %d\n", session->host->host_busy, session->host->host_failed); /* * force eh_abort() to unblock */ wake_up(&conn->ehwait); } /* flush queued up work because we free the connection below */ iscsi_suspend_tx(conn); spin_lock_bh(&session->lock); free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); if (session->leadconn == conn) session->leadconn = NULL; spin_unlock_bh(&session->lock); iscsi_destroy_conn(cls_conn); } EXPORT_SYMBOL_GPL(iscsi_conn_teardown); int iscsi_conn_start(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; if (!session) { iscsi_conn_printk(KERN_ERR, conn, "can't start unbound connection\n"); return -EPERM; } if ((session->imm_data_en || !session->initial_r2t_en) && session->first_burst > session->max_burst) { iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: " "first_burst %d max_burst %d\n", session->first_burst, session->max_burst); return -EINVAL; } if (conn->ping_timeout && !conn->recv_timeout) { iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of " "zero. Using 5 seconds\n."); conn->recv_timeout = 5; } if (conn->recv_timeout && !conn->ping_timeout) { iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of " "zero. Using 5 seconds.\n"); conn->ping_timeout = 5; } spin_lock_bh(&session->lock); conn->c_stage = ISCSI_CONN_STARTED; session->state = ISCSI_STATE_LOGGED_IN; session->queued_cmdsn = session->cmdsn; conn->last_recv = jiffies; conn->last_ping = jiffies; if (conn->recv_timeout && conn->ping_timeout) mod_timer(&conn->transport_timer, jiffies + (conn->recv_timeout * HZ)); switch(conn->stop_stage) { case STOP_CONN_RECOVER: /* * unblock eh_abort() if it is blocked. re-try all * commands after successful recovery */ conn->stop_stage = 0; conn->tmf_state = TMF_INITIAL; session->age++; if (session->age == 16) session->age = 0; break; case STOP_CONN_TERM: conn->stop_stage = 0; break; default: break; } spin_unlock_bh(&session->lock); iscsi_unblock_session(session->cls_session); wake_up(&conn->ehwait); return 0; } EXPORT_SYMBOL_GPL(iscsi_conn_start); static void fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn) { struct iscsi_task *task; int i, state; for (i = 0; i < conn->session->cmds_max; i++) { task = conn->session->cmds[i]; if (task->sc) continue; if (task->state == ISCSI_TASK_FREE) continue; ISCSI_DBG_SESSION(conn->session, "failing mgmt itt 0x%x state %d\n", task->itt, task->state); state = ISCSI_TASK_ABRT_SESS_RECOV; if (task->state == ISCSI_TASK_PENDING) state = ISCSI_TASK_COMPLETED; iscsi_complete_task(task, state); } } static void iscsi_start_session_recovery(struct iscsi_session *session, struct iscsi_conn *conn, int flag) { int old_stop_stage; mutex_lock(&session->eh_mutex); spin_lock_bh(&session->lock); if (conn->stop_stage == STOP_CONN_TERM) { spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); return; } /* * When this is called for the in_login state, we only want to clean * up the login task and connection. We do not need to block and set * the recovery state again */ if (flag == STOP_CONN_TERM) session->state = ISCSI_STATE_TERMINATE; else if (conn->stop_stage != STOP_CONN_RECOVER) session->state = ISCSI_STATE_IN_RECOVERY; old_stop_stage = conn->stop_stage; conn->stop_stage = flag; spin_unlock_bh(&session->lock); del_timer_sync(&conn->transport_timer); iscsi_suspend_tx(conn); spin_lock_bh(&session->lock); conn->c_stage = ISCSI_CONN_STOPPED; spin_unlock_bh(&session->lock); /* * for connection level recovery we should not calculate * header digest. conn->hdr_size used for optimization * in hdr_extract() and will be re-negotiated at * set_param() time. */ if (flag == STOP_CONN_RECOVER) { conn->hdrdgst_en = 0; conn->datadgst_en = 0; if (session->state == ISCSI_STATE_IN_RECOVERY && old_stop_stage != STOP_CONN_RECOVER) { ISCSI_DBG_SESSION(session, "blocking session\n"); iscsi_block_session(session->cls_session); } } /* * flush queues. */ spin_lock_bh(&session->lock); fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED); fail_mgmt_tasks(session, conn); memset(&conn->tmhdr, 0, sizeof(conn->tmhdr)); spin_unlock_bh(&session->lock); mutex_unlock(&session->eh_mutex); } void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; switch (flag) { case STOP_CONN_RECOVER: case STOP_CONN_TERM: iscsi_start_session_recovery(session, conn, flag); break; default: iscsi_conn_printk(KERN_ERR, conn, "invalid stop flag %d\n", flag); } } EXPORT_SYMBOL_GPL(iscsi_conn_stop); int iscsi_conn_bind(struct iscsi_cls_session *cls_session, struct iscsi_cls_conn *cls_conn, int is_leading) { struct iscsi_session *session = cls_session->dd_data; struct iscsi_conn *conn = cls_conn->dd_data; spin_lock_bh(&session->lock); if (is_leading) session->leadconn = conn; spin_unlock_bh(&session->lock); /* * Unblock xmitworker(), Login Phase will pass through. */ clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx); clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); return 0; } EXPORT_SYMBOL_GPL(iscsi_conn_bind); static int iscsi_switch_str_param(char **param, char *new_val_buf) { char *new_val; if (*param) { if (!strcmp(*param, new_val_buf)) return 0; } new_val = kstrdup(new_val_buf, GFP_NOIO); if (!new_val) return -ENOMEM; kfree(*param); *param = new_val; return 0; } int iscsi_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf, int buflen) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; uint32_t value; switch(param) { case ISCSI_PARAM_FAST_ABORT: sscanf(buf, "%d", &session->fast_abort); break; case ISCSI_PARAM_ABORT_TMO: sscanf(buf, "%d", &session->abort_timeout); break; case ISCSI_PARAM_LU_RESET_TMO: sscanf(buf, "%d", &session->lu_reset_timeout); break; case ISCSI_PARAM_TGT_RESET_TMO: sscanf(buf, "%d", &session->tgt_reset_timeout); break; case ISCSI_PARAM_PING_TMO: sscanf(buf, "%d", &conn->ping_timeout); break; case ISCSI_PARAM_RECV_TMO: sscanf(buf, "%d", &conn->recv_timeout); break; case ISCSI_PARAM_MAX_RECV_DLENGTH: sscanf(buf, "%d", &conn->max_recv_dlength); break; case ISCSI_PARAM_MAX_XMIT_DLENGTH: sscanf(buf, "%d", &conn->max_xmit_dlength); break; case ISCSI_PARAM_HDRDGST_EN: sscanf(buf, "%d", &conn->hdrdgst_en); break; case ISCSI_PARAM_DATADGST_EN: sscanf(buf, "%d", &conn->datadgst_en); break; case ISCSI_PARAM_INITIAL_R2T_EN: sscanf(buf, "%d", &session->initial_r2t_en); break; case ISCSI_PARAM_MAX_R2T: sscanf(buf, "%d", &session->max_r2t); break; case ISCSI_PARAM_IMM_DATA_EN: sscanf(buf, "%d", &session->imm_data_en); break; case ISCSI_PARAM_FIRST_BURST: sscanf(buf, "%d", &session->first_burst); break; case ISCSI_PARAM_MAX_BURST: sscanf(buf, "%d", &session->max_burst); break; case ISCSI_PARAM_PDU_INORDER_EN: sscanf(buf, "%d", &session->pdu_inorder_en); break; case ISCSI_PARAM_DATASEQ_INORDER_EN: sscanf(buf, "%d", &session->dataseq_inorder_en); break; case ISCSI_PARAM_ERL: sscanf(buf, "%d", &session->erl); break; case ISCSI_PARAM_IFMARKER_EN: sscanf(buf, "%d", &value); BUG_ON(value); break; case ISCSI_PARAM_OFMARKER_EN: sscanf(buf, "%d", &value); BUG_ON(value); break; case ISCSI_PARAM_EXP_STATSN: sscanf(buf, "%u", &conn->exp_statsn); break; case ISCSI_PARAM_USERNAME: return iscsi_switch_str_param(&session->username, buf); case ISCSI_PARAM_USERNAME_IN: return iscsi_switch_str_param(&session->username_in, buf); case ISCSI_PARAM_PASSWORD: return iscsi_switch_str_param(&session->password, buf); case ISCSI_PARAM_PASSWORD_IN: return iscsi_switch_str_param(&session->password_in, buf); case ISCSI_PARAM_TARGET_NAME: return iscsi_switch_str_param(&session->targetname, buf); case ISCSI_PARAM_TPGT: sscanf(buf, "%d", &session->tpgt); break; case ISCSI_PARAM_PERSISTENT_PORT: sscanf(buf, "%d", &conn->persistent_port); break; case ISCSI_PARAM_PERSISTENT_ADDRESS: return iscsi_switch_str_param(&conn->persistent_address, buf); case ISCSI_PARAM_IFACE_NAME: return iscsi_switch_str_param(&session->ifacename, buf); case ISCSI_PARAM_INITIATOR_NAME: return iscsi_switch_str_param(&session->initiatorname, buf); default: return -ENOSYS; } return 0; } EXPORT_SYMBOL_GPL(iscsi_set_param); int iscsi_session_get_param(struct iscsi_cls_session *cls_session, enum iscsi_param param, char *buf) { struct iscsi_session *session = cls_session->dd_data; int len; switch(param) { case ISCSI_PARAM_FAST_ABORT: len = sprintf(buf, "%d\n", session->fast_abort); break; case ISCSI_PARAM_ABORT_TMO: len = sprintf(buf, "%d\n", session->abort_timeout); break; case ISCSI_PARAM_LU_RESET_TMO: len = sprintf(buf, "%d\n", session->lu_reset_timeout); break; case ISCSI_PARAM_TGT_RESET_TMO: len = sprintf(buf, "%d\n", session->tgt_reset_timeout); break; case ISCSI_PARAM_INITIAL_R2T_EN: len = sprintf(buf, "%d\n", session->initial_r2t_en); break; case ISCSI_PARAM_MAX_R2T: len = sprintf(buf, "%hu\n", session->max_r2t); break; case ISCSI_PARAM_IMM_DATA_EN: len = sprintf(buf, "%d\n", session->imm_data_en); break; case ISCSI_PARAM_FIRST_BURST: len = sprintf(buf, "%u\n", session->first_burst); break; case ISCSI_PARAM_MAX_BURST: len = sprintf(buf, "%u\n", session->max_burst); break; case ISCSI_PARAM_PDU_INORDER_EN: len = sprintf(buf, "%d\n", session->pdu_inorder_en); break; case ISCSI_PARAM_DATASEQ_INORDER_EN: len = sprintf(buf, "%d\n", session->dataseq_inorder_en); break; case ISCSI_PARAM_ERL: len = sprintf(buf, "%d\n", session->erl); break; case ISCSI_PARAM_TARGET_NAME: len = sprintf(buf, "%s\n", session->targetname); break; case ISCSI_PARAM_TPGT: len = sprintf(buf, "%d\n", session->tpgt); break; case ISCSI_PARAM_USERNAME: len = sprintf(buf, "%s\n", session->username); break; case ISCSI_PARAM_USERNAME_IN: len = sprintf(buf, "%s\n", session->username_in); break; case ISCSI_PARAM_PASSWORD: len = sprintf(buf, "%s\n", session->password); break; case ISCSI_PARAM_PASSWORD_IN: len = sprintf(buf, "%s\n", session->password_in); break; case ISCSI_PARAM_IFACE_NAME: len = sprintf(buf, "%s\n", session->ifacename); break; case ISCSI_PARAM_INITIATOR_NAME: len = sprintf(buf, "%s\n", session->initiatorname); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_session_get_param); int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf) { struct iscsi_conn *conn = cls_conn->dd_data; int len; switch(param) { case ISCSI_PARAM_PING_TMO: len = sprintf(buf, "%u\n", conn->ping_timeout); break; case ISCSI_PARAM_RECV_TMO: len = sprintf(buf, "%u\n", conn->recv_timeout); break; case ISCSI_PARAM_MAX_RECV_DLENGTH: len = sprintf(buf, "%u\n", conn->max_recv_dlength); break; case ISCSI_PARAM_MAX_XMIT_DLENGTH: len = sprintf(buf, "%u\n", conn->max_xmit_dlength); break; case ISCSI_PARAM_HDRDGST_EN: len = sprintf(buf, "%d\n", conn->hdrdgst_en); break; case ISCSI_PARAM_DATADGST_EN: len = sprintf(buf, "%d\n", conn->datadgst_en); break; case ISCSI_PARAM_IFMARKER_EN: len = sprintf(buf, "%d\n", conn->ifmarker_en); break; case ISCSI_PARAM_OFMARKER_EN: len = sprintf(buf, "%d\n", conn->ofmarker_en); break; case ISCSI_PARAM_EXP_STATSN: len = sprintf(buf, "%u\n", conn->exp_statsn); break; case ISCSI_PARAM_PERSISTENT_PORT: len = sprintf(buf, "%d\n", conn->persistent_port); break; case ISCSI_PARAM_PERSISTENT_ADDRESS: len = sprintf(buf, "%s\n", conn->persistent_address); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_conn_get_param); int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf) { struct iscsi_host *ihost = shost_priv(shost); int len; switch (param) { case ISCSI_HOST_PARAM_NETDEV_NAME: len = sprintf(buf, "%s\n", ihost->netdev); break; case ISCSI_HOST_PARAM_HWADDRESS: len = sprintf(buf, "%s\n", ihost->hwaddress); break; case ISCSI_HOST_PARAM_INITIATOR_NAME: len = sprintf(buf, "%s\n", ihost->initiatorname); break; case ISCSI_HOST_PARAM_IPADDRESS: len = sprintf(buf, "%s\n", ihost->local_address); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_host_get_param); int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf, int buflen) { struct iscsi_host *ihost = shost_priv(shost); switch (param) { case ISCSI_HOST_PARAM_NETDEV_NAME: return iscsi_switch_str_param(&ihost->netdev, buf); case ISCSI_HOST_PARAM_HWADDRESS: return iscsi_switch_str_param(&ihost->hwaddress, buf); case ISCSI_HOST_PARAM_INITIATOR_NAME: return iscsi_switch_str_param(&ihost->initiatorname, buf); default: return -ENOSYS; } return 0; } EXPORT_SYMBOL_GPL(iscsi_host_set_param); MODULE_AUTHOR("Mike Christie"); MODULE_DESCRIPTION("iSCSI library functions"); MODULE_LICENSE("GPL"); open-iscsi-2.0.873/kernel/libiscsi.h000066400000000000000000000314731175631155400172160ustar00rootroot00000000000000/* * iSCSI lib definitions * * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * Copyright (C) 2004 - 2006 Mike Christie * Copyright (C) 2004 - 2005 Dmitry Yusupov * Copyright (C) 2004 - 2005 Alex Aizman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef LIBISCSI_H #define LIBISCSI_H #include #include #include #include #include #include "iscsi_proto.h" #include "iscsi_if.h" #include "scsi_transport_iscsi.h" struct scsi_transport_template; struct scsi_host_template; struct scsi_device; struct Scsi_Host; struct scsi_target; struct scsi_cmnd; struct socket; struct iscsi_transport; struct iscsi_cls_session; struct iscsi_cls_conn; struct iscsi_session; struct iscsi_nopin; struct device; #define ISCSI_DEF_XMIT_CMDS_MAX 128 /* must be power of 2 */ #define ISCSI_MGMT_CMDS_MAX 15 #define ISCSI_DEF_CMD_PER_LUN 32 /* Task Mgmt states */ enum { TMF_INITIAL, TMF_QUEUED, TMF_SUCCESS, TMF_FAILED, TMF_TIMEDOUT, TMF_NOT_FOUND, }; /* Connection suspend "bit" */ #define ISCSI_SUSPEND_BIT 1 #define ISCSI_ITT_MASK 0x1fff #define ISCSI_TOTAL_CMDS_MAX 4096 /* this must be a power of two greater than ISCSI_MGMT_CMDS_MAX */ #define ISCSI_TOTAL_CMDS_MIN 16 #define ISCSI_AGE_SHIFT 28 #define ISCSI_AGE_MASK 0xf #define ISCSI_ADDRESS_BUF_LEN 64 enum { /* this is the maximum possible storage for AHSs */ ISCSI_MAX_AHS_SIZE = sizeof(struct iscsi_ecdb_ahdr) + sizeof(struct iscsi_rlength_ahdr), ISCSI_DIGEST_SIZE = sizeof(__u32), }; enum { ISCSI_TASK_FREE, ISCSI_TASK_COMPLETED, ISCSI_TASK_PENDING, ISCSI_TASK_RUNNING, ISCSI_TASK_ABRT_TMF, /* aborted due to TMF */ ISCSI_TASK_ABRT_SESS_RECOV, /* aborted due to session recovery */ }; struct iscsi_r2t_info { __be32 ttt; /* copied from R2T */ __be32 exp_statsn; /* copied from R2T */ uint32_t data_length; /* copied from R2T */ uint32_t data_offset; /* copied from R2T */ int data_count; /* DATA-Out payload progress */ int datasn; /* LLDs should set/update these values */ int sent; /* R2T sequence progress */ }; struct iscsi_task { /* * Because LLDs allocate their hdr differently, this is a pointer * and length to that storage. It must be setup at session * creation time. */ struct iscsi_hdr *hdr; unsigned short hdr_max; unsigned short hdr_len; /* accumulated size of hdr used */ /* copied values in case we need to send tmfs */ itt_t hdr_itt; __be32 cmdsn; uint8_t lun[8]; int itt; /* this ITT */ unsigned imm_count; /* imm-data (bytes) */ /* offset in unsolicited stream (bytes); */ struct iscsi_r2t_info unsol_r2t; char *data; /* mgmt payload */ unsigned data_count; struct scsi_cmnd *sc; /* associated SCSI cmd*/ struct iscsi_conn *conn; /* used connection */ /* data processing tracking */ unsigned long last_xfer; unsigned long last_timeout; int have_checked_conn; /* state set/tested under session->lock */ int state; atomic_t refcount; struct list_head running; /* running cmd list */ void *dd_data; /* driver/transport data */ }; static inline int iscsi_task_has_unsol_data(struct iscsi_task *task) { return task->unsol_r2t.data_length > task->unsol_r2t.sent; } static inline void* iscsi_next_hdr(struct iscsi_task *task) { return (void*)task->hdr + task->hdr_len; } /* Connection's states */ enum { ISCSI_CONN_INITIAL_STAGE, ISCSI_CONN_STARTED, ISCSI_CONN_STOPPED, ISCSI_CONN_CLEANUP_WAIT, }; struct iscsi_conn { struct iscsi_cls_conn *cls_conn; /* ptr to class connection */ void *dd_data; /* iscsi_transport data */ struct iscsi_session *session; /* parent session */ /* * conn_stop() flag: stop to recover, stop to terminate */ int stop_stage; struct timer_list transport_timer; unsigned long last_recv; unsigned long last_ping; int ping_timeout; int recv_timeout; struct iscsi_task *ping_task; /* iSCSI connection-wide sequencing */ uint32_t exp_statsn; /* control data */ int id; /* CID */ int c_stage; /* connection state */ /* * Preallocated buffer for pdus that have data but do not * originate from scsi-ml. We never have two pdus using the * buffer at the same time. It is only allocated to * the default max recv size because the pdus we support * should always fit in this buffer */ char *data; struct iscsi_task *login_task; /* mtask used for login/text */ struct iscsi_task *task; /* xmit task in progress */ /* xmit */ struct list_head mgmtqueue; /* mgmt (control) xmit queue */ struct list_head cmdqueue; /* data-path cmd queue */ struct list_head requeue; /* tasks needing another run */ struct work_struct xmitwork; /* per-conn. xmit workqueue */ unsigned long suspend_tx; /* suspend Tx */ unsigned long suspend_rx; /* suspend Rx */ /* abort */ wait_queue_head_t ehwait; /* used in eh_abort() */ struct iscsi_tm tmhdr; struct timer_list tmf_timer; int tmf_state; /* see TMF_INITIAL, etc.*/ /* negotiated params */ unsigned max_recv_dlength; /* initiator_max_recv_dsl*/ unsigned max_xmit_dlength; /* target_max_recv_dsl */ int hdrdgst_en; int datadgst_en; int ifmarker_en; int ofmarker_en; /* values userspace uses to id a conn */ int persistent_port; char *persistent_address; /* remote portal currently connected to */ int portal_port; char portal_address[ISCSI_ADDRESS_BUF_LEN]; /* MIB-statistics */ uint64_t txdata_octets; uint64_t rxdata_octets; uint32_t scsicmd_pdus_cnt; uint32_t dataout_pdus_cnt; uint32_t scsirsp_pdus_cnt; uint32_t datain_pdus_cnt; uint32_t r2t_pdus_cnt; uint32_t tmfcmd_pdus_cnt; int32_t tmfrsp_pdus_cnt; /* custom statistics */ uint32_t eh_abort_cnt; uint32_t fmr_unalign_cnt; }; struct iscsi_pool { struct kfifo queue; /* FIFO Queue */ void **pool; /* Pool of elements */ int max; /* Max number of elements */ }; /* Session's states */ enum { ISCSI_STATE_FREE = 1, ISCSI_STATE_LOGGED_IN, ISCSI_STATE_FAILED, ISCSI_STATE_TERMINATE, ISCSI_STATE_IN_RECOVERY, ISCSI_STATE_RECOVERY_FAILED, ISCSI_STATE_LOGGING_OUT, }; struct iscsi_session { struct iscsi_cls_session *cls_session; /* * Syncs up the scsi eh thread with the iscsi eh thread when sending * task management functions. This must be taken before the session * and recv lock. */ struct mutex eh_mutex; /* iSCSI session-wide sequencing */ uint32_t cmdsn; uint32_t exp_cmdsn; uint32_t max_cmdsn; /* This tracks the reqs queued into the initiator */ uint32_t queued_cmdsn; /* configuration */ int abort_timeout; int lu_reset_timeout; int tgt_reset_timeout; int initial_r2t_en; unsigned max_r2t; int imm_data_en; unsigned first_burst; unsigned max_burst; int time2wait; int time2retain; int pdu_inorder_en; int dataseq_inorder_en; int erl; int fast_abort; int tpgt; char *username; char *username_in; char *password; char *password_in; char *targetname; char *ifacename; char *initiatorname; /* control data */ struct iscsi_transport *tt; struct Scsi_Host *host; struct iscsi_conn *leadconn; /* leading connection */ spinlock_t lock; /* protects session state, * * sequence numbers, * * session resources: * * - cmdpool, * * - mgmtpool, * * - r2tpool */ int state; /* session state */ int age; /* counts session re-opens */ int scsi_cmds_max; /* max scsi commands */ int cmds_max; /* size of cmds array */ struct iscsi_task **cmds; /* Original Cmds arr */ struct iscsi_pool cmdpool; /* PDU's pool */ void *dd_data; /* LLD private data */ }; enum { ISCSI_HOST_SETUP, ISCSI_HOST_REMOVED, }; struct iscsi_host { char *initiatorname; /* hw address or netdev iscsi connection is bound to */ char *hwaddress; char *netdev; /* local address */ int local_port; char local_address[ISCSI_ADDRESS_BUF_LEN]; wait_queue_head_t session_removal_wq; /* protects sessions and state */ spinlock_t lock; int num_sessions; int state; struct workqueue_struct *workq; char workq_name[20]; }; /* * scsi host template */ extern int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason); extern int iscsi_eh_abort(struct scsi_cmnd *sc); extern int iscsi_eh_recover_target(struct scsi_cmnd *sc); extern int iscsi_eh_session_reset(struct scsi_cmnd *sc); extern int iscsi_eh_device_reset(struct scsi_cmnd *sc); extern int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *)); /* * iSCSI host helpers. */ #define iscsi_host_priv(_shost) \ (shost_priv(_shost) + sizeof(struct iscsi_host)) extern int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf, int buflen); extern int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf); extern int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev); extern struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht, int dd_data_size, bool xmit_can_sleep); extern void iscsi_host_remove(struct Scsi_Host *shost); extern void iscsi_host_free(struct Scsi_Host *shost); extern int iscsi_target_alloc(struct scsi_target *starget); /* * session management */ extern struct iscsi_cls_session * iscsi_session_setup(struct iscsi_transport *, struct Scsi_Host *shost, uint16_t, int, int, uint32_t, unsigned int); extern void iscsi_session_teardown(struct iscsi_cls_session *); extern void iscsi_session_recovery_timedout(struct iscsi_cls_session *); extern int iscsi_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf, int buflen); extern int iscsi_session_get_param(struct iscsi_cls_session *cls_session, enum iscsi_param param, char *buf); #define iscsi_session_printk(prefix, _sess, fmt, a...) \ iscsi_cls_session_printk(prefix, _sess->cls_session, fmt, ##a) /* * connection management */ extern struct iscsi_cls_conn *iscsi_conn_setup(struct iscsi_cls_session *, int, uint32_t); extern void iscsi_conn_teardown(struct iscsi_cls_conn *); extern int iscsi_conn_start(struct iscsi_cls_conn *); extern void iscsi_conn_stop(struct iscsi_cls_conn *, int); extern int iscsi_conn_bind(struct iscsi_cls_session *, struct iscsi_cls_conn *, int); extern void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err); extern void iscsi_session_failure(struct iscsi_session *session, enum iscsi_err err); extern int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf); extern void iscsi_suspend_tx(struct iscsi_conn *conn); extern void iscsi_suspend_queue(struct iscsi_conn *conn); extern void iscsi_conn_queue_work(struct iscsi_conn *conn); #define iscsi_conn_printk(prefix, _c, fmt, a...) \ iscsi_cls_conn_printk(prefix, ((struct iscsi_conn *)_c)->cls_conn, \ fmt, ##a) /* * pdu and task processing */ extern void iscsi_update_cmdsn(struct iscsi_session *, struct iscsi_nopin *); extern void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t, struct iscsi_data *hdr); extern int iscsi_conn_send_pdu(struct iscsi_cls_conn *, struct iscsi_hdr *, char *, uint32_t); extern int iscsi_complete_pdu(struct iscsi_conn *, struct iscsi_hdr *, char *, int); extern int __iscsi_complete_pdu(struct iscsi_conn *, struct iscsi_hdr *, char *, int); extern int iscsi_verify_itt(struct iscsi_conn *, itt_t); extern struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *, itt_t); extern struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *, itt_t); extern void iscsi_requeue_task(struct iscsi_task *task); extern void iscsi_put_task(struct iscsi_task *task); extern void __iscsi_get_task(struct iscsi_task *task); extern void iscsi_complete_scsi_task(struct iscsi_task *task, uint32_t exp_cmdsn, uint32_t max_cmdsn); /* * generic helpers */ extern void iscsi_pool_free(struct iscsi_pool *); extern int iscsi_pool_init(struct iscsi_pool *, int, void ***, int); /* * inline functions to deal with padding. */ static inline unsigned int iscsi_padded(unsigned int len) { return (len + ISCSI_PAD_LEN - 1) & ~(ISCSI_PAD_LEN - 1); } static inline unsigned int iscsi_padding(unsigned int len) { len &= (ISCSI_PAD_LEN - 1); if (len) len = ISCSI_PAD_LEN - len; return len; } #endif open-iscsi-2.0.873/kernel/libiscsi_tcp.c000066400000000000000000000774271175631155400200700ustar00rootroot00000000000000/* * iSCSI over TCP/IP Data-Path lib * * Copyright (C) 2004 Dmitry Yusupov * Copyright (C) 2004 Alex Aizman * Copyright (C) 2005 - 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. * * Credits: * Christoph Hellwig * FUJITA Tomonori * Arne Redlich * Zhenyu Wang */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "scsi_transport_iscsi.h" #include "iscsi_tcp.h" MODULE_AUTHOR("Mike Christie , " "Dmitry Yusupov , " "Alex Aizman "); MODULE_DESCRIPTION("iSCSI/TCP data-path"); MODULE_LICENSE("GPL"); static int iscsi_dbg_libtcp; module_param_named(debug_libiscsi_tcp, iscsi_dbg_libtcp, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_tcp, "Turn on debugging for libiscsi_tcp " "module. Set to 1 to turn on, and zero to turn off. Default " "is off."); #define ISCSI_DBG_TCP(_conn, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_libtcp) \ iscsi_conn_printk(KERN_INFO, _conn, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); static int iscsi_tcp_hdr_recv_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment); /* * Scatterlist handling: inside the iscsi_segment, we * remember an index into the scatterlist, and set data/size * to the current scatterlist entry. For highmem pages, we * kmap as needed. * * Note that the page is unmapped when we return from * TCP's data_ready handler, so we may end up mapping and * unmapping the same page repeatedly. The whole reason * for this is that we shouldn't keep the page mapped * outside the softirq. */ /** * iscsi_tcp_segment_init_sg - init indicated scatterlist entry * @segment: the buffer object * @sg: scatterlist * @offset: byte offset into that sg entry * * This function sets up the segment so that subsequent * data is copied to the indicated sg entry, at the given * offset. */ static inline void iscsi_tcp_segment_init_sg(struct iscsi_segment *segment, struct scatterlist *sg, unsigned int offset) { segment->sg = sg; segment->sg_offset = offset; segment->size = min(sg->length - offset, segment->total_size - segment->total_copied); segment->data = NULL; } /** * iscsi_tcp_segment_map - map the current S/G page * @segment: iscsi_segment * @recv: 1 if called from recv path * * We only need to possibly kmap data if scatter lists are being used, * because the iscsi passthrough and internal IO paths will never use high * mem pages. */ static void iscsi_tcp_segment_map(struct iscsi_segment *segment, int recv) { struct scatterlist *sg; if (segment->data != NULL || !segment->sg) return; sg = segment->sg; BUG_ON(segment->sg_mapped); BUG_ON(sg->length == 0); /* * If the page count is greater than one it is ok to send * to the network layer's zero copy send path. If not we * have to go the slow sendmsg path. We always map for the * recv path. */ if (page_count(sg_page(sg)) >= 1 && !recv) return; segment->sg_mapped = kmap_atomic(sg_page(sg), KM_SOFTIRQ0); segment->data = segment->sg_mapped + sg->offset + segment->sg_offset; } void iscsi_tcp_segment_unmap(struct iscsi_segment *segment) { if (segment->sg_mapped) { kunmap_atomic(segment->sg_mapped, KM_SOFTIRQ0); segment->sg_mapped = NULL; segment->data = NULL; } } EXPORT_SYMBOL_GPL(iscsi_tcp_segment_unmap); /* * Splice the digest buffer into the buffer */ static inline void iscsi_tcp_segment_splice_digest(struct iscsi_segment *segment, void *digest) { segment->data = digest; segment->digest_len = ISCSI_DIGEST_SIZE; segment->total_size += ISCSI_DIGEST_SIZE; segment->size = ISCSI_DIGEST_SIZE; segment->copied = 0; segment->sg = NULL; segment->hash = NULL; } /** * iscsi_tcp_segment_done - check whether the segment is complete * @tcp_conn: iscsi tcp connection * @segment: iscsi segment to check * @recv: set to one of this is called from the recv path * @copied: number of bytes copied * * Check if we're done receiving this segment. If the receive * buffer is full but we expect more data, move on to the * next entry in the scatterlist. * * If the amount of data we received isn't a multiple of 4, * we will transparently receive the pad bytes, too. * * This function must be re-entrant. */ int iscsi_tcp_segment_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment, int recv, unsigned copied) { struct scatterlist sg; unsigned int pad; ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "copied %u %u size %u %s\n", segment->copied, copied, segment->size, recv ? "recv" : "xmit"); if (segment->hash && copied) { /* * If a segment is kmapd we must unmap it before sending * to the crypto layer since that will try to kmap it again. */ iscsi_tcp_segment_unmap(segment); if (!segment->data) { sg_init_table(&sg, 1); sg_set_page(&sg, sg_page(segment->sg), copied, segment->copied + segment->sg_offset + segment->sg->offset); } else sg_init_one(&sg, segment->data + segment->copied, copied); crypto_hash_update(segment->hash, &sg, copied); } segment->copied += copied; if (segment->copied < segment->size) { iscsi_tcp_segment_map(segment, recv); return 0; } segment->total_copied += segment->copied; segment->copied = 0; segment->size = 0; /* Unmap the current scatterlist page, if there is one. */ iscsi_tcp_segment_unmap(segment); /* Do we have more scatterlist entries? */ ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "total copied %u total size %u\n", segment->total_copied, segment->total_size); if (segment->total_copied < segment->total_size) { /* Proceed to the next entry in the scatterlist. */ iscsi_tcp_segment_init_sg(segment, sg_next(segment->sg), 0); iscsi_tcp_segment_map(segment, recv); BUG_ON(segment->size == 0); return 0; } /* Do we need to handle padding? */ if (!(tcp_conn->iscsi_conn->session->tt->caps & CAP_PADDING_OFFLOAD)) { pad = iscsi_padding(segment->total_copied); if (pad != 0) { ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "consume %d pad bytes\n", pad); segment->total_size += pad; segment->size = pad; segment->data = segment->padbuf; return 0; } } /* * Set us up for transferring the data digest. hdr digest * is completely handled in hdr done function. */ if (segment->hash) { crypto_hash_final(segment->hash, segment->digest); iscsi_tcp_segment_splice_digest(segment, recv ? segment->recv_digest : segment->digest); return 0; } return 1; } EXPORT_SYMBOL_GPL(iscsi_tcp_segment_done); /** * iscsi_tcp_segment_recv - copy data to segment * @tcp_conn: the iSCSI TCP connection * @segment: the buffer to copy to * @ptr: data pointer * @len: amount of data available * * This function copies up to @len bytes to the * given buffer, and returns the number of bytes * consumed, which can actually be less than @len. * * If hash digest is enabled, the function will update the * hash while copying. * Combining these two operations doesn't buy us a lot (yet), * but in the future we could implement combined copy+crc, * just way we do for network layer checksums. */ static int iscsi_tcp_segment_recv(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment, const void *ptr, unsigned int len) { unsigned int copy = 0, copied = 0; while (!iscsi_tcp_segment_done(tcp_conn, segment, 1, copy)) { if (copied == len) { ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "copied %d bytes\n", len); break; } copy = min(len - copied, segment->size - segment->copied); ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "copying %d\n", copy); memcpy(segment->data + segment->copied, ptr + copied, copy); copied += copy; } return copied; } inline void iscsi_tcp_dgst_header(struct hash_desc *hash, const void *hdr, size_t hdrlen, unsigned char digest[ISCSI_DIGEST_SIZE]) { struct scatterlist sg; sg_init_one(&sg, hdr, hdrlen); crypto_hash_digest(hash, &sg, hdrlen, digest); } EXPORT_SYMBOL_GPL(iscsi_tcp_dgst_header); static inline int iscsi_tcp_dgst_verify(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { if (!segment->digest_len) return 1; if (memcmp(segment->recv_digest, segment->digest, segment->digest_len)) { ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "digest mismatch\n"); return 0; } return 1; } /* * Helper function to set up segment buffer */ static inline void __iscsi_segment_init(struct iscsi_segment *segment, size_t size, iscsi_segment_done_fn_t *done, struct hash_desc *hash) { memset(segment, 0, sizeof(*segment)); segment->total_size = size; segment->done = done; if (hash) { segment->hash = hash; crypto_hash_init(hash); } } inline void iscsi_segment_init_linear(struct iscsi_segment *segment, void *data, size_t size, iscsi_segment_done_fn_t *done, struct hash_desc *hash) { __iscsi_segment_init(segment, size, done, hash); segment->data = data; segment->size = size; } EXPORT_SYMBOL_GPL(iscsi_segment_init_linear); inline int iscsi_segment_seek_sg(struct iscsi_segment *segment, struct scatterlist *sg_list, unsigned int sg_count, unsigned int offset, size_t size, iscsi_segment_done_fn_t *done, struct hash_desc *hash) { struct scatterlist *sg; unsigned int i; __iscsi_segment_init(segment, size, done, hash); for_each_sg(sg_list, sg, sg_count, i) { if (offset < sg->length) { iscsi_tcp_segment_init_sg(segment, sg, offset); return 0; } offset -= sg->length; } return ISCSI_ERR_DATA_OFFSET; } EXPORT_SYMBOL_GPL(iscsi_segment_seek_sg); /** * iscsi_tcp_hdr_recv_prep - prep segment for hdr reception * @tcp_conn: iscsi connection to prep for * * This function always passes NULL for the hash argument, because when this * function is called we do not yet know the final size of the header and want * to delay the digest processing until we know that. */ void iscsi_tcp_hdr_recv_prep(struct iscsi_tcp_conn *tcp_conn) { ISCSI_DBG_TCP(tcp_conn->iscsi_conn, "(%s)\n", tcp_conn->iscsi_conn->hdrdgst_en ? "digest enabled" : "digest disabled"); iscsi_segment_init_linear(&tcp_conn->in.segment, tcp_conn->in.hdr_buf, sizeof(struct iscsi_hdr), iscsi_tcp_hdr_recv_done, NULL); } EXPORT_SYMBOL_GPL(iscsi_tcp_hdr_recv_prep); /* * Handle incoming reply to any other type of command */ static int iscsi_tcp_data_recv_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { struct iscsi_conn *conn = tcp_conn->iscsi_conn; int rc = 0; if (!iscsi_tcp_dgst_verify(tcp_conn, segment)) return ISCSI_ERR_DATA_DGST; rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, conn->data, tcp_conn->in.datalen); if (rc) return rc; iscsi_tcp_hdr_recv_prep(tcp_conn); return 0; } static void iscsi_tcp_data_recv_prep(struct iscsi_tcp_conn *tcp_conn) { struct iscsi_conn *conn = tcp_conn->iscsi_conn; struct hash_desc *rx_hash = NULL; if (conn->datadgst_en && !(conn->session->tt->caps & CAP_DIGEST_OFFLOAD)) rx_hash = tcp_conn->rx_hash; iscsi_segment_init_linear(&tcp_conn->in.segment, conn->data, tcp_conn->in.datalen, iscsi_tcp_data_recv_done, rx_hash); } /** * iscsi_tcp_cleanup_task - free tcp_task resources * @task: iscsi task * * must be called with session lock */ void iscsi_tcp_cleanup_task(struct iscsi_task *task) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_r2t_info *r2t; /* nothing to do for mgmt */ if (!task->sc) return; /* flush task's r2t queues */ while (kfifo_out(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*))) { kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); ISCSI_DBG_TCP(task->conn, "pending r2t dropped\n"); } r2t = tcp_task->r2t; if (r2t != NULL) { kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); tcp_task->r2t = NULL; } } EXPORT_SYMBOL_GPL(iscsi_tcp_cleanup_task); /** * iscsi_tcp_data_in - SCSI Data-In Response processing * @conn: iscsi connection * @task: scsi command task */ static int iscsi_tcp_data_in(struct iscsi_conn *conn, struct iscsi_task *task) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr; int datasn = be32_to_cpu(rhdr->datasn); unsigned total_in_length = scsi_in(task->sc)->length; /* * lib iscsi will update this in the completion handling if there * is status. */ if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS)) iscsi_update_cmdsn(conn->session, (struct iscsi_nopin*)rhdr); if (tcp_conn->in.datalen == 0) return 0; if (tcp_task->exp_datasn != datasn) { ISCSI_DBG_TCP(conn, "task->exp_datasn(%d) != rhdr->datasn(%d)" "\n", tcp_task->exp_datasn, datasn); return ISCSI_ERR_DATASN; } tcp_task->exp_datasn++; tcp_task->data_offset = be32_to_cpu(rhdr->offset); if (tcp_task->data_offset + tcp_conn->in.datalen > total_in_length) { ISCSI_DBG_TCP(conn, "data_offset(%d) + data_len(%d) > " "total_length_in(%d)\n", tcp_task->data_offset, tcp_conn->in.datalen, total_in_length); return ISCSI_ERR_DATA_OFFSET; } conn->datain_pdus_cnt++; return 0; } /** * iscsi_tcp_r2t_rsp - iSCSI R2T Response processing * @conn: iscsi connection * @task: scsi command task */ static int iscsi_tcp_r2t_rsp(struct iscsi_conn *conn, struct iscsi_task *task) { struct iscsi_session *session = conn->session; struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_r2t_rsp *rhdr = (struct iscsi_r2t_rsp *)tcp_conn->in.hdr; struct iscsi_r2t_info *r2t; int r2tsn = be32_to_cpu(rhdr->r2tsn); int rc; if (tcp_conn->in.datalen) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2t with datalen %d\n", tcp_conn->in.datalen); return ISCSI_ERR_DATALEN; } if (tcp_task->exp_datasn != r2tsn){ ISCSI_DBG_TCP(conn, "task->exp_datasn(%d) != rhdr->r2tsn(%d)\n", tcp_task->exp_datasn, r2tsn); return ISCSI_ERR_R2TSN; } /* fill-in new R2T associated with the task */ iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr); if (!task->sc || session->state != ISCSI_STATE_LOGGED_IN) { iscsi_conn_printk(KERN_INFO, conn, "dropping R2T itt %d in recovery.\n", task->itt); return 0; } rc = kfifo_out(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); if (!rc) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate R2T. " "Target has sent more R2Ts than it " "negotiated for or driver has has leaked.\n"); return ISCSI_ERR_PROTO; } r2t->exp_statsn = rhdr->statsn; r2t->data_length = be32_to_cpu(rhdr->data_length); if (r2t->data_length == 0) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with zero data len\n"); kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } if (r2t->data_length > session->max_burst) ISCSI_DBG_TCP(conn, "invalid R2T with data len %u and max " "burst %u. Attempting to execute request.\n", r2t->data_length, session->max_burst); r2t->data_offset = be32_to_cpu(rhdr->data_offset); if (r2t->data_offset + r2t->data_length > scsi_out(task->sc)->length) { iscsi_conn_printk(KERN_ERR, conn, "invalid R2T with data len %u at offset %u " "and total length %d\n", r2t->data_length, r2t->data_offset, scsi_out(task->sc)->length); kfifo_in(&tcp_task->r2tpool.queue, (void*)&r2t, sizeof(void*)); return ISCSI_ERR_DATALEN; } r2t->ttt = rhdr->ttt; /* no flip */ r2t->datasn = 0; r2t->sent = 0; tcp_task->exp_datasn = r2tsn + 1; kfifo_in(&tcp_task->r2tqueue, (void*)&r2t, sizeof(void*)); conn->r2t_pdus_cnt++; iscsi_requeue_task(task); return 0; } /* * Handle incoming reply to DataIn command */ static int iscsi_tcp_process_data_in(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { struct iscsi_conn *conn = tcp_conn->iscsi_conn; struct iscsi_hdr *hdr = tcp_conn->in.hdr; int rc; if (!iscsi_tcp_dgst_verify(tcp_conn, segment)) return ISCSI_ERR_DATA_DGST; /* check for non-exceptional status */ if (hdr->flags & ISCSI_FLAG_DATA_STATUS) { rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, NULL, 0); if (rc) return rc; } iscsi_tcp_hdr_recv_prep(tcp_conn); return 0; } /** * iscsi_tcp_hdr_dissect - process PDU header * @conn: iSCSI connection * @hdr: PDU header * * This function analyzes the header of the PDU received, * and performs several sanity checks. If the PDU is accompanied * by data, the receive buffer is set up to copy the incoming data * to the correct location. */ static int iscsi_tcp_hdr_dissect(struct iscsi_conn *conn, struct iscsi_hdr *hdr) { int rc = 0, opcode, ahslen; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_task *task; /* verify PDU length */ tcp_conn->in.datalen = ntoh24(hdr->dlength); if (tcp_conn->in.datalen > conn->max_recv_dlength) { iscsi_conn_printk(KERN_ERR, conn, "iscsi_tcp: datalen %d > %d\n", tcp_conn->in.datalen, conn->max_recv_dlength); return ISCSI_ERR_DATALEN; } /* Additional header segments. So far, we don't * process additional headers. */ ahslen = hdr->hlength << 2; opcode = hdr->opcode & ISCSI_OPCODE_MASK; /* verify itt (itt encoding: age+cid+itt) */ rc = iscsi_verify_itt(conn, hdr->itt); if (rc) return rc; ISCSI_DBG_TCP(conn, "opcode 0x%x ahslen %d datalen %d\n", opcode, ahslen, tcp_conn->in.datalen); switch(opcode) { case ISCSI_OP_SCSI_DATA_IN: spin_lock(&conn->session->lock); task = iscsi_itt_to_ctask(conn, hdr->itt); if (!task) rc = ISCSI_ERR_BAD_ITT; else rc = iscsi_tcp_data_in(conn, task); if (rc) { spin_unlock(&conn->session->lock); break; } if (tcp_conn->in.datalen) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct hash_desc *rx_hash = NULL; struct scsi_data_buffer *sdb = scsi_in(task->sc); /* * Setup copy of Data-In into the Scsi_Cmnd * Scatterlist case: * We set up the iscsi_segment to point to the next * scatterlist entry to copy to. As we go along, * we move on to the next scatterlist entry and * update the digest per-entry. */ if (conn->datadgst_en && !(conn->session->tt->caps & CAP_DIGEST_OFFLOAD)) rx_hash = tcp_conn->rx_hash; ISCSI_DBG_TCP(conn, "iscsi_tcp_begin_data_in( " "offset=%d, datalen=%d)\n", tcp_task->data_offset, tcp_conn->in.datalen); task->last_xfer = jiffies; rc = iscsi_segment_seek_sg(&tcp_conn->in.segment, sdb->table.sgl, sdb->table.nents, tcp_task->data_offset, tcp_conn->in.datalen, iscsi_tcp_process_data_in, rx_hash); spin_unlock(&conn->session->lock); return rc; } rc = __iscsi_complete_pdu(conn, hdr, NULL, 0); spin_unlock(&conn->session->lock); break; case ISCSI_OP_SCSI_CMD_RSP: if (tcp_conn->in.datalen) { iscsi_tcp_data_recv_prep(tcp_conn); return 0; } rc = iscsi_complete_pdu(conn, hdr, NULL, 0); break; case ISCSI_OP_R2T: spin_lock(&conn->session->lock); task = iscsi_itt_to_ctask(conn, hdr->itt); if (!task) rc = ISCSI_ERR_BAD_ITT; else if (ahslen) rc = ISCSI_ERR_AHSLEN; else if (task->sc->sc_data_direction == DMA_TO_DEVICE) { task->last_xfer = jiffies; rc = iscsi_tcp_r2t_rsp(conn, task); } else rc = ISCSI_ERR_PROTO; spin_unlock(&conn->session->lock); break; case ISCSI_OP_LOGIN_RSP: case ISCSI_OP_TEXT_RSP: case ISCSI_OP_REJECT: case ISCSI_OP_ASYNC_EVENT: /* * It is possible that we could get a PDU with a buffer larger * than 8K, but there are no targets that currently do this. * For now we fail until we find a vendor that needs it */ if (ISCSI_DEF_MAX_RECV_SEG_LEN < tcp_conn->in.datalen) { iscsi_conn_printk(KERN_ERR, conn, "iscsi_tcp: received buffer of " "len %u but conn buffer is only %u " "(opcode %0x)\n", tcp_conn->in.datalen, ISCSI_DEF_MAX_RECV_SEG_LEN, opcode); rc = ISCSI_ERR_PROTO; break; } /* If there's data coming in with the response, * receive it to the connection's buffer. */ if (tcp_conn->in.datalen) { iscsi_tcp_data_recv_prep(tcp_conn); return 0; } /* fall through */ case ISCSI_OP_LOGOUT_RSP: case ISCSI_OP_NOOP_IN: case ISCSI_OP_SCSI_TMFUNC_RSP: rc = iscsi_complete_pdu(conn, hdr, NULL, 0); break; default: rc = ISCSI_ERR_BAD_OPCODE; break; } if (rc == 0) { /* Anything that comes with data should have * been handled above. */ if (tcp_conn->in.datalen) return ISCSI_ERR_PROTO; iscsi_tcp_hdr_recv_prep(tcp_conn); } return rc; } /** * iscsi_tcp_hdr_recv_done - process PDU header * * This is the callback invoked when the PDU header has * been received. If the header is followed by additional * header segments, we go back for more data. */ static int iscsi_tcp_hdr_recv_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment) { struct iscsi_conn *conn = tcp_conn->iscsi_conn; struct iscsi_hdr *hdr; /* Check if there are additional header segments * *prior* to computing the digest, because we * may need to go back to the caller for more. */ hdr = (struct iscsi_hdr *) tcp_conn->in.hdr_buf; if (segment->copied == sizeof(struct iscsi_hdr) && hdr->hlength) { /* Bump the header length - the caller will * just loop around and get the AHS for us, and * call again. */ unsigned int ahslen = hdr->hlength << 2; /* Make sure we don't overflow */ if (sizeof(*hdr) + ahslen > sizeof(tcp_conn->in.hdr_buf)) return ISCSI_ERR_AHSLEN; segment->total_size += ahslen; segment->size += ahslen; return 0; } /* We're done processing the header. See if we're doing * header digests; if so, set up the recv_digest buffer * and go back for more. */ if (conn->hdrdgst_en && !(conn->session->tt->caps & CAP_DIGEST_OFFLOAD)) { if (segment->digest_len == 0) { /* * Even if we offload the digest processing we * splice it in so we can increment the skb/segment * counters in preparation for the data segment. */ iscsi_tcp_segment_splice_digest(segment, segment->recv_digest); return 0; } iscsi_tcp_dgst_header(tcp_conn->rx_hash, hdr, segment->total_copied - ISCSI_DIGEST_SIZE, segment->digest); if (!iscsi_tcp_dgst_verify(tcp_conn, segment)) return ISCSI_ERR_HDR_DGST; } tcp_conn->in.hdr = hdr; return iscsi_tcp_hdr_dissect(conn, hdr); } /** * iscsi_tcp_recv_segment_is_hdr - tests if we are reading in a header * @tcp_conn: iscsi tcp conn * * returns non zero if we are currently processing or setup to process * a header. */ inline int iscsi_tcp_recv_segment_is_hdr(struct iscsi_tcp_conn *tcp_conn) { return tcp_conn->in.segment.done == iscsi_tcp_hdr_recv_done; } EXPORT_SYMBOL_GPL(iscsi_tcp_recv_segment_is_hdr); /** * iscsi_tcp_recv_skb - Process skb * @conn: iscsi connection * @skb: network buffer with header and/or data segment * @offset: offset in skb * @offload: bool indicating if transfer was offloaded * * Will return status of transfer in status. And will return * number of bytes copied. */ int iscsi_tcp_recv_skb(struct iscsi_conn *conn, struct sk_buff *skb, unsigned int offset, bool offloaded, int *status) { struct iscsi_tcp_conn *tcp_conn = conn->dd_data; struct iscsi_segment *segment = &tcp_conn->in.segment; struct skb_seq_state seq; unsigned int consumed = 0; int rc = 0; ISCSI_DBG_TCP(conn, "in %d bytes\n", skb->len - offset); /* * Update for each skb instead of pdu, because over slow networks a * data_in's data could take a while to read in. We also want to * account for r2ts. */ conn->last_recv = jiffies; if (unlikely(conn->suspend_rx)) { ISCSI_DBG_TCP(conn, "Rx suspended!\n"); *status = ISCSI_TCP_SUSPENDED; return 0; } if (offloaded) { segment->total_copied = segment->total_size; goto segment_done; } skb_prepare_seq_read(skb, offset, skb->len, &seq); while (1) { unsigned int avail; const u8 *ptr; avail = skb_seq_read(consumed, &ptr, &seq); if (avail == 0) { ISCSI_DBG_TCP(conn, "no more data avail. Consumed %d\n", consumed); *status = ISCSI_TCP_SKB_DONE; skb_abort_seq_read(&seq); goto skb_done; } BUG_ON(segment->copied >= segment->size); ISCSI_DBG_TCP(conn, "skb %p ptr=%p avail=%u\n", skb, ptr, avail); rc = iscsi_tcp_segment_recv(tcp_conn, segment, ptr, avail); BUG_ON(rc == 0); consumed += rc; if (segment->total_copied >= segment->total_size) { skb_abort_seq_read(&seq); goto segment_done; } } segment_done: *status = ISCSI_TCP_SEGMENT_DONE; ISCSI_DBG_TCP(conn, "segment done\n"); rc = segment->done(tcp_conn, segment); if (rc != 0) { *status = ISCSI_TCP_CONN_ERR; ISCSI_DBG_TCP(conn, "Error receiving PDU, errno=%d\n", rc); iscsi_conn_failure(conn, rc); return 0; } /* The done() functions sets up the next segment. */ skb_done: conn->rxdata_octets += consumed; return consumed; } EXPORT_SYMBOL_GPL(iscsi_tcp_recv_skb); /** * iscsi_tcp_task_init - Initialize iSCSI SCSI_READ or SCSI_WRITE commands * @conn: iscsi connection * @task: scsi command task * @sc: scsi command */ int iscsi_tcp_task_init(struct iscsi_task *task) { struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_conn *conn = task->conn; struct scsi_cmnd *sc = task->sc; int err; if (!sc) { /* * mgmt tasks do not have a scatterlist since they come * in from the iscsi interface. */ ISCSI_DBG_TCP(conn, "mtask deq [itt 0x%x]\n", task->itt); return conn->session->tt->init_pdu(task, 0, task->data_count); } BUG_ON(kfifo_len(&tcp_task->r2tqueue)); tcp_task->exp_datasn = 0; /* Prepare PDU, optionally w/ immediate data */ ISCSI_DBG_TCP(conn, "task deq [itt 0x%x imm %d unsol %d]\n", task->itt, task->imm_count, task->unsol_r2t.data_length); err = conn->session->tt->init_pdu(task, 0, task->imm_count); if (err) return err; task->imm_count = 0; return 0; } EXPORT_SYMBOL_GPL(iscsi_tcp_task_init); static struct iscsi_r2t_info *iscsi_tcp_get_curr_r2t(struct iscsi_task *task) { struct iscsi_session *session = task->conn->session; struct iscsi_tcp_task *tcp_task = task->dd_data; struct iscsi_r2t_info *r2t = NULL; if (iscsi_task_has_unsol_data(task)) r2t = &task->unsol_r2t; else { spin_lock_bh(&session->lock); if (tcp_task->r2t) { r2t = tcp_task->r2t; /* Continue with this R2T? */ if (r2t->data_length <= r2t->sent) { ISCSI_DBG_TCP(task->conn, " done with r2t %p\n", r2t); kfifo_in(&tcp_task->r2tpool.queue, (void *)&tcp_task->r2t, sizeof(void *)); tcp_task->r2t = r2t = NULL; } } if (r2t == NULL) { if (kfifo_out(&tcp_task->r2tqueue, (void *)&tcp_task->r2t, sizeof(void *)) != sizeof(void *)) r2t = NULL; else r2t = tcp_task->r2t; } spin_unlock_bh(&session->lock); } return r2t; } /** * iscsi_tcp_task_xmit - xmit normal PDU task * @task: iscsi command task * * We're expected to return 0 when everything was transmitted successfully, * -EAGAIN if there's still data in the queue, or != 0 for any other kind * of error. */ int iscsi_tcp_task_xmit(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; struct iscsi_session *session = conn->session; struct iscsi_r2t_info *r2t; int rc = 0; flush: /* Flush any pending data first. */ rc = session->tt->xmit_pdu(task); if (rc < 0) return rc; /* mgmt command */ if (!task->sc) { if (task->hdr->itt == RESERVED_ITT) iscsi_put_task(task); return 0; } /* Are we done already? */ if (task->sc->sc_data_direction != DMA_TO_DEVICE) return 0; r2t = iscsi_tcp_get_curr_r2t(task); if (r2t == NULL) { /* Waiting for more R2Ts to arrive. */ ISCSI_DBG_TCP(conn, "no R2Ts yet\n"); return 0; } rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_DATA_OUT); if (rc) return rc; iscsi_prep_data_out_pdu(task, r2t, (struct iscsi_data *) task->hdr); ISCSI_DBG_TCP(conn, "sol dout %p [dsn %d itt 0x%x doff %d dlen %d]\n", r2t, r2t->datasn - 1, task->hdr->itt, r2t->data_offset + r2t->sent, r2t->data_count); rc = conn->session->tt->init_pdu(task, r2t->data_offset + r2t->sent, r2t->data_count); if (rc) { iscsi_conn_failure(conn, ISCSI_ERR_XMIT_FAILED); return rc; } r2t->sent += r2t->data_count; goto flush; } EXPORT_SYMBOL_GPL(iscsi_tcp_task_xmit); struct iscsi_cls_conn * iscsi_tcp_conn_setup(struct iscsi_cls_session *cls_session, int dd_data_size, uint32_t conn_idx) { struct iscsi_conn *conn; struct iscsi_cls_conn *cls_conn; struct iscsi_tcp_conn *tcp_conn; cls_conn = iscsi_conn_setup(cls_session, sizeof(*tcp_conn), conn_idx); if (!cls_conn) return NULL; conn = cls_conn->dd_data; /* * due to strange issues with iser these are not set * in iscsi_conn_setup */ conn->max_recv_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN; tcp_conn = conn->dd_data; tcp_conn->iscsi_conn = conn; tcp_conn->dd_data = kzalloc(dd_data_size, GFP_KERNEL); if (!tcp_conn->dd_data) { iscsi_conn_teardown(cls_conn); return NULL; } return cls_conn; } EXPORT_SYMBOL_GPL(iscsi_tcp_conn_setup); void iscsi_tcp_conn_teardown(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_tcp_conn *tcp_conn = conn->dd_data; kfree(tcp_conn->dd_data); iscsi_conn_teardown(cls_conn); } EXPORT_SYMBOL_GPL(iscsi_tcp_conn_teardown); int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session) { int i; int cmd_i; /* * initialize per-task: R2T pool and xmit queue */ for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) { struct iscsi_task *task = session->cmds[cmd_i]; struct iscsi_tcp_task *tcp_task = task->dd_data; /* * pre-allocated x2 as much r2ts to handle race when * target acks DataOut faster than we data_xmit() queues * could replenish r2tqueue. */ /* R2T pool */ if (iscsi_pool_init(&tcp_task->r2tpool, session->max_r2t * 2, NULL, sizeof(struct iscsi_r2t_info))) { goto r2t_alloc_fail; } /* R2T xmit queue */ if (kfifo_alloc(&tcp_task->r2tqueue, session->max_r2t * 4 * sizeof(void*), GFP_KERNEL)) { iscsi_pool_free(&tcp_task->r2tpool); goto r2t_alloc_fail; } } return 0; r2t_alloc_fail: for (i = 0; i < cmd_i; i++) { struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; kfifo_free(&tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } return -ENOMEM; } EXPORT_SYMBOL_GPL(iscsi_tcp_r2tpool_alloc); void iscsi_tcp_r2tpool_free(struct iscsi_session *session) { int i; for (i = 0; i < session->cmds_max; i++) { struct iscsi_task *task = session->cmds[i]; struct iscsi_tcp_task *tcp_task = task->dd_data; kfifo_free(&tcp_task->r2tqueue); iscsi_pool_free(&tcp_task->r2tpool); } } EXPORT_SYMBOL_GPL(iscsi_tcp_r2tpool_free); void iscsi_tcp_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats) { struct iscsi_conn *conn = cls_conn->dd_data; stats->txdata_octets = conn->txdata_octets; stats->rxdata_octets = conn->rxdata_octets; stats->scsicmd_pdus = conn->scsicmd_pdus_cnt; stats->dataout_pdus = conn->dataout_pdus_cnt; stats->scsirsp_pdus = conn->scsirsp_pdus_cnt; stats->datain_pdus = conn->datain_pdus_cnt; stats->r2t_pdus = conn->r2t_pdus_cnt; stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt; stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt; } EXPORT_SYMBOL_GPL(iscsi_tcp_conn_get_stats); open-iscsi-2.0.873/kernel/libiscsi_tcp.h000066400000000000000000000102271175631155400200560ustar00rootroot00000000000000/* * iSCSI over TCP/IP Data-Path lib * * Copyright (C) 2008 Mike Christie * Copyright (C) 2008 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef LIBISCSI_TCP_H #define LIBISCSI_TCP_H #include "libiscsi.h" struct iscsi_tcp_conn; struct iscsi_segment; struct sk_buff; struct hash_desc; typedef int iscsi_segment_done_fn_t(struct iscsi_tcp_conn *, struct iscsi_segment *); struct iscsi_segment { unsigned char *data; unsigned int size; unsigned int copied; unsigned int total_size; unsigned int total_copied; struct hash_desc *hash; unsigned char padbuf[ISCSI_PAD_LEN]; unsigned char recv_digest[ISCSI_DIGEST_SIZE]; unsigned char digest[ISCSI_DIGEST_SIZE]; unsigned int digest_len; struct scatterlist *sg; void *sg_mapped; unsigned int sg_offset; iscsi_segment_done_fn_t *done; }; /* Socket connection recieve helper */ struct iscsi_tcp_recv { struct iscsi_hdr *hdr; struct iscsi_segment segment; /* Allocate buffer for BHS + AHS */ uint32_t hdr_buf[64]; /* copied and flipped values */ int datalen; }; struct iscsi_tcp_conn { struct iscsi_conn *iscsi_conn; void *dd_data; int stop_stage; /* conn_stop() flag: * * stop to recover, * * stop to terminate */ /* control data */ struct iscsi_tcp_recv in; /* TCP receive context */ /* CRC32C (Rx) LLD should set this is they do not offload */ struct hash_desc *rx_hash; }; struct iscsi_tcp_task { uint32_t exp_datasn; /* expected target's R2TSN/DataSN */ int data_offset; struct iscsi_r2t_info *r2t; /* in progress solict R2T */ struct iscsi_pool r2tpool; struct kfifo r2tqueue; void *dd_data; }; enum { ISCSI_TCP_SEGMENT_DONE, /* curr seg has been processed */ ISCSI_TCP_SKB_DONE, /* skb is out of data */ ISCSI_TCP_CONN_ERR, /* iscsi layer has fired a conn err */ ISCSI_TCP_SUSPENDED, /* conn is suspended */ }; extern void iscsi_tcp_hdr_recv_prep(struct iscsi_tcp_conn *tcp_conn); extern int iscsi_tcp_recv_skb(struct iscsi_conn *conn, struct sk_buff *skb, unsigned int offset, bool offloaded, int *status); extern void iscsi_tcp_cleanup_task(struct iscsi_task *task); extern int iscsi_tcp_task_init(struct iscsi_task *task); extern int iscsi_tcp_task_xmit(struct iscsi_task *task); /* segment helpers */ extern int iscsi_tcp_recv_segment_is_hdr(struct iscsi_tcp_conn *tcp_conn); extern int iscsi_tcp_segment_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment, int recv, unsigned copied); extern void iscsi_tcp_segment_unmap(struct iscsi_segment *segment); extern void iscsi_segment_init_linear(struct iscsi_segment *segment, void *data, size_t size, iscsi_segment_done_fn_t *done, struct hash_desc *hash); extern int iscsi_segment_seek_sg(struct iscsi_segment *segment, struct scatterlist *sg_list, unsigned int sg_count, unsigned int offset, size_t size, iscsi_segment_done_fn_t *done, struct hash_desc *hash); /* digest helpers */ extern void iscsi_tcp_dgst_header(struct hash_desc *hash, const void *hdr, size_t hdrlen, unsigned char digest[ISCSI_DIGEST_SIZE]); extern struct iscsi_cls_conn * iscsi_tcp_conn_setup(struct iscsi_cls_session *cls_session, int dd_data_size, uint32_t conn_idx); extern void iscsi_tcp_conn_teardown(struct iscsi_cls_conn *cls_conn); /* misc helpers */ extern int iscsi_tcp_r2tpool_alloc(struct iscsi_session *session); extern void iscsi_tcp_r2tpool_free(struct iscsi_session *session); extern void iscsi_tcp_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats); #endif /* LIBISCSI_TCP_H */ open-iscsi-2.0.873/kernel/scsi_transport_iscsi.c000066400000000000000000001642661175631155400216660ustar00rootroot00000000000000/* * iSCSI transport class definitions * * Copyright (C) IBM Corporation, 2004 * Copyright (C) Mike Christie, 2004 - 2005 * Copyright (C) Dmitry Yusupov, 2004 - 2005 * Copyright (C) Alex Aizman, 2004 - 2005 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include #include #include #include #include #include #include #include #include "scsi_transport_iscsi.h" #include "iscsi_if.h" #define ISCSI_SESSION_ATTRS 22 #define ISCSI_CONN_ATTRS 13 #define ISCSI_HOST_ATTRS 4 #define ISCSI_TRANSPORT_VERSION "2.0-871" static int dbg_session; module_param_named(debug_session, dbg_session, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_session, "Turn on debugging for sessions in scsi_transport_iscsi " "module. Set to 1 to turn on, and zero to turn off. Default " "is off."); static int dbg_conn; module_param_named(debug_conn, dbg_conn, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_conn, "Turn on debugging for connections in scsi_transport_iscsi " "module. Set to 1 to turn on, and zero to turn off. Default " "is off."); #define ISCSI_DBG_TRANS_SESSION(_session, dbg_fmt, arg...) \ do { \ if (dbg_session) \ iscsi_cls_session_printk(KERN_INFO, _session, \ "%s: " dbg_fmt, \ __func__, ##arg); \ } while (0); #define ISCSI_DBG_TRANS_CONN(_conn, dbg_fmt, arg...) \ do { \ if (dbg_conn) \ iscsi_cls_conn_printk(KERN_INFO, _conn, \ "%s: " dbg_fmt, \ __func__, ##arg); \ } while (0); struct iscsi_internal { struct scsi_transport_template t; struct iscsi_transport *iscsi_transport; struct list_head list; struct device dev; struct device_attribute *host_attrs[ISCSI_HOST_ATTRS + 1]; struct transport_container conn_cont; struct device_attribute *conn_attrs[ISCSI_CONN_ATTRS + 1]; struct transport_container session_cont; struct device_attribute *session_attrs[ISCSI_SESSION_ATTRS + 1]; }; static atomic_t iscsi_session_nr; /* sysfs session id for next new session */ static struct workqueue_struct *iscsi_eh_timer_workq; /* * list of registered transports and lock that must * be held while accessing list. The iscsi_transport_lock must * be acquired after the rx_queue_mutex. */ static LIST_HEAD(iscsi_transports); static DEFINE_SPINLOCK(iscsi_transport_lock); #define to_iscsi_internal(tmpl) \ container_of(tmpl, struct iscsi_internal, t) #define dev_to_iscsi_internal(_dev) \ container_of(_dev, struct iscsi_internal, dev) static void iscsi_transport_release(struct device *dev) { struct iscsi_internal *priv = dev_to_iscsi_internal(dev); kfree(priv); } /* * iscsi_transport_class represents the iscsi_transports that are * registered. */ static struct class iscsi_transport_class = { .name = "iscsi_transport", .dev_release = iscsi_transport_release, }; static ssize_t show_transport_handle(struct device *dev, struct device_attribute *attr, char *buf) { struct iscsi_internal *priv = dev_to_iscsi_internal(dev); return sprintf(buf, "%llu\n", (unsigned long long)iscsi_handle(priv->iscsi_transport)); } static DEVICE_ATTR(handle, S_IRUGO, show_transport_handle, NULL); #define show_transport_attr(name, format) \ static ssize_t \ show_transport_##name(struct device *dev, \ struct device_attribute *attr,char *buf) \ { \ struct iscsi_internal *priv = dev_to_iscsi_internal(dev); \ return sprintf(buf, format"\n", priv->iscsi_transport->name); \ } \ static DEVICE_ATTR(name, S_IRUGO, show_transport_##name, NULL); show_transport_attr(caps, "0x%x"); static struct attribute *iscsi_transport_attrs[] = { &dev_attr_handle.attr, &dev_attr_caps.attr, NULL, }; static struct attribute_group iscsi_transport_group = { .attrs = iscsi_transport_attrs, }; /* * iSCSI endpoint attrs */ #define iscsi_dev_to_endpoint(_dev) \ container_of(_dev, struct iscsi_endpoint, dev) #define ISCSI_ATTR(_prefix,_name,_mode,_show,_store) \ struct device_attribute dev_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) static void iscsi_endpoint_release(struct device *dev) { struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); kfree(ep); } static struct class iscsi_endpoint_class = { .name = "iscsi_endpoint", .dev_release = iscsi_endpoint_release, }; static ssize_t show_ep_handle(struct device *dev, struct device_attribute *attr, char *buf) { struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); return sprintf(buf, "%llu\n", (unsigned long long) ep->id); } static ISCSI_ATTR(ep, handle, S_IRUGO, show_ep_handle, NULL); static struct attribute *iscsi_endpoint_attrs[] = { &dev_attr_ep_handle.attr, NULL, }; static struct attribute_group iscsi_endpoint_group = { .attrs = iscsi_endpoint_attrs, }; #define ISCSI_MAX_EPID -1 static int iscsi_match_epid(struct device *dev, void *data) { struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); uint64_t *epid = (uint64_t *) data; return *epid == ep->id; } struct iscsi_endpoint * iscsi_create_endpoint(int dd_size) { struct device *dev; struct iscsi_endpoint *ep; uint64_t id; int err; for (id = 1; id < ISCSI_MAX_EPID; id++) { dev = class_find_device(&iscsi_endpoint_class, NULL, &id, iscsi_match_epid); if (!dev) break; } if (id == ISCSI_MAX_EPID) { printk(KERN_ERR "Too many connections. Max supported %u\n", ISCSI_MAX_EPID - 1); return NULL; } ep = kzalloc(sizeof(*ep) + dd_size, GFP_KERNEL); if (!ep) return NULL; ep->id = id; ep->dev.class = &iscsi_endpoint_class; dev_set_name(&ep->dev, "ep-%llu", (unsigned long long) id); err = device_register(&ep->dev); if (err) goto free_ep; err = sysfs_create_group(&ep->dev.kobj, &iscsi_endpoint_group); if (err) goto unregister_dev; if (dd_size) ep->dd_data = &ep[1]; return ep; unregister_dev: device_unregister(&ep->dev); return NULL; free_ep: kfree(ep); return NULL; } EXPORT_SYMBOL_GPL(iscsi_create_endpoint); void iscsi_destroy_endpoint(struct iscsi_endpoint *ep) { sysfs_remove_group(&ep->dev.kobj, &iscsi_endpoint_group); device_unregister(&ep->dev); } EXPORT_SYMBOL_GPL(iscsi_destroy_endpoint); struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle) { struct iscsi_endpoint *ep; struct device *dev; dev = class_find_device(&iscsi_endpoint_class, NULL, &handle, iscsi_match_epid); if (!dev) return NULL; ep = iscsi_dev_to_endpoint(dev); /* * we can drop this now because the interface will prevent * removals and lookups from racing. */ put_device(dev); return ep; } EXPORT_SYMBOL_GPL(iscsi_lookup_endpoint); static int iscsi_setup_host(struct transport_container *tc, struct device *dev, struct device *cdev) { struct Scsi_Host *shost = dev_to_shost(dev); struct iscsi_cls_host *ihost = shost->shost_data; memset(ihost, 0, sizeof(*ihost)); atomic_set(&ihost->nr_scans, 0); mutex_init(&ihost->mutex); return 0; } static DECLARE_TRANSPORT_CLASS(iscsi_host_class, "iscsi_host", iscsi_setup_host, NULL, NULL); static DECLARE_TRANSPORT_CLASS(iscsi_session_class, "iscsi_session", NULL, NULL, NULL); static DECLARE_TRANSPORT_CLASS(iscsi_connection_class, "iscsi_connection", NULL, NULL, NULL); static struct sock *nls; static DEFINE_MUTEX(rx_queue_mutex); static LIST_HEAD(sesslist); static DEFINE_SPINLOCK(sesslock); static LIST_HEAD(connlist); static DEFINE_SPINLOCK(connlock); static uint32_t iscsi_conn_get_sid(struct iscsi_cls_conn *conn) { struct iscsi_cls_session *sess = iscsi_dev_to_session(conn->dev.parent); return sess->sid; } /* * Returns the matching session to a given sid */ static struct iscsi_cls_session *iscsi_session_lookup(uint32_t sid) { unsigned long flags; struct iscsi_cls_session *sess; spin_lock_irqsave(&sesslock, flags); list_for_each_entry(sess, &sesslist, sess_list) { if (sess->sid == sid) { spin_unlock_irqrestore(&sesslock, flags); return sess; } } spin_unlock_irqrestore(&sesslock, flags); return NULL; } /* * Returns the matching connection to a given sid / cid tuple */ static struct iscsi_cls_conn *iscsi_conn_lookup(uint32_t sid, uint32_t cid) { unsigned long flags; struct iscsi_cls_conn *conn; spin_lock_irqsave(&connlock, flags); list_for_each_entry(conn, &connlist, conn_list) { if ((conn->cid == cid) && (iscsi_conn_get_sid(conn) == sid)) { spin_unlock_irqrestore(&connlock, flags); return conn; } } spin_unlock_irqrestore(&connlock, flags); return NULL; } /* * The following functions can be used by LLDs that allocate * their own scsi_hosts or by software iscsi LLDs */ static struct { int value; char *name; } iscsi_session_state_names[] = { { ISCSI_SESSION_LOGGED_IN, "LOGGED_IN" }, { ISCSI_SESSION_FAILED, "FAILED" }, { ISCSI_SESSION_FREE, "FREE" }, }; static const char *iscsi_session_state_name(int state) { int i; char *name = NULL; for (i = 0; i < ARRAY_SIZE(iscsi_session_state_names); i++) { if (iscsi_session_state_names[i].value == state) { name = iscsi_session_state_names[i].name; break; } } return name; } int iscsi_session_chkready(struct iscsi_cls_session *session) { unsigned long flags; int err; spin_lock_irqsave(&session->lock, flags); switch (session->state) { case ISCSI_SESSION_LOGGED_IN: err = 0; break; case ISCSI_SESSION_FAILED: err = DID_IMM_RETRY << 16; break; case ISCSI_SESSION_FREE: err = DID_TRANSPORT_FAILFAST << 16; break; default: err = DID_NO_CONNECT << 16; break; } spin_unlock_irqrestore(&session->lock, flags); return err; } EXPORT_SYMBOL_GPL(iscsi_session_chkready); static void iscsi_session_release(struct device *dev) { struct iscsi_cls_session *session = iscsi_dev_to_session(dev); struct Scsi_Host *shost; shost = iscsi_session_to_shost(session); scsi_host_put(shost); ISCSI_DBG_TRANS_SESSION(session, "Completing session release\n"); kfree(session); } static int iscsi_is_session_dev(const struct device *dev) { return dev->release == iscsi_session_release; } static int iscsi_iter_session_fn(struct device *dev, void *data) { void (* fn) (struct iscsi_cls_session *) = data; if (!iscsi_is_session_dev(dev)) return 0; fn(iscsi_dev_to_session(dev)); return 0; } void iscsi_host_for_each_session(struct Scsi_Host *shost, void (*fn)(struct iscsi_cls_session *)) { device_for_each_child(&shost->shost_gendev, fn, iscsi_iter_session_fn); } EXPORT_SYMBOL_GPL(iscsi_host_for_each_session); /** * iscsi_scan_finished - helper to report when running scans are done * @shost: scsi host * @time: scan run time * * This function can be used by drives like qla4xxx to report to the scsi * layer when the scans it kicked off at module load time are done. */ int iscsi_scan_finished(struct Scsi_Host *shost, unsigned long time) { struct iscsi_cls_host *ihost = shost->shost_data; /* * qla4xxx will have kicked off some session unblocks before calling * scsi_scan_host, so just wait for them to complete. */ return !atomic_read(&ihost->nr_scans); } EXPORT_SYMBOL_GPL(iscsi_scan_finished); struct iscsi_scan_data { unsigned int channel; unsigned int id; unsigned int lun; }; static int iscsi_user_scan_session(struct device *dev, void *data) { struct iscsi_scan_data *scan_data = data; struct iscsi_cls_session *session; struct Scsi_Host *shost; struct iscsi_cls_host *ihost; unsigned long flags; unsigned int id; if (!iscsi_is_session_dev(dev)) return 0; session = iscsi_dev_to_session(dev); ISCSI_DBG_TRANS_SESSION(session, "Scanning session\n"); shost = iscsi_session_to_shost(session); ihost = shost->shost_data; mutex_lock(&ihost->mutex); spin_lock_irqsave(&session->lock, flags); if (session->state != ISCSI_SESSION_LOGGED_IN) { spin_unlock_irqrestore(&session->lock, flags); goto user_scan_exit; } id = session->target_id; spin_unlock_irqrestore(&session->lock, flags); if (id != ISCSI_MAX_TARGET) { if ((scan_data->channel == SCAN_WILD_CARD || scan_data->channel == 0) && (scan_data->id == SCAN_WILD_CARD || scan_data->id == id)) scsi_scan_target(&session->dev, 0, id, scan_data->lun, 1); } user_scan_exit: mutex_unlock(&ihost->mutex); ISCSI_DBG_TRANS_SESSION(session, "Completed session scan\n"); return 0; } static int iscsi_user_scan(struct Scsi_Host *shost, uint channel, uint id, uint lun) { struct iscsi_scan_data scan_data; scan_data.channel = channel; scan_data.id = id; scan_data.lun = lun; return device_for_each_child(&shost->shost_gendev, &scan_data, iscsi_user_scan_session); } static void iscsi_scan_session(struct work_struct *work) { struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, scan_work); struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; struct iscsi_scan_data scan_data; scan_data.channel = 0; scan_data.id = SCAN_WILD_CARD; scan_data.lun = SCAN_WILD_CARD; iscsi_user_scan_session(&session->dev, &scan_data); atomic_dec(&ihost->nr_scans); } static void session_recovery_timedout(struct work_struct *work) { struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, recovery_work.work); unsigned long flags; iscsi_cls_session_printk(KERN_INFO, session, "session recovery timed out after %d secs\n", session->recovery_tmo); spin_lock_irqsave(&session->lock, flags); switch (session->state) { case ISCSI_SESSION_FAILED: session->state = ISCSI_SESSION_FREE; break; case ISCSI_SESSION_LOGGED_IN: case ISCSI_SESSION_FREE: /* we raced with the unblock's flush */ spin_unlock_irqrestore(&session->lock, flags); return; } spin_unlock_irqrestore(&session->lock, flags); if (session->transport->session_recovery_timedout) session->transport->session_recovery_timedout(session); ISCSI_DBG_TRANS_SESSION(session, "Unblocking SCSI target\n"); scsi_target_unblock(&session->dev); ISCSI_DBG_TRANS_SESSION(session, "Completed unblocking SCSI target\n"); } static void __iscsi_unblock_session(struct work_struct *work) { struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, unblock_work); struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; ISCSI_DBG_TRANS_SESSION(session, "Unblocking session\n"); /* * The recovery and unblock work get run from the same workqueue, * so try to cancel it if it was going to run after this unblock. */ cancel_delayed_work(&session->recovery_work); spin_lock_irqsave(&session->lock, flags); session->state = ISCSI_SESSION_LOGGED_IN; spin_unlock_irqrestore(&session->lock, flags); /* start IO */ scsi_target_unblock(&session->dev); /* * Only do kernel scanning if the driver is properly hooked into * the async scanning code (drivers like iscsi_tcp do login and * scanning from userspace). */ if (shost->hostt->scan_finished) { if (scsi_queue_work(shost, &session->scan_work)) atomic_inc(&ihost->nr_scans); } ISCSI_DBG_TRANS_SESSION(session, "Completed unblocking session\n"); } /** * iscsi_unblock_session - set a session as logged in and start IO. * @session: iscsi session * * Mark a session as ready to accept IO. */ void iscsi_unblock_session(struct iscsi_cls_session *session) { queue_work(iscsi_eh_timer_workq, &session->unblock_work); /* * make sure all the events have completed before tell the driver * it is safe */ flush_workqueue(iscsi_eh_timer_workq); } EXPORT_SYMBOL_GPL(iscsi_unblock_session); static void __iscsi_block_session(struct work_struct *work) { struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, block_work); unsigned long flags; ISCSI_DBG_TRANS_SESSION(session, "Blocking session\n"); spin_lock_irqsave(&session->lock, flags); session->state = ISCSI_SESSION_FAILED; spin_unlock_irqrestore(&session->lock, flags); scsi_target_block(&session->dev); ISCSI_DBG_TRANS_SESSION(session, "Completed SCSI target blocking\n"); if (session->recovery_tmo >= 0) queue_delayed_work(iscsi_eh_timer_workq, &session->recovery_work, session->recovery_tmo * HZ); } void iscsi_block_session(struct iscsi_cls_session *session) { queue_work(iscsi_eh_timer_workq, &session->block_work); } EXPORT_SYMBOL_GPL(iscsi_block_session); static void __iscsi_unbind_session(struct work_struct *work) { struct iscsi_cls_session *session = container_of(work, struct iscsi_cls_session, unbind_work); struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost = shost->shost_data; unsigned long flags; ISCSI_DBG_TRANS_SESSION(session, "Unbinding session\n"); /* Prevent new scans and make sure scanning is not in progress */ mutex_lock(&ihost->mutex); spin_lock_irqsave(&session->lock, flags); if (session->target_id == ISCSI_MAX_TARGET) { spin_unlock_irqrestore(&session->lock, flags); mutex_unlock(&ihost->mutex); return; } session->target_id = ISCSI_MAX_TARGET; spin_unlock_irqrestore(&session->lock, flags); mutex_unlock(&ihost->mutex); scsi_remove_target(&session->dev); iscsi_session_event(session, ISCSI_KEVENT_UNBIND_SESSION); ISCSI_DBG_TRANS_SESSION(session, "Completed target removal\n"); } struct iscsi_cls_session * iscsi_alloc_session(struct Scsi_Host *shost, struct iscsi_transport *transport, int dd_size) { struct iscsi_cls_session *session; session = kzalloc(sizeof(*session) + dd_size, GFP_KERNEL); if (!session) return NULL; session->transport = transport; session->recovery_tmo = 120; session->state = ISCSI_SESSION_FREE; INIT_DELAYED_WORK(&session->recovery_work, session_recovery_timedout); INIT_LIST_HEAD(&session->sess_list); INIT_WORK(&session->unblock_work, __iscsi_unblock_session); INIT_WORK(&session->block_work, __iscsi_block_session); INIT_WORK(&session->unbind_work, __iscsi_unbind_session); INIT_WORK(&session->scan_work, iscsi_scan_session); spin_lock_init(&session->lock); /* this is released in the dev's release function */ scsi_host_get(shost); session->dev.parent = &shost->shost_gendev; session->dev.release = iscsi_session_release; device_initialize(&session->dev); if (dd_size) session->dd_data = &session[1]; ISCSI_DBG_TRANS_SESSION(session, "Completed session allocation\n"); return session; } EXPORT_SYMBOL_GPL(iscsi_alloc_session); static int iscsi_get_next_target_id(struct device *dev, void *data) { struct iscsi_cls_session *session; unsigned long flags; int err = 0; if (!iscsi_is_session_dev(dev)) return 0; session = iscsi_dev_to_session(dev); spin_lock_irqsave(&session->lock, flags); if (*((unsigned int *) data) == session->target_id) err = -EEXIST; spin_unlock_irqrestore(&session->lock, flags); return err; } int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id) { struct Scsi_Host *shost = iscsi_session_to_shost(session); struct iscsi_cls_host *ihost; unsigned long flags; unsigned int id = target_id; int err; ihost = shost->shost_data; session->sid = atomic_add_return(1, &iscsi_session_nr); if (id == ISCSI_MAX_TARGET) { for (id = 0; id < ISCSI_MAX_TARGET; id++) { err = device_for_each_child(&shost->shost_gendev, &id, iscsi_get_next_target_id); if (!err) break; } if (id == ISCSI_MAX_TARGET) { iscsi_cls_session_printk(KERN_ERR, session, "Too many iscsi targets. Max " "number of targets is %d.\n", ISCSI_MAX_TARGET - 1); err = -EOVERFLOW; goto release_host; } } session->target_id = id; dev_set_name(&session->dev, "session%u", session->sid); err = device_add(&session->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, "could not register session's dev\n"); goto release_host; } transport_register_device(&session->dev); spin_lock_irqsave(&sesslock, flags); list_add(&session->sess_list, &sesslist); spin_unlock_irqrestore(&sesslock, flags); iscsi_session_event(session, ISCSI_KEVENT_CREATE_SESSION); ISCSI_DBG_TRANS_SESSION(session, "Completed session adding\n"); return 0; release_host: scsi_host_put(shost); return err; } EXPORT_SYMBOL_GPL(iscsi_add_session); /** * iscsi_create_session - create iscsi class session * @shost: scsi host * @transport: iscsi transport * @dd_size: private driver data size * @target_id: which target * * This can be called from a LLD or iscsi_transport. */ struct iscsi_cls_session * iscsi_create_session(struct Scsi_Host *shost, struct iscsi_transport *transport, int dd_size, unsigned int target_id) { struct iscsi_cls_session *session; session = iscsi_alloc_session(shost, transport, dd_size); if (!session) return NULL; if (iscsi_add_session(session, target_id)) { iscsi_free_session(session); return NULL; } return session; } EXPORT_SYMBOL_GPL(iscsi_create_session); static void iscsi_conn_release(struct device *dev) { struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev); struct device *parent = conn->dev.parent; ISCSI_DBG_TRANS_CONN(conn, "Releasing conn\n"); kfree(conn); put_device(parent); } static int iscsi_is_conn_dev(const struct device *dev) { return dev->release == iscsi_conn_release; } static int iscsi_iter_destroy_conn_fn(struct device *dev, void *data) { if (!iscsi_is_conn_dev(dev)) return 0; return iscsi_destroy_conn(iscsi_dev_to_conn(dev)); } void iscsi_remove_session(struct iscsi_cls_session *session) { struct Scsi_Host *shost = iscsi_session_to_shost(session); unsigned long flags; int err; ISCSI_DBG_TRANS_SESSION(session, "Removing session\n"); spin_lock_irqsave(&sesslock, flags); list_del(&session->sess_list); spin_unlock_irqrestore(&sesslock, flags); /* make sure there are no blocks/unblocks queued */ flush_workqueue(iscsi_eh_timer_workq); /* make sure the timedout callout is not running */ if (!cancel_delayed_work(&session->recovery_work)) flush_workqueue(iscsi_eh_timer_workq); /* * If we are blocked let commands flow again. The lld or iscsi * layer should set up the queuecommand to fail commands. * We assume that LLD will not be calling block/unblock while * removing the session. */ spin_lock_irqsave(&session->lock, flags); session->state = ISCSI_SESSION_FREE; spin_unlock_irqrestore(&session->lock, flags); scsi_target_unblock(&session->dev); /* flush running scans then delete devices */ scsi_flush_work(shost); __iscsi_unbind_session(&session->unbind_work); /* hw iscsi may not have removed all connections from session */ err = device_for_each_child(&session->dev, NULL, iscsi_iter_destroy_conn_fn); if (err) iscsi_cls_session_printk(KERN_ERR, session, "Could not delete all connections " "for session. Error %d.\n", err); transport_unregister_device(&session->dev); ISCSI_DBG_TRANS_SESSION(session, "Completing session removal\n"); device_del(&session->dev); } EXPORT_SYMBOL_GPL(iscsi_remove_session); void iscsi_free_session(struct iscsi_cls_session *session) { ISCSI_DBG_TRANS_SESSION(session, "Freeing session\n"); iscsi_session_event(session, ISCSI_KEVENT_DESTROY_SESSION); put_device(&session->dev); } EXPORT_SYMBOL_GPL(iscsi_free_session); /** * iscsi_destroy_session - destroy iscsi session * @session: iscsi_session * * Can be called by a LLD or iscsi_transport. There must not be * any running connections. */ int iscsi_destroy_session(struct iscsi_cls_session *session) { iscsi_remove_session(session); ISCSI_DBG_TRANS_SESSION(session, "Completing session destruction\n"); iscsi_free_session(session); return 0; } EXPORT_SYMBOL_GPL(iscsi_destroy_session); /** * iscsi_create_conn - create iscsi class connection * @session: iscsi cls session * @dd_size: private driver data size * @cid: connection id * * This can be called from a LLD or iscsi_transport. The connection * is child of the session so cid must be unique for all connections * on the session. * * Since we do not support MCS, cid will normally be zero. In some cases * for software iscsi we could be trying to preallocate a connection struct * in which case there could be two connection structs and cid would be * non-zero. */ struct iscsi_cls_conn * iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid) { struct iscsi_transport *transport = session->transport; struct iscsi_cls_conn *conn; unsigned long flags; int err; conn = kzalloc(sizeof(*conn) + dd_size, GFP_KERNEL); if (!conn) return NULL; if (dd_size) conn->dd_data = &conn[1]; INIT_LIST_HEAD(&conn->conn_list); conn->transport = transport; conn->cid = cid; /* this is released in the dev's release function */ if (!get_device(&session->dev)) goto free_conn; dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid); conn->dev.parent = &session->dev; conn->dev.release = iscsi_conn_release; err = device_register(&conn->dev); if (err) { iscsi_cls_session_printk(KERN_ERR, session, "could not " "register connection's dev\n"); goto release_parent_ref; } transport_register_device(&conn->dev); spin_lock_irqsave(&connlock, flags); list_add(&conn->conn_list, &connlist); conn->active = 1; spin_unlock_irqrestore(&connlock, flags); ISCSI_DBG_TRANS_CONN(conn, "Completed conn creation\n"); return conn; release_parent_ref: put_device(&session->dev); free_conn: kfree(conn); return NULL; } EXPORT_SYMBOL_GPL(iscsi_create_conn); /** * iscsi_destroy_conn - destroy iscsi class connection * @conn: iscsi cls session * * This can be called from a LLD or iscsi_transport. */ int iscsi_destroy_conn(struct iscsi_cls_conn *conn) { unsigned long flags; spin_lock_irqsave(&connlock, flags); conn->active = 0; list_del(&conn->conn_list); spin_unlock_irqrestore(&connlock, flags); transport_unregister_device(&conn->dev); ISCSI_DBG_TRANS_CONN(conn, "Completing conn destruction\n"); device_unregister(&conn->dev); return 0; } EXPORT_SYMBOL_GPL(iscsi_destroy_conn); /* * iscsi interface functions */ static struct iscsi_internal * iscsi_if_transport_lookup(struct iscsi_transport *tt) { struct iscsi_internal *priv; unsigned long flags; spin_lock_irqsave(&iscsi_transport_lock, flags); list_for_each_entry(priv, &iscsi_transports, list) { if (tt == priv->iscsi_transport) { spin_unlock_irqrestore(&iscsi_transport_lock, flags); return priv; } } spin_unlock_irqrestore(&iscsi_transport_lock, flags); return NULL; } static int iscsi_multicast_skb(struct sk_buff *skb, uint32_t group, gfp_t gfp) { return nlmsg_multicast(nls, skb, 0, group, gfp); } int iscsi_recv_pdu(struct iscsi_cls_conn *conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size) { struct nlmsghdr *nlh; struct sk_buff *skb; struct iscsi_uevent *ev; char *pdu; struct iscsi_internal *priv; int len = NLMSG_SPACE(sizeof(*ev) + sizeof(struct iscsi_hdr) + data_size); priv = iscsi_if_transport_lookup(conn->transport); if (!priv) return -EINVAL; skb = alloc_skb(len, GFP_ATOMIC); if (!skb) { iscsi_conn_error_event(conn, ISCSI_ERR_CONN_FAILED); iscsi_cls_conn_printk(KERN_ERR, conn, "can not deliver " "control PDU: OOM\n"); return -ENOMEM; } nlh = __nlmsg_put(skb, 0, 0, 0, (len - sizeof(*nlh)), 0); ev = NLMSG_DATA(nlh); memset(ev, 0, sizeof(*ev)); ev->transport_handle = iscsi_handle(conn->transport); ev->type = ISCSI_KEVENT_RECV_PDU; ev->r.recv_req.cid = conn->cid; ev->r.recv_req.sid = iscsi_conn_get_sid(conn); pdu = (char*)ev + sizeof(*ev); memcpy(pdu, hdr, sizeof(struct iscsi_hdr)); memcpy(pdu + sizeof(struct iscsi_hdr), data, data_size); return iscsi_multicast_skb(skb, ISCSI_NL_GRP_ISCSID, GFP_ATOMIC); } EXPORT_SYMBOL_GPL(iscsi_recv_pdu); int iscsi_offload_mesg(struct Scsi_Host *shost, struct iscsi_transport *transport, uint32_t type, char *data, uint16_t data_size) { struct nlmsghdr *nlh; struct sk_buff *skb; struct iscsi_uevent *ev; int len = NLMSG_SPACE(sizeof(*ev) + data_size); skb = alloc_skb(len, GFP_ATOMIC); if (!skb) { printk(KERN_ERR "can not deliver iscsi offload message:OOM\n"); return -ENOMEM; } nlh = __nlmsg_put(skb, 0, 0, 0, (len - sizeof(*nlh)), 0); ev = NLMSG_DATA(nlh); memset(ev, 0, sizeof(*ev)); ev->type = type; ev->transport_handle = iscsi_handle(transport); switch (type) { case ISCSI_KEVENT_PATH_REQ: ev->r.req_path.host_no = shost->host_no; break; case ISCSI_KEVENT_IF_DOWN: ev->r.notify_if_down.host_no = shost->host_no; break; } memcpy((char *)ev + sizeof(*ev), data, data_size); return iscsi_multicast_skb(skb, ISCSI_NL_GRP_UIP, GFP_ATOMIC); } EXPORT_SYMBOL_GPL(iscsi_offload_mesg); void iscsi_conn_error_event(struct iscsi_cls_conn *conn, enum iscsi_err error) { struct nlmsghdr *nlh; struct sk_buff *skb; struct iscsi_uevent *ev; struct iscsi_internal *priv; int len = NLMSG_SPACE(sizeof(*ev)); priv = iscsi_if_transport_lookup(conn->transport); if (!priv) return; skb = alloc_skb(len, GFP_ATOMIC); if (!skb) { iscsi_cls_conn_printk(KERN_ERR, conn, "gracefully ignored " "conn error (%d)\n", error); return; } nlh = __nlmsg_put(skb, 0, 0, 0, (len - sizeof(*nlh)), 0); ev = NLMSG_DATA(nlh); ev->transport_handle = iscsi_handle(conn->transport); ev->type = ISCSI_KEVENT_CONN_ERROR; ev->r.connerror.error = error; ev->r.connerror.cid = conn->cid; ev->r.connerror.sid = iscsi_conn_get_sid(conn); iscsi_multicast_skb(skb, ISCSI_NL_GRP_ISCSID, GFP_ATOMIC); iscsi_cls_conn_printk(KERN_INFO, conn, "detected conn error (%d)\n", error); } EXPORT_SYMBOL_GPL(iscsi_conn_error_event); static int iscsi_if_send_reply(uint32_t group, int seq, int type, int done, int multi, void *payload, int size) { struct sk_buff *skb; struct nlmsghdr *nlh; int len = NLMSG_SPACE(size); int flags = multi ? NLM_F_MULTI : 0; int t = done ? NLMSG_DONE : type; skb = alloc_skb(len, GFP_ATOMIC); if (!skb) { printk(KERN_ERR "Could not allocate skb to send reply.\n"); return -ENOMEM; } nlh = __nlmsg_put(skb, 0, 0, t, (len - sizeof(*nlh)), 0); nlh->nlmsg_flags = flags; memcpy(NLMSG_DATA(nlh), payload, size); return iscsi_multicast_skb(skb, group, GFP_ATOMIC); } static int iscsi_if_get_stats(struct iscsi_transport *transport, struct nlmsghdr *nlh) { struct iscsi_uevent *ev = NLMSG_DATA(nlh); struct iscsi_stats *stats; struct sk_buff *skbstat; struct iscsi_cls_conn *conn; struct nlmsghdr *nlhstat; struct iscsi_uevent *evstat; struct iscsi_internal *priv; int len = NLMSG_SPACE(sizeof(*ev) + sizeof(struct iscsi_stats) + sizeof(struct iscsi_stats_custom) * ISCSI_STATS_CUSTOM_MAX); int err = 0; priv = iscsi_if_transport_lookup(transport); if (!priv) return -EINVAL; conn = iscsi_conn_lookup(ev->u.get_stats.sid, ev->u.get_stats.cid); if (!conn) return -EEXIST; do { int actual_size; skbstat = alloc_skb(len, GFP_ATOMIC); if (!skbstat) { iscsi_cls_conn_printk(KERN_ERR, conn, "can not " "deliver stats: OOM\n"); return -ENOMEM; } nlhstat = __nlmsg_put(skbstat, 0, 0, 0, (len - sizeof(*nlhstat)), 0); evstat = NLMSG_DATA(nlhstat); memset(evstat, 0, sizeof(*evstat)); evstat->transport_handle = iscsi_handle(conn->transport); evstat->type = nlh->nlmsg_type; evstat->u.get_stats.cid = ev->u.get_stats.cid; evstat->u.get_stats.sid = ev->u.get_stats.sid; stats = (struct iscsi_stats *) ((char*)evstat + sizeof(*evstat)); memset(stats, 0, sizeof(*stats)); transport->get_stats(conn, stats); actual_size = NLMSG_SPACE(sizeof(struct iscsi_uevent) + sizeof(struct iscsi_stats) + sizeof(struct iscsi_stats_custom) * stats->custom_length); actual_size -= sizeof(*nlhstat); actual_size = NLMSG_LENGTH(actual_size); skb_trim(skbstat, NLMSG_ALIGN(actual_size)); nlhstat->nlmsg_len = actual_size; err = iscsi_multicast_skb(skbstat, ISCSI_NL_GRP_ISCSID, GFP_ATOMIC); } while (err < 0 && err != -ECONNREFUSED); return err; } /** * iscsi_session_event - send session destr. completion event * @session: iscsi class session * @event: type of event */ int iscsi_session_event(struct iscsi_cls_session *session, enum iscsi_uevent_e event) { struct iscsi_internal *priv; struct Scsi_Host *shost; struct iscsi_uevent *ev; struct sk_buff *skb; struct nlmsghdr *nlh; int rc, len = NLMSG_SPACE(sizeof(*ev)); priv = iscsi_if_transport_lookup(session->transport); if (!priv) return -EINVAL; shost = iscsi_session_to_shost(session); skb = alloc_skb(len, GFP_KERNEL); if (!skb) { iscsi_cls_session_printk(KERN_ERR, session, "Cannot notify userspace of session " "event %u\n", event); return -ENOMEM; } nlh = __nlmsg_put(skb, 0, 0, 0, (len - sizeof(*nlh)), 0); ev = NLMSG_DATA(nlh); ev->transport_handle = iscsi_handle(session->transport); ev->type = event; switch (event) { case ISCSI_KEVENT_DESTROY_SESSION: ev->r.d_session.host_no = shost->host_no; ev->r.d_session.sid = session->sid; break; case ISCSI_KEVENT_CREATE_SESSION: ev->r.c_session_ret.host_no = shost->host_no; ev->r.c_session_ret.sid = session->sid; break; case ISCSI_KEVENT_UNBIND_SESSION: ev->r.unbind_session.host_no = shost->host_no; ev->r.unbind_session.sid = session->sid; break; default: iscsi_cls_session_printk(KERN_ERR, session, "Invalid event " "%u.\n", event); kfree_skb(skb); return -EINVAL; } /* * this will occur if the daemon is not up, so we just warn * the user and when the daemon is restarted it will handle it */ rc = iscsi_multicast_skb(skb, ISCSI_NL_GRP_ISCSID, GFP_KERNEL); if (rc == -ESRCH) iscsi_cls_session_printk(KERN_ERR, session, "Cannot notify userspace of session " "event %u. Check iscsi daemon\n", event); ISCSI_DBG_TRANS_SESSION(session, "Completed handling event %d rc %d\n", event, rc); return rc; } EXPORT_SYMBOL_GPL(iscsi_session_event); static int iscsi_if_create_session(struct iscsi_internal *priv, struct iscsi_endpoint *ep, struct iscsi_uevent *ev, uint32_t initial_cmdsn, uint16_t cmds_max, uint16_t queue_depth) { struct iscsi_transport *transport = priv->iscsi_transport; struct iscsi_cls_session *session; struct Scsi_Host *shost; session = transport->create_session(ep, cmds_max, queue_depth, initial_cmdsn); if (!session) return -ENOMEM; shost = iscsi_session_to_shost(session); ev->r.c_session_ret.host_no = shost->host_no; ev->r.c_session_ret.sid = session->sid; ISCSI_DBG_TRANS_SESSION(session, "Completed creating transport session\n"); return 0; } static int iscsi_if_create_conn(struct iscsi_transport *transport, struct iscsi_uevent *ev) { struct iscsi_cls_conn *conn; struct iscsi_cls_session *session; session = iscsi_session_lookup(ev->u.c_conn.sid); if (!session) { printk(KERN_ERR "iscsi: invalid session %d.\n", ev->u.c_conn.sid); return -EINVAL; } conn = transport->create_conn(session, ev->u.c_conn.cid); if (!conn) { iscsi_cls_session_printk(KERN_ERR, session, "couldn't create a new connection."); return -ENOMEM; } ev->r.c_conn_ret.sid = session->sid; ev->r.c_conn_ret.cid = conn->cid; ISCSI_DBG_TRANS_CONN(conn, "Completed creating transport conn\n"); return 0; } static int iscsi_if_destroy_conn(struct iscsi_transport *transport, struct iscsi_uevent *ev) { struct iscsi_cls_conn *conn; conn = iscsi_conn_lookup(ev->u.d_conn.sid, ev->u.d_conn.cid); if (!conn) return -EINVAL; ISCSI_DBG_TRANS_CONN(conn, "Destroying transport conn\n"); if (transport->destroy_conn) transport->destroy_conn(conn); return 0; } static int iscsi_set_param(struct iscsi_transport *transport, struct iscsi_uevent *ev) { char *data = (char*)ev + sizeof(*ev); struct iscsi_cls_conn *conn; struct iscsi_cls_session *session; int err = 0, value = 0; session = iscsi_session_lookup(ev->u.set_param.sid); conn = iscsi_conn_lookup(ev->u.set_param.sid, ev->u.set_param.cid); if (!conn || !session) return -EINVAL; switch (ev->u.set_param.param) { case ISCSI_PARAM_SESS_RECOVERY_TMO: sscanf(data, "%d", &value); session->recovery_tmo = value; break; default: err = transport->set_param(conn, ev->u.set_param.param, data, ev->u.set_param.len); } return err; } static int iscsi_if_ep_connect(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { struct iscsi_endpoint *ep; struct sockaddr *dst_addr; struct Scsi_Host *shost = NULL; int non_blocking, err = 0; if (!transport->ep_connect) return -EINVAL; if (msg_type == ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST) { shost = scsi_host_lookup(ev->u.ep_connect_through_host.host_no); if (!shost) { printk(KERN_ERR "ep connect failed. Could not find " "host no %u\n", ev->u.ep_connect_through_host.host_no); return -ENODEV; } non_blocking = ev->u.ep_connect_through_host.non_blocking; } else non_blocking = ev->u.ep_connect.non_blocking; dst_addr = (struct sockaddr *)((char*)ev + sizeof(*ev)); ep = transport->ep_connect(shost, dst_addr, non_blocking); if (IS_ERR(ep)) { err = PTR_ERR(ep); goto release_host; } ev->r.ep_connect_ret.handle = ep->id; release_host: if (shost) scsi_host_put(shost); return err; } static int iscsi_if_transport_ep(struct iscsi_transport *transport, struct iscsi_uevent *ev, int msg_type) { struct iscsi_endpoint *ep; int rc = 0; switch (msg_type) { case ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST: case ISCSI_UEVENT_TRANSPORT_EP_CONNECT: rc = iscsi_if_ep_connect(transport, ev, msg_type); break; case ISCSI_UEVENT_TRANSPORT_EP_POLL: if (!transport->ep_poll) return -EINVAL; ep = iscsi_lookup_endpoint(ev->u.ep_poll.ep_handle); if (!ep) return -EINVAL; ev->r.retcode = transport->ep_poll(ep, ev->u.ep_poll.timeout_ms); break; case ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT: if (!transport->ep_disconnect) return -EINVAL; ep = iscsi_lookup_endpoint(ev->u.ep_disconnect.ep_handle); if (!ep) return -EINVAL; transport->ep_disconnect(ep); break; } return rc; } static int iscsi_tgt_dscvr(struct iscsi_transport *transport, struct iscsi_uevent *ev) { struct Scsi_Host *shost; struct sockaddr *dst_addr; int err; if (!transport->tgt_dscvr) return -EINVAL; shost = scsi_host_lookup(ev->u.tgt_dscvr.host_no); if (!shost) { printk(KERN_ERR "target discovery could not find host no %u\n", ev->u.tgt_dscvr.host_no); return -ENODEV; } dst_addr = (struct sockaddr *)((char*)ev + sizeof(*ev)); err = transport->tgt_dscvr(shost, ev->u.tgt_dscvr.type, ev->u.tgt_dscvr.enable, dst_addr); scsi_host_put(shost); return err; } static int iscsi_set_host_param(struct iscsi_transport *transport, struct iscsi_uevent *ev) { char *data = (char*)ev + sizeof(*ev); struct Scsi_Host *shost; int err; if (!transport->set_host_param) return -ENOSYS; shost = scsi_host_lookup(ev->u.set_host_param.host_no); if (!shost) { printk(KERN_ERR "set_host_param could not find host no %u\n", ev->u.set_host_param.host_no); return -ENODEV; } err = transport->set_host_param(shost, ev->u.set_host_param.param, data, ev->u.set_host_param.len); scsi_host_put(shost); return err; } static int iscsi_set_path(struct iscsi_transport *transport, struct iscsi_uevent *ev) { struct Scsi_Host *shost; struct iscsi_path *params; int err; if (!transport->set_path) return -ENOSYS; shost = scsi_host_lookup(ev->u.set_path.host_no); if (!shost) { printk(KERN_ERR "set path could not find host no %u\n", ev->u.set_path.host_no); return -ENODEV; } params = (struct iscsi_path *)((char *)ev + sizeof(*ev)); err = transport->set_path(shost, params); scsi_host_put(shost); return err; } static int iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) { int err = 0; struct iscsi_uevent *ev = NLMSG_DATA(nlh); struct iscsi_transport *transport = NULL; struct iscsi_internal *priv; struct iscsi_cls_session *session; struct iscsi_cls_conn *conn; struct iscsi_endpoint *ep = NULL; if (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE) *group = ISCSI_NL_GRP_UIP; else *group = ISCSI_NL_GRP_ISCSID; priv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle)); if (!priv) return -EINVAL; transport = priv->iscsi_transport; if (!try_module_get(transport->owner)) return -EINVAL; switch (nlh->nlmsg_type) { case ISCSI_UEVENT_CREATE_SESSION: err = iscsi_if_create_session(priv, ep, ev, ev->u.c_session.initial_cmdsn, ev->u.c_session.cmds_max, ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; break; } err = iscsi_if_create_session(priv, ep, ev, ev->u.c_bound_session.initial_cmdsn, ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) transport->destroy_session(session); else err = -EINVAL; break; case ISCSI_UEVENT_UNBIND_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) scsi_queue_work(iscsi_session_to_shost(session), &session->unbind_work); else err = -EINVAL; break; case ISCSI_UEVENT_CREATE_CONN: err = iscsi_if_create_conn(transport, ev); break; case ISCSI_UEVENT_DESTROY_CONN: err = iscsi_if_destroy_conn(transport, ev); break; case ISCSI_UEVENT_BIND_CONN: session = iscsi_session_lookup(ev->u.b_conn.sid); conn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid); if (session && conn) ev->r.retcode = transport->bind_conn(session, conn, ev->u.b_conn.transport_eph, ev->u.b_conn.is_leading); else err = -EINVAL; break; case ISCSI_UEVENT_SET_PARAM: err = iscsi_set_param(transport, ev); break; case ISCSI_UEVENT_START_CONN: conn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid); if (conn) ev->r.retcode = transport->start_conn(conn); else err = -EINVAL; break; case ISCSI_UEVENT_STOP_CONN: conn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid); if (conn) transport->stop_conn(conn, ev->u.stop_conn.flag); else err = -EINVAL; break; case ISCSI_UEVENT_SEND_PDU: conn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid); if (conn) ev->r.retcode = transport->send_pdu(conn, (struct iscsi_hdr*)((char*)ev + sizeof(*ev)), (char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size, ev->u.send_pdu.data_size); else err = -EINVAL; break; case ISCSI_UEVENT_GET_STATS: err = iscsi_if_get_stats(transport, nlh); break; case ISCSI_UEVENT_TRANSPORT_EP_CONNECT: case ISCSI_UEVENT_TRANSPORT_EP_POLL: case ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT: case ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST: err = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type); break; case ISCSI_UEVENT_TGT_DSCVR: err = iscsi_tgt_dscvr(transport, ev); break; case ISCSI_UEVENT_SET_HOST_PARAM: err = iscsi_set_host_param(transport, ev); break; case ISCSI_UEVENT_PATH_UPDATE: err = iscsi_set_path(transport, ev); break; default: err = -ENOSYS; break; } module_put(transport->owner); return err; } /* * Get message from skb. Each message is processed by iscsi_if_recv_msg. * Malformed skbs with wrong lengths or invalid creds are not processed. */ static void iscsi_if_rx(struct sk_buff *skb) { mutex_lock(&rx_queue_mutex); while (skb->len >= NLMSG_SPACE(0)) { int err; uint32_t rlen; struct nlmsghdr *nlh; struct iscsi_uevent *ev; uint32_t group; nlh = nlmsg_hdr(skb); if (nlh->nlmsg_len < sizeof(*nlh) || skb->len < nlh->nlmsg_len) { break; } ev = NLMSG_DATA(nlh); rlen = NLMSG_ALIGN(nlh->nlmsg_len); if (rlen > skb->len) rlen = skb->len; err = iscsi_if_recv_msg(skb, nlh, &group); if (err) { ev->type = ISCSI_KEVENT_IF_ERROR; ev->iferror = err; } do { /* * special case for GET_STATS: * on success - sending reply and stats from * inside of if_recv_msg(), * on error - fall through. */ if (ev->type == ISCSI_UEVENT_GET_STATS && !err) break; err = iscsi_if_send_reply(group, nlh->nlmsg_seq, nlh->nlmsg_type, 0, 0, ev, sizeof(*ev)); } while (err < 0 && err != -ECONNREFUSED); skb_pull(skb, rlen); } mutex_unlock(&rx_queue_mutex); } #define ISCSI_CLASS_ATTR(_prefix,_name,_mode,_show,_store) \ struct device_attribute dev_attr_##_prefix##_##_name = \ __ATTR(_name,_mode,_show,_store) /* * iSCSI connection attrs */ #define iscsi_conn_attr_show(param) \ static ssize_t \ show_conn_param_##param(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct iscsi_cls_conn *conn = iscsi_dev_to_conn(dev->parent); \ struct iscsi_transport *t = conn->transport; \ return t->get_conn_param(conn, param, buf); \ } #define iscsi_conn_attr(field, param) \ iscsi_conn_attr_show(param) \ static ISCSI_CLASS_ATTR(conn, field, S_IRUGO, show_conn_param_##param, \ NULL); iscsi_conn_attr(max_recv_dlength, ISCSI_PARAM_MAX_RECV_DLENGTH); iscsi_conn_attr(max_xmit_dlength, ISCSI_PARAM_MAX_XMIT_DLENGTH); iscsi_conn_attr(header_digest, ISCSI_PARAM_HDRDGST_EN); iscsi_conn_attr(data_digest, ISCSI_PARAM_DATADGST_EN); iscsi_conn_attr(ifmarker, ISCSI_PARAM_IFMARKER_EN); iscsi_conn_attr(ofmarker, ISCSI_PARAM_OFMARKER_EN); iscsi_conn_attr(persistent_port, ISCSI_PARAM_PERSISTENT_PORT); iscsi_conn_attr(port, ISCSI_PARAM_CONN_PORT); iscsi_conn_attr(exp_statsn, ISCSI_PARAM_EXP_STATSN); iscsi_conn_attr(persistent_address, ISCSI_PARAM_PERSISTENT_ADDRESS); iscsi_conn_attr(address, ISCSI_PARAM_CONN_ADDRESS); iscsi_conn_attr(ping_tmo, ISCSI_PARAM_PING_TMO); iscsi_conn_attr(recv_tmo, ISCSI_PARAM_RECV_TMO); /* * iSCSI session attrs */ #define iscsi_session_attr_show(param, perm) \ static ssize_t \ show_session_param_##param(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct iscsi_cls_session *session = \ iscsi_dev_to_session(dev->parent); \ struct iscsi_transport *t = session->transport; \ \ if (perm && !capable(CAP_SYS_ADMIN)) \ return -EACCES; \ return t->get_session_param(session, param, buf); \ } #define iscsi_session_attr(field, param, perm) \ iscsi_session_attr_show(param, perm) \ static ISCSI_CLASS_ATTR(sess, field, S_IRUGO, show_session_param_##param, \ NULL); iscsi_session_attr(targetname, ISCSI_PARAM_TARGET_NAME, 0); iscsi_session_attr(initial_r2t, ISCSI_PARAM_INITIAL_R2T_EN, 0); iscsi_session_attr(max_outstanding_r2t, ISCSI_PARAM_MAX_R2T, 0); iscsi_session_attr(immediate_data, ISCSI_PARAM_IMM_DATA_EN, 0); iscsi_session_attr(first_burst_len, ISCSI_PARAM_FIRST_BURST, 0); iscsi_session_attr(max_burst_len, ISCSI_PARAM_MAX_BURST, 0); iscsi_session_attr(data_pdu_in_order, ISCSI_PARAM_PDU_INORDER_EN, 0); iscsi_session_attr(data_seq_in_order, ISCSI_PARAM_DATASEQ_INORDER_EN, 0); iscsi_session_attr(erl, ISCSI_PARAM_ERL, 0); iscsi_session_attr(tpgt, ISCSI_PARAM_TPGT, 0); iscsi_session_attr(username, ISCSI_PARAM_USERNAME, 1); iscsi_session_attr(username_in, ISCSI_PARAM_USERNAME_IN, 1); iscsi_session_attr(password, ISCSI_PARAM_PASSWORD, 1); iscsi_session_attr(password_in, ISCSI_PARAM_PASSWORD_IN, 1); iscsi_session_attr(fast_abort, ISCSI_PARAM_FAST_ABORT, 0); iscsi_session_attr(abort_tmo, ISCSI_PARAM_ABORT_TMO, 0); iscsi_session_attr(lu_reset_tmo, ISCSI_PARAM_LU_RESET_TMO, 0); iscsi_session_attr(tgt_reset_tmo, ISCSI_PARAM_TGT_RESET_TMO, 0); iscsi_session_attr(ifacename, ISCSI_PARAM_IFACE_NAME, 0); iscsi_session_attr(initiatorname, ISCSI_PARAM_INITIATOR_NAME, 0) static ssize_t show_priv_session_state(struct device *dev, struct device_attribute *attr, char *buf) { struct iscsi_cls_session *session = iscsi_dev_to_session(dev->parent); return sprintf(buf, "%s\n", iscsi_session_state_name(session->state)); } static ISCSI_CLASS_ATTR(priv_sess, state, S_IRUGO, show_priv_session_state, NULL); #define iscsi_priv_session_attr_show(field, format) \ static ssize_t \ show_priv_session_##field(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct iscsi_cls_session *session = \ iscsi_dev_to_session(dev->parent); \ return sprintf(buf, format"\n", session->field); \ } #define iscsi_priv_session_attr(field, format) \ iscsi_priv_session_attr_show(field, format) \ static ISCSI_CLASS_ATTR(priv_sess, field, S_IRUGO, show_priv_session_##field, \ NULL) iscsi_priv_session_attr(recovery_tmo, "%d"); /* * iSCSI host attrs */ #define iscsi_host_attr_show(param) \ static ssize_t \ show_host_param_##param(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct Scsi_Host *shost = transport_class_to_shost(dev); \ struct iscsi_internal *priv = to_iscsi_internal(shost->transportt); \ return priv->iscsi_transport->get_host_param(shost, param, buf); \ } #define iscsi_host_attr(field, param) \ iscsi_host_attr_show(param) \ static ISCSI_CLASS_ATTR(host, field, S_IRUGO, show_host_param_##param, \ NULL); iscsi_host_attr(netdev, ISCSI_HOST_PARAM_NETDEV_NAME); iscsi_host_attr(hwaddress, ISCSI_HOST_PARAM_HWADDRESS); iscsi_host_attr(ipaddress, ISCSI_HOST_PARAM_IPADDRESS); iscsi_host_attr(initiatorname, ISCSI_HOST_PARAM_INITIATOR_NAME); #define SETUP_PRIV_SESSION_RD_ATTR(field) \ do { \ priv->session_attrs[count] = &dev_attr_priv_sess_##field; \ count++; \ } while (0) #define SETUP_SESSION_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ priv->session_attrs[count] = &dev_attr_sess_##field; \ count++; \ } \ } while (0) #define SETUP_CONN_RD_ATTR(field, param_flag) \ do { \ if (tt->param_mask & param_flag) { \ priv->conn_attrs[count] = &dev_attr_conn_##field; \ count++; \ } \ } while (0) #define SETUP_HOST_RD_ATTR(field, param_flag) \ do { \ if (tt->host_param_mask & param_flag) { \ priv->host_attrs[count] = &dev_attr_host_##field; \ count++; \ } \ } while (0) static int iscsi_session_match(struct attribute_container *cont, struct device *dev) { struct iscsi_cls_session *session; struct Scsi_Host *shost; struct iscsi_internal *priv; if (!iscsi_is_session_dev(dev)) return 0; session = iscsi_dev_to_session(dev); shost = iscsi_session_to_shost(session); if (!shost->transportt) return 0; priv = to_iscsi_internal(shost->transportt); if (priv->session_cont.ac.class != &iscsi_session_class.class) return 0; return &priv->session_cont.ac == cont; } static int iscsi_conn_match(struct attribute_container *cont, struct device *dev) { struct iscsi_cls_session *session; struct iscsi_cls_conn *conn; struct Scsi_Host *shost; struct iscsi_internal *priv; if (!iscsi_is_conn_dev(dev)) return 0; conn = iscsi_dev_to_conn(dev); session = iscsi_dev_to_session(conn->dev.parent); shost = iscsi_session_to_shost(session); if (!shost->transportt) return 0; priv = to_iscsi_internal(shost->transportt); if (priv->conn_cont.ac.class != &iscsi_connection_class.class) return 0; return &priv->conn_cont.ac == cont; } static int iscsi_host_match(struct attribute_container *cont, struct device *dev) { struct Scsi_Host *shost; struct iscsi_internal *priv; if (!scsi_is_host_device(dev)) return 0; shost = dev_to_shost(dev); if (!shost->transportt || shost->transportt->host_attrs.ac.class != &iscsi_host_class.class) return 0; priv = to_iscsi_internal(shost->transportt); return &priv->t.host_attrs.ac == cont; } struct scsi_transport_template * iscsi_register_transport(struct iscsi_transport *tt) { struct iscsi_internal *priv; unsigned long flags; int count = 0, err; BUG_ON(!tt); priv = iscsi_if_transport_lookup(tt); if (priv) return NULL; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return NULL; INIT_LIST_HEAD(&priv->list); priv->iscsi_transport = tt; priv->t.user_scan = iscsi_user_scan; priv->t.create_work_queue = 1; priv->dev.class = &iscsi_transport_class; dev_set_name(&priv->dev, "%s", tt->name); err = device_register(&priv->dev); if (err) goto free_priv; err = sysfs_create_group(&priv->dev.kobj, &iscsi_transport_group); if (err) goto unregister_dev; /* host parameters */ priv->t.host_attrs.ac.attrs = &priv->host_attrs[0]; priv->t.host_attrs.ac.class = &iscsi_host_class.class; priv->t.host_attrs.ac.match = iscsi_host_match; priv->t.host_size = sizeof(struct iscsi_cls_host); transport_container_register(&priv->t.host_attrs); SETUP_HOST_RD_ATTR(netdev, ISCSI_HOST_NETDEV_NAME); SETUP_HOST_RD_ATTR(ipaddress, ISCSI_HOST_IPADDRESS); SETUP_HOST_RD_ATTR(hwaddress, ISCSI_HOST_HWADDRESS); SETUP_HOST_RD_ATTR(initiatorname, ISCSI_HOST_INITIATOR_NAME); BUG_ON(count > ISCSI_HOST_ATTRS); priv->host_attrs[count] = NULL; count = 0; /* connection parameters */ priv->conn_cont.ac.attrs = &priv->conn_attrs[0]; priv->conn_cont.ac.class = &iscsi_connection_class.class; priv->conn_cont.ac.match = iscsi_conn_match; transport_container_register(&priv->conn_cont); SETUP_CONN_RD_ATTR(max_recv_dlength, ISCSI_MAX_RECV_DLENGTH); SETUP_CONN_RD_ATTR(max_xmit_dlength, ISCSI_MAX_XMIT_DLENGTH); SETUP_CONN_RD_ATTR(header_digest, ISCSI_HDRDGST_EN); SETUP_CONN_RD_ATTR(data_digest, ISCSI_DATADGST_EN); SETUP_CONN_RD_ATTR(ifmarker, ISCSI_IFMARKER_EN); SETUP_CONN_RD_ATTR(ofmarker, ISCSI_OFMARKER_EN); SETUP_CONN_RD_ATTR(address, ISCSI_CONN_ADDRESS); SETUP_CONN_RD_ATTR(port, ISCSI_CONN_PORT); SETUP_CONN_RD_ATTR(exp_statsn, ISCSI_EXP_STATSN); SETUP_CONN_RD_ATTR(persistent_address, ISCSI_PERSISTENT_ADDRESS); SETUP_CONN_RD_ATTR(persistent_port, ISCSI_PERSISTENT_PORT); SETUP_CONN_RD_ATTR(ping_tmo, ISCSI_PING_TMO); SETUP_CONN_RD_ATTR(recv_tmo, ISCSI_RECV_TMO); BUG_ON(count > ISCSI_CONN_ATTRS); priv->conn_attrs[count] = NULL; count = 0; /* session parameters */ priv->session_cont.ac.attrs = &priv->session_attrs[0]; priv->session_cont.ac.class = &iscsi_session_class.class; priv->session_cont.ac.match = iscsi_session_match; transport_container_register(&priv->session_cont); SETUP_SESSION_RD_ATTR(initial_r2t, ISCSI_INITIAL_R2T_EN); SETUP_SESSION_RD_ATTR(max_outstanding_r2t, ISCSI_MAX_R2T); SETUP_SESSION_RD_ATTR(immediate_data, ISCSI_IMM_DATA_EN); SETUP_SESSION_RD_ATTR(first_burst_len, ISCSI_FIRST_BURST); SETUP_SESSION_RD_ATTR(max_burst_len, ISCSI_MAX_BURST); SETUP_SESSION_RD_ATTR(data_pdu_in_order, ISCSI_PDU_INORDER_EN); SETUP_SESSION_RD_ATTR(data_seq_in_order, ISCSI_DATASEQ_INORDER_EN); SETUP_SESSION_RD_ATTR(erl, ISCSI_ERL); SETUP_SESSION_RD_ATTR(targetname, ISCSI_TARGET_NAME); SETUP_SESSION_RD_ATTR(tpgt, ISCSI_TPGT); SETUP_SESSION_RD_ATTR(password, ISCSI_USERNAME); SETUP_SESSION_RD_ATTR(password_in, ISCSI_USERNAME_IN); SETUP_SESSION_RD_ATTR(username, ISCSI_PASSWORD); SETUP_SESSION_RD_ATTR(username_in, ISCSI_PASSWORD_IN); SETUP_SESSION_RD_ATTR(fast_abort, ISCSI_FAST_ABORT); SETUP_SESSION_RD_ATTR(abort_tmo, ISCSI_ABORT_TMO); SETUP_SESSION_RD_ATTR(lu_reset_tmo,ISCSI_LU_RESET_TMO); SETUP_SESSION_RD_ATTR(tgt_reset_tmo,ISCSI_TGT_RESET_TMO); SETUP_SESSION_RD_ATTR(ifacename, ISCSI_IFACE_NAME); SETUP_SESSION_RD_ATTR(initiatorname, ISCSI_INITIATOR_NAME); SETUP_PRIV_SESSION_RD_ATTR(recovery_tmo); SETUP_PRIV_SESSION_RD_ATTR(state); BUG_ON(count > ISCSI_SESSION_ATTRS); priv->session_attrs[count] = NULL; spin_lock_irqsave(&iscsi_transport_lock, flags); list_add(&priv->list, &iscsi_transports); spin_unlock_irqrestore(&iscsi_transport_lock, flags); printk(KERN_NOTICE "iscsi: registered transport (%s)\n", tt->name); return &priv->t; unregister_dev: device_unregister(&priv->dev); return NULL; free_priv: kfree(priv); return NULL; } EXPORT_SYMBOL_GPL(iscsi_register_transport); int iscsi_unregister_transport(struct iscsi_transport *tt) { struct iscsi_internal *priv; unsigned long flags; BUG_ON(!tt); mutex_lock(&rx_queue_mutex); priv = iscsi_if_transport_lookup(tt); BUG_ON (!priv); spin_lock_irqsave(&iscsi_transport_lock, flags); list_del(&priv->list); spin_unlock_irqrestore(&iscsi_transport_lock, flags); transport_container_unregister(&priv->conn_cont); transport_container_unregister(&priv->session_cont); transport_container_unregister(&priv->t.host_attrs); sysfs_remove_group(&priv->dev.kobj, &iscsi_transport_group); device_unregister(&priv->dev); mutex_unlock(&rx_queue_mutex); return 0; } EXPORT_SYMBOL_GPL(iscsi_unregister_transport); static __init int iscsi_transport_init(void) { int err; printk(KERN_INFO "Loading iSCSI transport class v%s.\n", ISCSI_TRANSPORT_VERSION); atomic_set(&iscsi_session_nr, 0); err = class_register(&iscsi_transport_class); if (err) return err; err = class_register(&iscsi_endpoint_class); if (err) goto unregister_transport_class; err = transport_class_register(&iscsi_host_class); if (err) goto unregister_endpoint_class; err = transport_class_register(&iscsi_connection_class); if (err) goto unregister_host_class; err = transport_class_register(&iscsi_session_class); if (err) goto unregister_conn_class; nls = netlink_kernel_create(&init_net, NETLINK_ISCSI, 1, iscsi_if_rx, NULL, THIS_MODULE); if (!nls) { err = -ENOBUFS; goto unregister_session_class; } iscsi_eh_timer_workq = create_singlethread_workqueue("iscsi_eh"); if (!iscsi_eh_timer_workq) goto release_nls; return 0; release_nls: netlink_kernel_release(nls); unregister_session_class: transport_class_unregister(&iscsi_session_class); unregister_conn_class: transport_class_unregister(&iscsi_connection_class); unregister_host_class: transport_class_unregister(&iscsi_host_class); unregister_endpoint_class: class_unregister(&iscsi_endpoint_class); unregister_transport_class: class_unregister(&iscsi_transport_class); return err; } static void __exit iscsi_transport_exit(void) { destroy_workqueue(iscsi_eh_timer_workq); netlink_kernel_release(nls); transport_class_unregister(&iscsi_connection_class); transport_class_unregister(&iscsi_session_class); transport_class_unregister(&iscsi_host_class); class_unregister(&iscsi_endpoint_class); class_unregister(&iscsi_transport_class); } module_init(iscsi_transport_init); module_exit(iscsi_transport_exit); MODULE_AUTHOR("Mike Christie , " "Dmitry Yusupov , " "Alex Aizman "); MODULE_DESCRIPTION("iSCSI Transport Interface"); MODULE_LICENSE("GPL"); MODULE_VERSION(ISCSI_TRANSPORT_VERSION); open-iscsi-2.0.873/kernel/scsi_transport_iscsi.h000066400000000000000000000230031175631155400216520ustar00rootroot00000000000000/* * iSCSI transport class definitions * * Copyright (C) IBM Corporation, 2004 * Copyright (C) Mike Christie, 2004 - 2006 * Copyright (C) Dmitry Yusupov, 2004 - 2005 * Copyright (C) Alex Aizman, 2004 - 2005 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SCSI_TRANSPORT_ISCSI_H #define SCSI_TRANSPORT_ISCSI_H #include #include #include #include "iscsi_if.h" struct scsi_transport_template; struct iscsi_transport; struct iscsi_endpoint; struct Scsi_Host; struct iscsi_cls_conn; struct iscsi_conn; struct iscsi_task; struct sockaddr; /** * struct iscsi_transport - iSCSI Transport template * * @name: transport name * @caps: iSCSI Data-Path capabilities * @create_session: create new iSCSI session object * @destroy_session: destroy existing iSCSI session object * @create_conn: create new iSCSI connection * @bind_conn: associate this connection with existing iSCSI session * and specified transport descriptor * @destroy_conn: destroy inactive iSCSI connection * @set_param: set iSCSI parameter. Return 0 on success, -ENODATA * when param is not supported, and a -Exx value on other * error. * @get_param get iSCSI parameter. Must return number of bytes * copied to buffer on success, -ENODATA when param * is not supported, and a -Exx value on other error * @start_conn: set connection to be operational * @stop_conn: suspend/recover/terminate connection * @send_pdu: send iSCSI PDU, Login, Logout, NOP-Out, Reject, Text. * @session_recovery_timedout: notify LLD a block during recovery timed out * @init_task: Initialize a iscsi_task and any internal structs. * When offloading the data path, this is called from * queuecommand with the session lock, or from the * iscsi_conn_send_pdu context with the session lock. * When not offloading the data path, this is called * from the scsi work queue without the session lock. * @xmit_task Requests LLD to transfer cmd task. Returns 0 or the * the number of bytes transferred on success, and -Exyz * value on error. When offloading the data path, this * is called from queuecommand with the session lock, or * from the iscsi_conn_send_pdu context with the session * lock. When not offloading the data path, this is called * from the scsi work queue without the session lock. * @cleanup_task: requests LLD to fail task. Called with session lock * and after the connection has been suspended and * terminated during recovery. If called * from abort task then connection is not suspended * or terminated but sk_callback_lock is held * * Template API provided by iSCSI Transport */ struct iscsi_transport { struct module *owner; char *name; unsigned int caps; /* LLD sets this to indicate what values it can export to sysfs */ uint64_t param_mask; uint64_t host_param_mask; struct iscsi_cls_session *(*create_session) (struct iscsi_endpoint *ep, uint16_t cmds_max, uint16_t qdepth, uint32_t sn); void (*destroy_session) (struct iscsi_cls_session *session); struct iscsi_cls_conn *(*create_conn) (struct iscsi_cls_session *sess, uint32_t cid); int (*bind_conn) (struct iscsi_cls_session *session, struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, int is_leading); int (*start_conn) (struct iscsi_cls_conn *conn); void (*stop_conn) (struct iscsi_cls_conn *conn, int flag); void (*destroy_conn) (struct iscsi_cls_conn *conn); int (*set_param) (struct iscsi_cls_conn *conn, enum iscsi_param param, char *buf, int buflen); int (*get_conn_param) (struct iscsi_cls_conn *conn, enum iscsi_param param, char *buf); int (*get_session_param) (struct iscsi_cls_session *session, enum iscsi_param param, char *buf); int (*get_host_param) (struct Scsi_Host *shost, enum iscsi_host_param param, char *buf); int (*set_host_param) (struct Scsi_Host *shost, enum iscsi_host_param param, char *buf, int buflen); int (*send_pdu) (struct iscsi_cls_conn *conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size); void (*get_stats) (struct iscsi_cls_conn *conn, struct iscsi_stats *stats); int (*init_task) (struct iscsi_task *task); int (*xmit_task) (struct iscsi_task *task); void (*cleanup_task) (struct iscsi_task *task); int (*alloc_pdu) (struct iscsi_task *task, uint8_t opcode); int (*xmit_pdu) (struct iscsi_task *task); int (*init_pdu) (struct iscsi_task *task, unsigned int offset, unsigned int count); void (*parse_pdu_itt) (struct iscsi_conn *conn, itt_t itt, int *index, int *age); void (*session_recovery_timedout) (struct iscsi_cls_session *session); struct iscsi_endpoint *(*ep_connect) (struct Scsi_Host *shost, struct sockaddr *dst_addr, int non_blocking); int (*ep_poll) (struct iscsi_endpoint *ep, int timeout_ms); void (*ep_disconnect) (struct iscsi_endpoint *ep); int (*tgt_dscvr) (struct Scsi_Host *shost, enum iscsi_tgt_dscvr type, uint32_t enable, struct sockaddr *dst_addr); int (*set_path) (struct Scsi_Host *shost, struct iscsi_path *params); }; /* * transport registration upcalls */ extern struct scsi_transport_template *iscsi_register_transport(struct iscsi_transport *tt); extern int iscsi_unregister_transport(struct iscsi_transport *tt); /* * control plane upcalls */ extern void iscsi_conn_error_event(struct iscsi_cls_conn *conn, enum iscsi_err error); extern int iscsi_recv_pdu(struct iscsi_cls_conn *conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size); extern int iscsi_offload_mesg(struct Scsi_Host *shost, struct iscsi_transport *transport, uint32_t type, char *data, uint16_t data_size); struct iscsi_cls_conn { struct list_head conn_list; /* item in connlist */ void *dd_data; /* LLD private data */ struct iscsi_transport *transport; uint32_t cid; /* connection id */ int active; /* must be accessed with the connlock */ struct device dev; /* sysfs transport/container device */ }; #define iscsi_dev_to_conn(_dev) \ container_of(_dev, struct iscsi_cls_conn, dev) #define iscsi_conn_to_session(_conn) \ iscsi_dev_to_session(_conn->dev.parent) /* iscsi class session state */ enum { ISCSI_SESSION_LOGGED_IN, ISCSI_SESSION_FAILED, ISCSI_SESSION_FREE, }; #define ISCSI_MAX_TARGET -1 struct iscsi_cls_session { struct list_head sess_list; /* item in session_list */ struct iscsi_transport *transport; spinlock_t lock; struct work_struct block_work; struct work_struct unblock_work; struct work_struct scan_work; struct work_struct unbind_work; /* recovery fields */ int recovery_tmo; struct delayed_work recovery_work; unsigned int target_id; int state; int sid; /* session id */ void *dd_data; /* LLD private data */ struct device dev; /* sysfs transport/container device */ }; #define iscsi_dev_to_session(_dev) \ container_of(_dev, struct iscsi_cls_session, dev) #define iscsi_session_to_shost(_session) \ dev_to_shost(_session->dev.parent) #define starget_to_session(_stgt) \ iscsi_dev_to_session(_stgt->dev.parent) struct iscsi_cls_host { atomic_t nr_scans; struct mutex mutex; }; extern void iscsi_host_for_each_session(struct Scsi_Host *shost, void (*fn)(struct iscsi_cls_session *)); struct iscsi_endpoint { void *dd_data; /* LLD private data */ struct device dev; uint64_t id; }; /* * session and connection functions that can be used by HW iSCSI LLDs */ #define iscsi_cls_session_printk(prefix, _cls_session, fmt, a...) \ dev_printk(prefix, &(_cls_session)->dev, fmt, ##a) #define iscsi_cls_conn_printk(prefix, _cls_conn, fmt, a...) \ dev_printk(prefix, &(_cls_conn)->dev, fmt, ##a) extern int iscsi_session_chkready(struct iscsi_cls_session *session); extern struct iscsi_cls_session *iscsi_alloc_session(struct Scsi_Host *shost, struct iscsi_transport *transport, int dd_size); extern int iscsi_add_session(struct iscsi_cls_session *session, unsigned int target_id); extern int iscsi_session_event(struct iscsi_cls_session *session, enum iscsi_uevent_e event); extern struct iscsi_cls_session *iscsi_create_session(struct Scsi_Host *shost, struct iscsi_transport *t, int dd_size, unsigned int target_id); extern void iscsi_remove_session(struct iscsi_cls_session *session); extern void iscsi_free_session(struct iscsi_cls_session *session); extern int iscsi_destroy_session(struct iscsi_cls_session *session); extern struct iscsi_cls_conn *iscsi_create_conn(struct iscsi_cls_session *sess, int dd_size, uint32_t cid); extern int iscsi_destroy_conn(struct iscsi_cls_conn *conn); extern void iscsi_unblock_session(struct iscsi_cls_session *session); extern void iscsi_block_session(struct iscsi_cls_session *session); extern int iscsi_scan_finished(struct Scsi_Host *shost, unsigned long time); extern struct iscsi_endpoint *iscsi_create_endpoint(int dd_size); extern void iscsi_destroy_endpoint(struct iscsi_endpoint *ep); extern struct iscsi_endpoint *iscsi_lookup_endpoint(u64 handle); #endif open-iscsi-2.0.873/test/000077500000000000000000000000001175631155400147335ustar00rootroot00000000000000open-iscsi-2.0.873/test/README000066400000000000000000000006671175631155400156240ustar00rootroot00000000000000This directory contains regression suite. I would appreciate if developer will run it at least once after modifications done before commit or mailing list submit. ./regression.sh script expects next binaries and data files exists in current directory: - regression.dat - iscsiadm - bonnie++ (source: http://www.open-iscsi.org/bits/bonnie++.tar.gz) - disktest (source: http://www.open-iscsi.org/bits/disktest.tar.gz) Thanks! Dmitry open-iscsi-2.0.873/test/regression.dat000066400000000000000000000067651175631155400176230ustar00rootroot00000000000000#imdata inir2t hdrdgst datdgst frstbst mxbrst mxrecv mxr2t # 0 - 16 No Yes None None 4096 4096 4096 1 No Yes None None 8192 4096 4096 1 No Yes None None 16384 4096 4096 1 No Yes None None 32768 4096 4096 1 No Yes None None 65536 4096 4096 1 No Yes None None 131972 4096 4096 1 No Yes None None 4096 8192 4096 1 No Yes None None 4096 16384 4096 1 No Yes None None 4096 32768 4096 1 No Yes None None 4096 65536 4096 1 No Yes None None 4096 131072 4096 1 No Yes None None 4096 4096 8192 1 No Yes None None 4096 4096 16384 1 No Yes None None 4096 4096 32768 1 No Yes None None 4096 4096 65536 1 No Yes None None 4096 4096 131072 1 # 15 - 31 No No None None 4096 4096 4096 1 No No None None 8192 4096 4096 1 No No None None 16384 4096 4096 1 No No None None 32768 4096 4096 1 No No None None 65536 4096 4096 1 No No None None 131972 4096 4096 1 No No None None 4096 8192 4096 1 No No None None 4096 16384 4096 1 No No None None 4096 32768 4096 1 No No None None 4096 65536 4096 1 No No None None 4096 131072 4096 1 No No None None 4096 4096 8192 1 No No None None 4096 4096 16384 1 No No None None 4096 4096 32768 1 No No None None 4096 4096 65536 1 No No None None 4096 4096 131072 1 # 32 - 47 Yes No None None 4096 4096 4096 1 Yes No None None 8192 4096 4096 1 Yes No None None 16384 4096 4096 1 Yes No None None 32768 4096 4096 1 Yes No None None 65536 4096 4096 1 Yes No None None 131972 4096 4096 1 Yes No None None 4096 8192 4096 1 Yes No None None 4096 16384 4096 1 Yes No None None 4096 32768 4096 1 Yes No None None 4096 65536 4096 1 Yes No None None 4096 131072 4096 1 Yes No None None 4096 4096 8192 1 Yes No None None 4096 4096 16384 1 Yes No None None 4096 4096 32768 1 Yes No None None 4096 4096 65536 1 Yes No None None 4096 4096 131072 1 # 48 - 63 Yes Yes None None 4096 4096 4096 1 Yes Yes None None 8192 4096 4096 1 Yes Yes None None 16384 4096 4096 1 Yes Yes None None 32768 4096 4096 1 Yes Yes None None 65536 4096 4096 1 Yes Yes None None 131972 4096 4096 1 Yes Yes None None 4096 8192 4096 1 Yes Yes None None 4096 16384 4096 1 Yes Yes None None 4096 32768 4096 1 Yes Yes None None 4096 65536 4096 1 Yes Yes None None 4096 131072 4096 1 Yes Yes None None 4096 4096 8192 1 Yes Yes None None 4096 4096 16384 1 Yes Yes None None 4096 4096 32768 1 Yes Yes None None 4096 4096 65536 1 Yes Yes None None 4096 4096 131072 1 # 64 - 79 No Yes CRC32C None 4096 4096 4096 1 No Yes CRC32C None 8192 4096 4096 1 No Yes CRC32C None 16384 4096 4096 1 No Yes CRC32C None 32768 4096 4096 1 No Yes CRC32C None 65536 4096 4096 1 No Yes CRC32C None 131972 4096 4096 1 No Yes CRC32C None 4096 8192 4096 1 No Yes CRC32C None 4096 16384 4096 1 No Yes CRC32C None 4096 32768 4096 1 No Yes CRC32C None 4096 65536 4096 1 No Yes CRC32C None 4096 131072 4096 1 No Yes CRC32C None 4096 4096 8192 1 No Yes CRC32C None 4096 4096 16384 1 No Yes CRC32C None 4096 4096 32768 1 No Yes CRC32C None 4096 4096 65536 1 No Yes CRC32C None 4096 4096 131072 1 # 80 - 95 No Yes CRC32C CRC32C 4096 4096 4096 1 No Yes CRC32C CRC32C 8192 4096 4096 1 No Yes CRC32C CRC32C 16384 4096 4096 1 No Yes CRC32C CRC32C 32768 4096 4096 1 No Yes CRC32C CRC32C 65536 4096 4096 1 No Yes CRC32C CRC32C 131972 4096 4096 1 No Yes CRC32C CRC32C 4096 8192 4096 1 No Yes CRC32C CRC32C 4096 16384 4096 1 No Yes CRC32C CRC32C 4096 32768 4096 1 No Yes CRC32C CRC32C 4096 65536 4096 1 No Yes CRC32C CRC32C 4096 131072 4096 1 No Yes CRC32C CRC32C 4096 4096 8192 1 No Yes CRC32C CRC32C 4096 4096 16384 1 No Yes CRC32C CRC32C 4096 4096 32768 1 No Yes CRC32C CRC32C 4096 4096 65536 1 No Yes CRC32C CRC32C 4096 4096 131072 1 open-iscsi-2.0.873/test/regression.sh000077500000000000000000000163761175631155400174670ustar00rootroot00000000000000#!/bin/bash # # Open-iSCSI Regression Test Utility # Copyright (C) 2004 Dmitry Yusupov # maintained by open-iscsi@googlegroups.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # See the file COPYING included with this distribution for more details. # PATH=".:${PATH}" FSTYPE="${FSTYPE:-ext3}" DEFAULTMOUNTOPTS='-o _netdev' [ -z "${MOUNTOPTS}" ] && MOUNTOPTS="${DEFAULTMOUNTOPTS}" # to avoid mount looking for fstype MOUNTOPTIONS="${MOUNTOPTIONS} -t ${FSTYPE}" MKFSCMD="${MKFSCMD:-mkfs.${FSTYPE}} ${MKFSOPTS}" PARTITIONSUFFIX="1" BONNIEPARAMS="${BONNIEPARAMS:--r0 -n10:0:0 -s16 -uroot -f -q}" trap regress_signal INT QUIT TERM regress_signal() { printf "\nterminating, restore defaults: " # use the other function to clean up imm_data_en="Yes" initial_r2t_en="No" hdrdgst_en="None,CRC32C" datdgst_en="None,CRC32C" c="${iscsiadm} -m node -T $target -p $ipnr -o update" first_burst="$((256*1024))" max_burst="$((16*1024*1024-1024))" max_recv_dlength="$((128*1024))" max_r2t="1" update_cfg ${iscsiadm} -m node -T $target -p $ipnr --logout 2>/dev/null >/dev/null printf "done\n" exit 0 } function update_cfg() { c="${iscsiadm} -m node -T $target -p $ipnr -o update" $c -n node.session.iscsi.ImmediateData -v $imm_data_en $c -n node.session.iscsi.InitialR2T -v $initial_r2t_en $c -n node.conn[0].iscsi.HeaderDigest -v $hdrdgst_en $c -n node.conn[0].iscsi.DataDigest -v $datdgst_en $c -n node.session.iscsi.FirstBurstLength -v $first_burst $c -n node.session.iscsi.MaxBurstLength -v $max_burst $c -n node.conn[0].iscsi.MaxRecvDataSegmentLength -v $max_recv_dlength $c -n node.session.iscsi.MaxOutstandingR2T -v $max_r2t } function disktest_run() { bsizes="512 1024 2048 4096 8192 16384 32768 65536 131072 1000000" test "x$bsize" != x && bsizes=$bsize test "x$bsize" = xbonnie && return 0; for bs in $bsizes; do echo -n "disktest -T2 -K8 -B$bs -r -ID $device: " if ! ${disktest} -T2 -K8 -B$bs -r -ID $device >/dev/null; then echo "FAILED" return 1; fi echo "PASSED" echo -n "disktest -T2 -K8 -B$bs -E16 -w -ID $device: " if ! ${disktest} -T2 -K8 -B$bs -E16 -w -ID $device >/dev/null;then echo "FAILED" return 1; fi echo "PASSED" done return 0; } function fdisk_run() { echo -n "sfdisk -Lqf $device: " sfdisk -Lqf $device >/dev/null 2>/dev/null <<-EOF 0, ; ; ; EOF rc=$? if [ $rc -ne 0 ]; then echo "FAILED" return 1; fi echo "PASSED" return 0; } function mkfs_run() { echo -n "${MKFSCMD} $device_partition: " if ! ${MKFSCMD} $device_partition 2>/dev/null >/dev/null; then echo "FAILED" return 1; fi echo "PASSED" return 0; } function bonnie_run() { dir="/tmp/iscsi.bonnie.regression.$record.$RANDOM" umount $dir 2>/dev/null >/dev/null rm -rf $dir; mkdir $dir echo -n "mount $dir: " if ! mount ${MOUNTOPTIONS} $device_partition $dir; then echo "FAILED" return 1; fi echo "PASSED" echo -n "bonnie++ ${BONNIEPARAMS}: " pushd $dir >/dev/null ${bonnie} ${BONNIEPARAMS} 2>/dev/null >/dev/null rc=$? popd >/dev/null umount $dir 2>/dev/null >/dev/null rmdir ${dir} if [ $rc -ne 0 ]; then echo "FAILED" return 1; fi echo "PASSED" return 0; } function fatal() { echo "regression.sh: $1" echo "Usage: regression.sh [-f | ] [test#[:#]] [bsize]" exit 1 } ############################ main ################################### disktest=`which disktest` iscsiadm=`which iscsiadm` bonnie=`which bonnie++` datfile=`dirname $0`"/regression.dat" test ! -e ${datfile} && fatal "can not find regression.dat" test ! -e ${disktest} && fatal "can not find disktest" test ! -e ${iscsiadm} && fatal "can not find iscsiadm" test ! -e ${bonnie} && fatal "can not find bonnie++" if test x$1 = "x-f" -o x$1 = "x--format"; then test x$2 = x && fatal "SCSI device parameter error" device=$2 else test x$1 = x && fatal "target name parameter error" test x$2 = x && fatal "ipnumber parameter error" test x$3 = x && fatal "SCSI device parameter error" target="$1" ipnr="$2" device=$3 fi device_dir="$(dirname ${device})" device_partition='' case "${device_dir}" in # /dev/sdaX /dev) device_partition="${device}1" ;; # /dev/disk/by-id/scsi-${ID_SERIAL}-part1 # where ID_SERIAL is SCSI disk SERIAL from scsi_id /dev/disk/by-id|/dev/disk/by-path) device_partition="${device}-part1" ;; # upcoming stuff /dev/iscsi/*) device_partition="${device}-part1" ;; esac if test x$1 = "x-f" -o x$1 = "x--format"; then mkfs_run exit fi if [ -z "${device_partition}" ]; then echo 'Unable to find device name for first partition.' >&2 exit 1 fi test "x$4" != x && begin="$4" test "x$5" != x && bsize="$5" if test "x$begin" != "x"; then end="${begin/*:}" begin="${begin/:*}" fi # don't say we didn't warn you if [ -z "${SKIP_WARNING}" ]; then cat <<-EOF BIG FAT WARNING! Open-iSCSI Regression Test Suite is about to start. It is going to use "$device" for its testing. iSCSI session could be re-opened during the tests several times and as the result device name could not match provided device name if some other SCSI activity happened during the test. Are you sure you want to continue? [y/n]: EOF read line if test x$line = xn -o x$line = xN -o x$line = xno -o x$line = xNO; then echo "aborting..." exit fi fi i=0 cat ${datfile} | while read line; do if echo $line | grep "^#" >/dev/null; then continue; fi if echo $line | grep "^$" >/dev/null; then continue; fi if test x$begin != x; then if test x$begin != x$i -a x$end = x; then let i=i+1 continue elif test x$begin != x -a x$end != x; then if test $i -lt $begin -o $i -gt $end; then let i=i+1 continue fi fi fi imm_data_en=`echo $line | awk '/^[YesNo]+/ {print $1}'` if test x$imm_data_en = x; then continue; fi initial_r2t_en=`echo $line | awk '{print $2}'` hdrdgst_en=`echo $line | awk '{print $3}'` datdgst_en=`echo $line | awk '{print $4}'` first_burst=`echo $line | awk '{print $5}'` max_burst=`echo $line | awk '{print $6}'` max_recv_dlength=`echo $line | awk '{print $7}'` max_r2t=`echo $line | awk '{print $8}'` # ensure we are logged out ${iscsiadm} -m node -T $target -p $ipnr --logout 2>/dev/null >/dev/null # set parameters for next run update_cfg echo "================== TEST #$i BEGIN ====================" echo "ImmediateData = $imm_data_en" echo "InitialR2T = $initial_r2t_en" echo "HeaderDigest = $hdrdgst_en" echo "DataDigest = $datdgst_en" echo "FirstBurstLength = $first_burst" echo "MaxBurstLength = $max_burst" echo "MaxRecvDataSegmentLength = $max_recv_dlength" echo "MaxOutstandingR2T = $max_r2t" # login for new test # catch errors on this if ! ${iscsiadm} -m node -T $target -p $ipnr --login; then break; fi while [ ! -e $device ] ; do sleep 1 ; done if ! disktest_run; then break; fi if ! fdisk_run; then break; fi if ! mkfs_run; then break; fi if ! bonnie_run; then break; fi let i=i+1 done regress_signal echo echo "===================== THE END ========================" open-iscsi-2.0.873/usr/000077500000000000000000000000001175631155400145655ustar00rootroot00000000000000open-iscsi-2.0.873/usr/.gitignore000066400000000000000000000000331175631155400165510ustar00rootroot00000000000000iscsiadm iscsid iscsistart open-iscsi-2.0.873/usr/Makefile000066400000000000000000000040531175631155400162270ustar00rootroot00000000000000# This Makefile will work only with GNU make. OSNAME=$(shell uname -s) # allow users to override these # eg to compile for a kernel that you aren't currently running KERNELRELEASE ?= $(shell uname -r) KSRC ?= /lib/modules/$(KERNELRELEASE)/build KSUBLEVEL=$(shell cat $(KSRC)/Makefile | awk -F= '/^SUBLEVEL =/ {print $$2}' | \ sed 's/^[ \t]*//;s/[ \t]*$$//') ifeq ($(OSNAME),Linux) ifeq ($(KSUBLEVEL),11) IPC_CFLAGS=-DNETLINK_ISCSI=12 -D_GNU_SOURCE else ifeq ($(KSUBLEVEL),12) IPC_CFLAGS=-DNETLINK_ISCSI=12 -D_GNU_SOURCE else IPC_CFLAGS=-DNETLINK_ISCSI=8 -D_GNU_SOURCE endif endif IPC_OBJ=netlink.o else ifeq ($(OSNAME),FreeBSD) IPC_CFLAGS= IPC_OBJ=ioctl.o endif endif OPTFLAGS ?= -O2 -g WARNFLAGS ?= -Wall -Wstrict-prototypes CFLAGS += $(OPTFLAGS) $(WARNFLAGS) -I../include -I. -I../utils/open-isns \ -D$(OSNAME) $(IPC_CFLAGS) PROGRAMS = iscsid iscsiadm iscsistart # libc compat files SYSDEPS_SRCS = $(wildcard ../utils/sysdeps/*.o) # sources shared between iscsid, iscsiadm and iscsistart ISCSI_LIB_SRCS = iscsi_util.o io.o auth.o iscsi_timer.o login.o log.o md5.o \ sha1.o iface.o idbm.o sysfs.o host.o session_info.o iscsi_sysfs.o \ iscsi_net_util.o iscsid_req.o transport.o iser.o cxgbi.o be2iscsi.o \ initiator_common.o iscsi_err.o $(IPC_OBJ) $(SYSDEPS_SRCS) # core initiator files INITIATOR_SRCS = initiator.o scsi.o actor.o event_poll.o mgmt_ipc.o kern_err_table.o # fw boot files FW_BOOT_SRCS = $(wildcard ../utils/fwparam_ibft/*.o) # core discovery files DISCOVERY_SRCS = $(FW_BOOT_SRCS) strings.o discovery.o all: $(PROGRAMS) iscsid: $(ISCSI_LIB_SRCS) $(INITIATOR_SRCS) $(DISCOVERY_SRCS) \ iscsid.o session_mgmt.o discoveryd.o $(CC) $(CFLAGS) $^ -o $@ -L../utils/open-isns -lisns iscsiadm: $(ISCSI_LIB_SRCS) $(DISCOVERY_SRCS) iscsiadm.o session_mgmt.o $(CC) $(CFLAGS) $^ -o $@ -L../utils/open-isns -lisns iscsistart: $(ISCSI_LIB_SRCS) $(INITIATOR_SRCS) $(FW_BOOT_SRCS) \ iscsistart.o statics.o $(CC) $(CFLAGS) -static $^ -o $@ clean: rm -f *.o $(PROGRAMS) .depend $(LIBSYS) depend: gcc $(CFLAGS) -M `ls *.c` > .depend -include .depend open-iscsi-2.0.873/usr/actor.c000066400000000000000000000171051175631155400160450ustar00rootroot00000000000000/* * iSCSI usermode single-threaded scheduler * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include "actor.h" #include "log.h" #include "list.h" static LIST_HEAD(pend_list); static LIST_HEAD(poll_list); static LIST_HEAD(actor_list); static volatile uint64_t previous_time; static volatile uint32_t scheduler_loops; static volatile int poll_in_progress; static volatile uint64_t actor_jiffies = 0; #define actor_diff(_time1, _time2) ({ \ uint64_t __ret; \ if ((_time2) >= (_time1)) \ __ret = (_time2) - (_time1); \ else \ __ret = ((~0ULL) - (_time1)) + (_time2); \ __ret; \ }) #define ACTOR_TICKS actor_jiffies #define ACTOR_TICKS_10MS(_a) (_a) #define ACTOR_MS_TO_TICKS(_a) ((_a)/ACTOR_RESOLUTION) static uint64_t actor_diff_time(actor_t *thread, uint64_t current_time) { uint64_t diff_time = actor_diff(thread->scheduled_at, current_time); if(diff_time >= thread->ttschedule) return 0; return (thread->ttschedule - diff_time); } #define time_after(a,b) \ ((int64_t)(b) - (int64_t)(a) < 0) void actor_init(void) { poll_in_progress = 0; previous_time = 0; scheduler_loops = 0; } void actor_new(actor_t *thread, void (*callback)(void *), void *data) { INIT_LIST_HEAD(&thread->list); thread->state = ACTOR_NOTSCHEDULED; thread->callback = callback; thread->data = data; } void actor_delete(actor_t *thread) { log_debug(7, "thread %08lx delete: state %d", (long)thread, thread->state); switch(thread->state) { case ACTOR_SCHEDULED: case ACTOR_WAITING: case ACTOR_POLL_WAITING: log_debug(1, "deleting a scheduled/waiting thread!"); list_del_init(&thread->list); break; default: break; } thread->state = ACTOR_NOTSCHEDULED; } static void actor_schedule_private(actor_t *thread, uint32_t ttschedule, int head) { uint64_t delay_time, current_time; actor_t *next_thread; delay_time = ACTOR_MS_TO_TICKS(ttschedule); current_time = ACTOR_TICKS; log_debug(7, "thread %p schedule: delay %" PRIu64 " state %d", thread, delay_time, thread->state); /* convert ttscheduled msecs in 10s of msecs by dividing for now. * later we will change param to 10s of msecs */ switch(thread->state) { case ACTOR_WAITING: log_error("rescheduling a waiting thread!"); list_del(&thread->list); case ACTOR_NOTSCHEDULED: INIT_LIST_HEAD(&thread->list); /* if ttschedule is 0, put in scheduled queue and change * state to scheduled, else add current time to ttschedule and * insert in the queue at the correct point */ if (delay_time == 0) { /* For head addition, it must go onto the head of the actor_list regardless if poll is in progress or not */ if (poll_in_progress && !head) { thread->state = ACTOR_POLL_WAITING; list_add_tail(&thread->list, &poll_list); } else { thread->state = ACTOR_SCHEDULED; if (head) list_add(&thread->list, &actor_list); else list_add_tail(&thread->list, &actor_list); } } else { thread->state = ACTOR_WAITING; thread->ttschedule = delay_time; thread->scheduled_at = current_time; /* insert new entry in sort order */ list_for_each_entry(next_thread, &pend_list, list) { log_debug(7, "thread %p %" PRIu64 " %"PRIu64, next_thread, next_thread->scheduled_at + next_thread->ttschedule, current_time + delay_time); if (time_after(next_thread->scheduled_at + next_thread->ttschedule, current_time + delay_time)) { list_add(&thread->list, &next_thread->list); goto done; } } list_add_tail(&thread->list, &pend_list); } done: break; case ACTOR_POLL_WAITING: case ACTOR_SCHEDULED: // don't do anything break; case ACTOR_INVALID: log_error("BUG: Trying to schedule a thread that has not been " "setup. Ignoring sched."); break; } } void actor_schedule_head(actor_t *thread) { actor_schedule_private(thread, 0, 1); } void actor_schedule(actor_t *thread) { actor_schedule_private(thread, 0, 0); } void actor_timer(actor_t *thread, uint32_t timeout, void (*callback)(void *), void *data) { actor_new(thread, callback, data); actor_schedule_private(thread, timeout, 0); } int actor_timer_mod(actor_t *thread, uint32_t timeout, void *data) { if (thread->state == ACTOR_WAITING) { list_del_init(&thread->list); thread->data = data; actor_schedule_private(thread, timeout, 0); return 1; } return 0; } void actor_check(uint64_t current_time) { struct actor *thread, *tmp; list_for_each_entry_safe(thread, tmp, &pend_list, list) { if (actor_diff_time(thread, current_time)) { log_debug(7, "thread %08lx wait some more", (long)thread); /* wait some more */ break; } /* it is time to schedule this entry */ list_del_init(&thread->list); log_debug(2, "thread %08lx was scheduled at %" PRIu64 ":" "%" PRIu64 ", curtime %" PRIu64 " q_forw %p " "&pend_list %p", (long)thread, thread->scheduled_at, thread->ttschedule, current_time, pend_list.next, &pend_list); if (poll_in_progress) { thread->state = ACTOR_POLL_WAITING; list_add_tail(&thread->list, &poll_list); log_debug(7, "thread %08lx now in poll_list", (long)thread); } else { thread->state = ACTOR_SCHEDULED; list_add_tail(&thread->list, &actor_list); log_debug(7, "thread %08lx now in actor_list", (long)thread); } } } void actor_poll(void) { uint64_t current_time; struct actor *thread; /* check that there are no any concurrency */ if (poll_in_progress) { log_error("concurrent actor_poll() is not allowed"); } /* don't check wait list every single poll. * get new time. Shift it to make 10s of msecs approx * if new time is not same as old time */ if (scheduler_loops++ > ACTOR_MAX_LOOPS) { /* try coming in about every 100 msecs */ current_time = ACTOR_TICKS; scheduler_loops = 0; /* checking whether we are in the same tick... */ if ( ACTOR_TICKS_10MS(current_time) != ACTOR_TICKS_10MS(previous_time)) { previous_time = current_time; actor_check(current_time); } } /* the following code to check in the main data path */ poll_in_progress = 1; while (!list_empty(&actor_list)) { thread = list_entry(actor_list.next, struct actor, list); list_del_init(&thread->list); if (thread->state != ACTOR_SCHEDULED) log_error("actor_list: thread state corrupted! " "Thread with state %d in actor list.", thread->state); thread->state = ACTOR_NOTSCHEDULED; log_debug(7, "exec thread %08lx callback", (long)thread); thread->callback(thread->data); log_debug(7, "thread removed\n"); } poll_in_progress = 0; while (!list_empty(&poll_list)) { thread = list_entry(poll_list.next, struct actor, list); list_del_init(&thread->list); if (thread->state != ACTOR_POLL_WAITING) log_error("poll_list: thread state corrupted!" "Thread with state %d in poll list.", thread->state); thread->state = ACTOR_SCHEDULED; list_add_tail(&thread->list, &actor_list); log_debug(7, "thread %08lx removed from poll_list", (long)thread); } ACTOR_TICKS++; } open-iscsi-2.0.873/usr/actor.h000066400000000000000000000032111175631155400160430ustar00rootroot00000000000000/* * iSCSI usermode single-threaded scheduler * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ACTOR_H #define ACTOR_H #include "types.h" #include "list.h" #define ACTOR_RESOLUTION 250 /* in millis */ #define ACTOR_MAX_LOOPS 1 typedef enum actor_state_e { ACTOR_INVALID, ACTOR_WAITING, ACTOR_SCHEDULED, ACTOR_NOTSCHEDULED, ACTOR_POLL_WAITING } actor_state_e; typedef struct actor { struct list_head list; actor_state_e state; void *data; void (*callback)(void * ); uint64_t scheduled_at; uint64_t ttschedule; } actor_t; extern void actor_new(actor_t *thread, void (*callback)(void *), void * data); extern void actor_delete(actor_t *thread); extern void actor_schedule_head(actor_t *thread); extern void actor_schedule(actor_t *thread); extern void actor_timer(actor_t *thread, uint32_t timeout, void (*callback)(void *), void *data); extern int actor_timer_mod(actor_t *thread, uint32_t new_timeout, void *data); extern void actor_poll(void); extern void actor_init(void); #endif /* ACTOR_H */ open-iscsi-2.0.873/usr/auth.c000066400000000000000000001442101175631155400156740ustar00rootroot00000000000000/* * iSCSI Authorization Library * * maintained by open-iscsi@@googlegroups.com * * Originally based on: * Copyright (C) 2001 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * This file implements the iSCSI CHAP authentication method based on * RFC 3720. The code in this file is meant to be common for both kernel and * user level and makes use of only limited library functions, presently only * string.h. Routines specific to kernel, user level are implemented in * seperate files under the appropriate directories. * This code in this files assumes a single thread of execution * for each iscsi_acl structure, and does no locking. */ #include #include #include #include #include #include "sysdeps.h" #include "auth.h" #include "initiator.h" #include "md5.h" #include "log.h" static const char acl_hexstring[] = "0123456789abcdefABCDEF"; static const char acl_base64_string[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char acl_authmethod_set_chap_alg_list[] = "CHAP"; static const char acl_reject_option_name[] = "Reject"; void auth_md5_init(struct MD5Context *); void auth_md5_update(struct MD5Context *, unsigned char *, unsigned int); void auth_md5_final(unsigned char *, struct MD5Context *); void get_random_bytes(unsigned char *data, unsigned int length); size_t strlcpy(char *, const char *, size_t); size_t strlcat(char *, const char *, size_t); enum auth_dbg_status acl_chap_compute_rsp(struct iscsi_acl *client, int rmt_auth, unsigned int id, unsigned char *challenge_data, unsigned int challenge_length, unsigned char *response_data) { unsigned char id_data[1]; struct MD5Context context; unsigned char out_data[AUTH_STR_MAX_LEN]; unsigned int out_length = AUTH_STR_MAX_LEN; if (!client->passwd_present) return AUTH_DBG_STATUS_LOCAL_PASSWD_NOT_SET; auth_md5_init(&context); /* id byte */ id_data[0] = id; auth_md5_update(&context, id_data, 1); /* decrypt password */ if (acl_data(out_data, &out_length, client->passwd_data, client->passwd_length)) return AUTH_DBG_STATUS_PASSWD_DECRYPT_FAILED; if (!rmt_auth && !client->ip_sec && out_length < 12) return AUTH_DBG_STATUS_PASSWD_TOO_SHORT_WITH_NO_IPSEC; /* shared secret */ auth_md5_update(&context, out_data, out_length); /* clear decrypted password */ memset(out_data, 0, AUTH_STR_MAX_LEN); /* challenge value */ auth_md5_update(&context, challenge_data, challenge_length); auth_md5_final(response_data, &context); return AUTH_DBG_STATUS_NOT_SET; /* no error */ } /* * Authenticate a target's CHAP response. */ int acl_chap_auth_request(struct iscsi_acl *client, char *username, unsigned int id, unsigned char *challenge_data, unsigned int challenge_length, unsigned char *response_data, unsigned int rsp_length) { iscsi_session_t *session = client->session_handle; struct MD5Context context; unsigned char verify_data[16]; /* the expected credentials are in the session */ if (session->username_in == NULL) { log_error("failing authentication, no incoming username " "configured to authenticate target %s\n", session->target_name); return AUTH_STATUS_FAIL; } if (strcmp(username, session->username_in) != 0) { log_error("failing authentication, received incorrect " "username from target %s\n", session->target_name); return AUTH_STATUS_FAIL; } if ((session->password_in_length < 1) || (session->password_in == NULL) || (session->password_in[0] == '\0')) { log_error("failing authentication, no incoming password " "configured to authenticate target %s\n", session->target_name); return AUTH_STATUS_FAIL; } /* challenge length is I->T, and shouldn't need to be checked */ if (rsp_length != sizeof(verify_data)) { log_error("failing authentication, received incorrect " "CHAP response length %u from target %s\n", rsp_length, session->target_name); return AUTH_STATUS_FAIL; } auth_md5_init(&context); /* id byte */ verify_data[0] = id; auth_md5_update(&context, verify_data, 1); /* shared secret */ auth_md5_update(&context, (unsigned char *)session->password_in, session->password_in_length); /* challenge value */ auth_md5_update(&context, (unsigned char *)challenge_data, challenge_length); auth_md5_final(verify_data, &context); if (memcmp(response_data, verify_data, sizeof(verify_data)) == 0) { log_debug(1, "initiator authenticated target %s\n", session->target_name); return AUTH_STATUS_PASS; } log_error("failing authentication, received incorrect CHAP " "response from target %s\n", session->target_name); return AUTH_STATUS_FAIL; } void auth_md5_init(struct MD5Context *context) { MD5Init(context); } void auth_md5_update(struct MD5Context *context, unsigned char *data, unsigned int length) { MD5Update(context, data, length); } void auth_md5_final(unsigned char *hash, struct MD5Context *context) { MD5Final(hash, context); } void get_random_bytes(unsigned char *data, unsigned int length) { long r; unsigned n; int fd; fd = open("/dev/urandom", O_RDONLY); while (length > 0) { if (!fd || read(fd, &r, sizeof(long)) != -1) r = rand(); r = r ^ (r >> 8); r = r ^ (r >> 4); n = r & 0x7; if (!fd || read(fd, &r, sizeof(long)) != -1) r = rand(); r = r ^ (r >> 8); r = r ^ (r >> 5); n = (n << 3) | (r & 0x7); if (!fd || read(fd, &r, sizeof(long)) != -1) r = rand(); r = r ^ (r >> 8); r = r ^ (r >> 5); n = (n << 2) | (r & 0x3); *data++ = n; length--; } if (fd) close(fd); } static const char acl_none_option_name[] = "None"; static int acl_text_to_number(const char *text, unsigned long *num) { char *end; unsigned long number = *num; if (text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) number = strtoul(text + 2, &end, 16); else number = strtoul(text, &end, 10); if (*text != '\0' && *end == '\0') { *num = number; return 0; /* No error */ } else return 1; /* Error */ } static int acl_chk_string(const char *s, unsigned int max_len, unsigned int *out_len) { unsigned int len; if (!s) return 1; for (len = 0; len < max_len; len++) if (*s++ == '\0') { if (out_len) *out_len = len; return 0; } return 1; } static int acl_str_index(const char *s, int c) { char *str = strchr(s, c); if (str) return (str - s); else return -1; } static int acl_chk_auth_mthd_optn(int val) { if (val == AUTH_OPTION_NONE || val == AUTH_METHOD_CHAP) return 0; return 1; } static const char * acl_authmethod_optn_to_text(int value) { const char *s; switch (value) { case AUTH_OPTION_REJECT: s = acl_reject_option_name; break; case AUTH_OPTION_NONE: s = acl_none_option_name; break; case AUTH_METHOD_CHAP: s = acl_authmethod_set_chap_alg_list; break; default: s = NULL; } return s; } static int acl_chk_chap_alg_optn(int chap_algorithm) { if (chap_algorithm == AUTH_OPTION_NONE || chap_algorithm == AUTH_CHAP_ALG_MD5) return 0; return 1; } static int acl_data_to_text(unsigned char *data, unsigned int data_length, char *text, unsigned int text_length) { unsigned long n; if (!text || text_length == 0) return 1; if (!data || data_length == 0) { *text = '\0'; return 1; } if (text_length < 3) { *text = '\0'; return 1; } *text++ = '0'; *text++ = 'x'; text_length -= 2; while (data_length > 0) { if (text_length < 3) { *text = '\0'; return 1; } n = *data++; data_length--; *text++ = acl_hexstring[(n >> 4) & 0xf]; *text++ = acl_hexstring[n & 0xf]; text_length -= 2; } *text = '\0'; return 0; } static int acl_hex_to_data(const char *text, unsigned int text_length, unsigned char *data, unsigned int *data_lenp) { int i; unsigned int n1; unsigned int n2; unsigned int data_length = *data_lenp; if ((text_length % 2) == 1) { i = acl_str_index(acl_hexstring, *text++); if (i < 0) return 1; /* error, bad character */ if (i > 15) i -= 6; n2 = i; if (data_length < 1) return 1; /* error, too much data */ *data++ = n2; data_length--; } while (*text != '\0') { i = acl_str_index(acl_hexstring, *text++); if (i < 0) return 1; /* error, bad character */ if (i > 15) i -= 6; n1 = i; if (*text == '\0') return 1; /* error, odd string length */ i = acl_str_index(acl_hexstring, *text++); if (i < 0) return 1; /* error, bad character */ if (i > 15) i -= 6; n2 = i; if (data_length < 1) return 1; /* error, too much data */ *data++ = (n1 << 4) | n2; data_length--; } if (data_length >= *data_lenp) return 1; /* error, no data */ *data_lenp = *data_lenp - data_length; return 0; /* no error */ } static int acl_base64_to_data(const char *text, unsigned char *data, unsigned int *data_lenp) { int i; unsigned int n; unsigned int count; unsigned int data_length = *data_lenp; n = 0; count = 0; while (*text != '\0' && *text != '=') { i = acl_str_index(acl_base64_string, *text++); if (i < 0) return 1; /* error, bad character */ n = (n << 6 | (unsigned int)i); count++; if (count >= 4) { if (data_length < 3) return 1; /* error, too much data */ *data++ = n >> 16; *data++ = n >> 8; *data++ = n; data_length -= 3; n = 0; count = 0; } } while (*text != '\0') if (*text++ != '=') return 1; /* error, bad pad */ if (count == 0) { /* do nothing */ } else if (count == 2) { if (data_length < 1) return 1; /* error, too much data */ n = n >> 4; *data++ = n; data_length--; } else if (count == 3) { if (data_length < 2) return 1; /* error, too much data */ n = n >> 2; *data++ = n >> 8; *data++ = n; data_length -= 2; } else return 1; /* bad encoding */ if (data_length >= *data_lenp) return 1; /* error, no data */ *data_lenp = *data_lenp - data_length; return 0; /* no error */ } static int acl_text_to_data(const char *text, unsigned char *data, unsigned int *data_length) { int status; unsigned int text_length; status = acl_chk_string(text, 2 + 2 * AUTH_LARGE_BINARY_MAX_LEN + 1, &text_length); if (status) return status; if (text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { /* skip prefix */ text += 2; text_length -= 2; status = acl_hex_to_data(text, text_length, data, data_length); } else if (text[0] == '0' && (text[1] == 'b' || text[1] == 'B')) { /* skip prefix */ text += 2; text_length -= 2; status = acl_base64_to_data(text, data, data_length); } else status = 1; /* prefix not recognized. */ return status; } static void acl_init_key_blk(struct auth_key_block *key_blk) { char *str_block = key_blk->str_block; memset(key_blk, 0, sizeof(*key_blk)); key_blk->str_block = str_block; } static void acl_set_key_value(struct auth_key_block *key_blk, int key_type, const char *key_val) { unsigned int length; char *string; if (key_blk->key[key_type].value_set) { key_blk->dup_set = 1; return; } key_blk->key[key_type].value_set = 1; if (!key_val) return; if (acl_chk_string(key_val, AUTH_STR_MAX_LEN, &length)) { key_blk->str_too_long = 1; return; } length += 1; if ((key_blk->blk_length + length) > AUTH_STR_BLOCK_MAX_LEN) { key_blk->too_much_data = 1; return; } string = &key_blk->str_block[key_blk->blk_length]; if (strlcpy(string, key_val, length) >= length) { key_blk->too_much_data = 1; return; } key_blk->blk_length += length; key_blk->key[key_type].string = string; key_blk->key[key_type].present = 1; } static const char * acl_get_key_val(struct auth_key_block *key_blk, int key_type) { key_blk->key[key_type].processed = 1; if (!key_blk->key[key_type].present) return NULL; return key_blk->key[key_type].string; } static void acl_chk_key(struct iscsi_acl *client, int key_type, int *negotiated_option, unsigned int option_count, int *option_list, const char *(*value_to_text) (int)) { const char *key_val; int length; unsigned int i; key_val = acl_get_key_val(&client->recv_key_block, key_type); if (!key_val) { *negotiated_option = AUTH_OPTION_NOT_PRESENT; return; } while (*key_val != '\0') { length = 0; while (*key_val != '\0' && *key_val != ',') client->scratch_key_value[length++] = *key_val++; if (*key_val == ',') key_val++; client->scratch_key_value[length++] = '\0'; for (i = 0; i < option_count; i++) { const char *s = (*value_to_text)(option_list[i]); if (!s) continue; if (strcmp(client->scratch_key_value, s) == 0) { *negotiated_option = option_list[i]; return; } } } *negotiated_option = AUTH_OPTION_REJECT; } static void acl_set_key(struct iscsi_acl *client, int key_type, unsigned int option_count, int *option_list, const char *(*value_to_text)(int)) { unsigned int i; if (option_count == 0) { /* * No valid options to send, but we always want to * send something. */ acl_set_key_value(&client->send_key_block, key_type, acl_none_option_name); return; } if (option_count == 1 && option_list[0] == AUTH_OPTION_NOT_PRESENT) { acl_set_key_value(&client->send_key_block, key_type, NULL); return; } for (i = 0; i < option_count; i++) { const char *s = (*value_to_text)(option_list[i]); if (!s) continue; if (i == 0) strlcpy(client->scratch_key_value, s, AUTH_STR_MAX_LEN); else { strlcat(client->scratch_key_value, ",", AUTH_STR_MAX_LEN); strlcat(client->scratch_key_value, s, AUTH_STR_MAX_LEN); } } acl_set_key_value(&client->send_key_block, key_type, client->scratch_key_value); } static void acl_chk_auth_method_key(struct iscsi_acl *client) { acl_chk_key(client, AUTH_KEY_TYPE_AUTH_METHOD, &client->negotiated_auth_method, client->auth_method_valid_count, client->auth_method_valid_list, acl_authmethod_optn_to_text); } static void acl_set_auth_method_key(struct iscsi_acl *client, unsigned int auth_method_count, int *auth_method_list) { acl_set_key(client, AUTH_KEY_TYPE_AUTH_METHOD, auth_method_count, auth_method_list, acl_authmethod_optn_to_text); } static void acl_chk_chap_alg_key(struct iscsi_acl *client) { const char *key_val; int length; unsigned long number; unsigned int i; key_val = acl_get_key_val(&client->recv_key_block, AUTH_KEY_TYPE_CHAP_ALG); if (!key_val) { client->negotiated_chap_alg = AUTH_OPTION_NOT_PRESENT; return; } while (*key_val != '\0') { length = 0; while (*key_val != '\0' && *key_val != ',') client->scratch_key_value[length++] = *key_val++; if (*key_val == ',') key_val++; client->scratch_key_value[length++] = '\0'; if (acl_text_to_number(client->scratch_key_value, &number)) continue; for (i = 0; i < client->chap_alg_count; i++) if (number == (unsigned long)client->chap_alg_list[i]) { client->negotiated_chap_alg = number; return; } } client->negotiated_chap_alg = AUTH_OPTION_REJECT; } static void acl_set_chap_alg_key(struct iscsi_acl *client, unsigned int chap_alg_count, int *chap_alg_list) { unsigned int i; if (chap_alg_count == 0) { acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG, NULL); return; } if (chap_alg_count == 1 && chap_alg_list[0] == AUTH_OPTION_NOT_PRESENT) { acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG, NULL); return; } if (chap_alg_count == 1 && chap_alg_list[0] == AUTH_OPTION_REJECT) { acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG, acl_reject_option_name); return; } for (i = 0; i < chap_alg_count; i++) { char s[20]; snprintf(s, sizeof(s), "%lu",(unsigned long)chap_alg_list[i]); if (i == 0) strlcpy(client->scratch_key_value, s, AUTH_STR_MAX_LEN); else { strlcat(client->scratch_key_value, ",", AUTH_STR_MAX_LEN); strlcat(client->scratch_key_value, s, AUTH_STR_MAX_LEN); } } acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG, client->scratch_key_value); } static void acl_next_phase(struct iscsi_acl *client) { switch (client->phase) { case AUTH_PHASE_CONFIGURE: client->phase = AUTH_PHASE_NEGOTIATE; break; case AUTH_PHASE_NEGOTIATE: client->phase = AUTH_PHASE_AUTHENTICATE; if (client->negotiated_auth_method == AUTH_OPTION_REJECT || client->negotiated_auth_method == AUTH_OPTION_NOT_PRESENT || client->negotiated_auth_method == AUTH_OPTION_NONE) { client->local_state = AUTH_LOCAL_STATE_DONE; client->rmt_state = AUTH_RMT_STATE_DONE; if (client->auth_rmt) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; } else client->rmt_auth_status = AUTH_STATUS_PASS; switch (client->negotiated_auth_method) { case AUTH_OPTION_REJECT: client->dbg_status = AUTH_DBG_STATUS_AUTH_METHOD_REJECT; break; case AUTH_OPTION_NOT_PRESENT: client->dbg_status = AUTH_DBG_STATUS_AUTH_METHOD_NOT_PRESENT; break; case AUTH_OPTION_NONE: client->dbg_status = AUTH_DBG_STATUS_AUTH_METHOD_NONE; } } else if (client->negotiated_auth_method == AUTH_METHOD_CHAP) { client->local_state = AUTH_LOCAL_STATE_SEND_ALG; client->rmt_state = AUTH_RMT_STATE_SEND_ALG; } else { client->local_state = AUTH_LOCAL_STATE_DONE; client->rmt_state = AUTH_RMT_STATE_DONE; client->rmt_auth_status = AUTH_STATUS_FAIL; client->dbg_status = AUTH_DBG_STATUS_AUTH_METHOD_BAD; } break; case AUTH_PHASE_AUTHENTICATE: client->phase = AUTH_PHASE_DONE; break; case AUTH_PHASE_DONE: case AUTH_PHASE_ERROR: default: client->phase = AUTH_PHASE_ERROR; } } static void acl_local_auth(struct iscsi_acl *client) { unsigned int chap_identifier; unsigned char response_data[AUTH_CHAP_RSP_LEN]; unsigned long number; int status; enum auth_dbg_status dbg_status; const char *chap_identifier_key_val; const char *chap_challenge_key_val; switch (client->local_state) { case AUTH_LOCAL_STATE_SEND_ALG: if (client->node_type == TYPE_INITIATOR) { acl_set_chap_alg_key(client, client->chap_alg_count, client->chap_alg_list); client->local_state = AUTH_LOCAL_STATE_RECV_ALG; break; } /* Fall through */ case AUTH_LOCAL_STATE_RECV_ALG: acl_chk_chap_alg_key(client); if (client->node_type == TYPE_TARGET) acl_set_chap_alg_key(client, 1, &client->negotiated_chap_alg); /* Make sure only supported CHAP algorithm is used. */ if (client->negotiated_chap_alg == AUTH_OPTION_NOT_PRESENT) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_ALG_EXPECTED; break; } else if (client->negotiated_chap_alg == AUTH_OPTION_REJECT) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_ALG_REJECT; break; } else if (client->negotiated_chap_alg != AUTH_CHAP_ALG_MD5) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_ALG_BAD; break; } if (client->node_type == TYPE_TARGET) { client->local_state = AUTH_LOCAL_STATE_RECV_CHALLENGE; break; } /* Fall through */ case AUTH_LOCAL_STATE_RECV_CHALLENGE: chap_identifier_key_val = acl_get_key_val(&client->recv_key_block, AUTH_KEY_TYPE_CHAP_IDENTIFIER); chap_challenge_key_val = acl_get_key_val(&client->recv_key_block, AUTH_KEY_TYPE_CHAP_CHALLENGE); if (client->node_type == TYPE_TARGET) { if (!chap_identifier_key_val && !chap_challenge_key_val) { client->local_state = AUTH_LOCAL_STATE_DONE; break; } } if (!chap_identifier_key_val) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_IDENTIFIER_EXPECTED; break; } if (!chap_challenge_key_val) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_CHALLENGE_EXPECTED; break; } status = acl_text_to_number(chap_identifier_key_val, &number); if (status || (255 < number)) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_IDENTIFIER_BAD; break; } chap_identifier = number; if (client->recv_chap_challenge_status) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHALLENGE_BAD; break; } if (client->node_type == TYPE_TARGET && client->recv_chap_challenge.length == client->send_chap_challenge.length && memcmp(client->recv_chap_challenge.large_binary, client->send_chap_challenge.large_binary, client->send_chap_challenge.length) == 0) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_CHALLENGE_REFLECTED; break; } dbg_status = acl_chap_compute_rsp(client, 0, chap_identifier, client->recv_chap_challenge.large_binary, client->recv_chap_challenge.length, response_data); if (dbg_status != AUTH_DBG_STATUS_NOT_SET) { client->local_state = AUTH_LOCAL_STATE_ERROR; client->dbg_status = dbg_status; break; } acl_data_to_text(response_data, AUTH_CHAP_RSP_LEN, client->scratch_key_value, AUTH_STR_MAX_LEN); acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_RSP, client->scratch_key_value); acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_USERNAME, client->username); client->local_state = AUTH_LOCAL_STATE_DONE; break; case AUTH_LOCAL_STATE_DONE: break; case AUTH_LOCAL_STATE_ERROR: default: client->phase = AUTH_PHASE_ERROR; } } static void acl_rmt_auth(struct iscsi_acl *client) { unsigned char id_data[1]; unsigned char response_data[AUTH_STR_MAX_LEN]; unsigned int rsp_len = AUTH_STR_MAX_LEN; unsigned char my_rsp_data[AUTH_CHAP_RSP_LEN]; int status; enum auth_dbg_status dbg_status; const char *chap_rsp_key_val; const char *chap_username_key_val; switch (client->rmt_state) { case AUTH_RMT_STATE_SEND_ALG: if (client->node_type == TYPE_INITIATOR) { client->rmt_state = AUTH_RMT_STATE_SEND_CHALLENGE; break; } /* Fall through */ case AUTH_RMT_STATE_SEND_CHALLENGE: if (!client->auth_rmt) { client->rmt_auth_status = AUTH_STATUS_PASS; client->dbg_status = AUTH_DBG_STATUS_AUTH_RMT_FALSE; client->rmt_state = AUTH_RMT_STATE_DONE; break; } get_random_bytes(id_data, 1); client->send_chap_identifier = id_data[0]; snprintf(client->scratch_key_value, AUTH_STR_MAX_LEN, "%lu", (unsigned long)client->send_chap_identifier); acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_IDENTIFIER, client->scratch_key_value); client->send_chap_challenge.length = client->chap_challenge_len; get_random_bytes(client->send_chap_challenge.large_binary, client->send_chap_challenge.length); acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_CHALLENGE, ""); client->rmt_state = AUTH_RMT_STATE_RECV_RSP; break; case AUTH_RMT_STATE_RECV_RSP: chap_rsp_key_val = acl_get_key_val(&client->recv_key_block, AUTH_KEY_TYPE_CHAP_RSP); chap_username_key_val = acl_get_key_val(&client->recv_key_block, AUTH_KEY_TYPE_CHAP_USERNAME); if (!chap_rsp_key_val) { client->rmt_state = AUTH_RMT_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_RSP_EXPECTED; break; } if (!chap_username_key_val) { client->rmt_state = AUTH_RMT_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_USERNAME_EXPECTED; break; } status = acl_text_to_data(chap_rsp_key_val, response_data, &rsp_len); if (status) { client->rmt_state = AUTH_RMT_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_CHAP_RSP_BAD; break; } if (rsp_len == AUTH_CHAP_RSP_LEN) { dbg_status = acl_chap_compute_rsp(client, 1, client->send_chap_identifier, client->send_chap_challenge.large_binary, client->send_chap_challenge.length, my_rsp_data); if (dbg_status == AUTH_DBG_STATUS_NOT_SET && memcmp(my_rsp_data, response_data, AUTH_CHAP_RSP_LEN) == 0) { client->rmt_state = AUTH_RMT_STATE_ERROR; client->dbg_status = AUTH_DBG_STATUS_PASSWD_IDENTICAL; break; } } strlcpy(client->chap_username, chap_username_key_val, AUTH_STR_MAX_LEN); status = acl_chap_auth_request(client, client->chap_username, client->send_chap_identifier, client->send_chap_challenge. large_binary, client->send_chap_challenge. length, response_data, rsp_len); client->rmt_auth_status = (enum auth_status) status; client->auth_rsp_flag = 1; if (client->auth_server_error_flag) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->dbg_status = AUTH_DBG_STATUS_AUTH_SERVER_ERROR; } else if (client->rmt_auth_status == AUTH_STATUS_PASS) client->dbg_status = AUTH_DBG_STATUS_AUTH_PASS; else if (client->rmt_auth_status == AUTH_STATUS_FAIL) client->dbg_status = AUTH_DBG_STATUS_AUTH_FAIL; else { client->rmt_auth_status = AUTH_STATUS_FAIL; client->dbg_status = AUTH_DBG_STATUS_AUTH_STATUS_BAD; } client->rmt_state = AUTH_RMT_STATE_DONE; /* Fall through */ case AUTH_RMT_STATE_DONE: break; case AUTH_RMT_STATE_ERROR: default: client->phase = AUTH_PHASE_ERROR; } } static void acl_hand_shake(struct iscsi_acl *client) { if (client->phase == AUTH_PHASE_DONE) /* * Should only happen if authentication * protocol error occured. */ return; if (client->node_type == TYPE_INITIATOR) /* * Target should only have set T bit on response if * initiator set it on previous message. */ if (client->recv_key_block.transit_bit && !client->transit_bit_sent_flag) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_T_BIT_SET_ILLEGAL; return; } if (client->phase == AUTH_PHASE_NEGOTIATE) { /* * Should only happen if waiting for peer * to send AuthMethod key or set Transit Bit. */ if (client->node_type == TYPE_INITIATOR) client->send_key_block.transit_bit = 1; return; } if (client->rmt_state == AUTH_RMT_STATE_RECV_RSP || client->rmt_state == AUTH_RMT_STATE_DONE) { if (client->node_type == TYPE_INITIATOR) { if (client->recv_key_block.transit_bit) { if (client->rmt_state != AUTH_RMT_STATE_DONE) goto recv_transit_bit_err; acl_next_phase(client); } else client->send_key_block.transit_bit = 1; } else { if (client->rmt_state == AUTH_RMT_STATE_DONE && client->rmt_auth_status != AUTH_STATUS_PASS) /* * Authentication failed, don't do T bit * handshake. */ acl_next_phase(client); else { /* * Target can only set T bit on response if * initiator set it on current message. */ if (client->recv_key_block.transit_bit) { client->send_key_block.transit_bit = 1; acl_next_phase(client); } } } } else if (client->node_type == TYPE_INITIATOR) if (client->recv_key_block.transit_bit) goto recv_transit_bit_err; return; recv_transit_bit_err: /* * Target set T bit on response but * initiator was not done with authentication. */ client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_T_BIT_SET_PREMATURE; } static int acl_rcv_end_status(struct iscsi_acl *client) { int auth_status; int key_type; if (client->phase == AUTH_PHASE_ERROR) return AUTH_STATUS_ERROR; if (client->phase == AUTH_PHASE_DONE) { /* Perform sanity check against configured parameters. */ if (client->auth_rmt && !client->auth_rsp_flag && client->rmt_auth_status == AUTH_STATUS_PASS) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->dbg_status = AUTH_DBG_STATUS_AUTHPASS_NOT_VALID; } auth_status = client->rmt_auth_status; } else auth_status = AUTH_STATUS_CONTINUE; if (auth_status == AUTH_STATUS_CONTINUE || auth_status == AUTH_STATUS_PASS) { if (client->send_key_block.dup_set) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_SEND_DUP_SET_KEY_VALUE; auth_status = AUTH_STATUS_FAIL; } else if (client->send_key_block.str_too_long) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_SEND_STR_TOO_LONG; auth_status = AUTH_STATUS_FAIL; } else if (client->send_key_block.too_much_data) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_SEND_TOO_MUCH_DATA; auth_status = AUTH_STATUS_FAIL; } else { /* Check that all incoming keys have been processed. */ for (key_type = AUTH_KEY_TYPE_FIRST; key_type < AUTH_KEY_TYPE_MAX_COUNT; key_type++) if (client->recv_key_block.key[key_type].present && !client->recv_key_block.key[key_type]. processed) break; if (key_type < AUTH_KEY_TYPE_MAX_COUNT) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_UNEXPECTED_KEY_PRESENT; auth_status = AUTH_STATUS_FAIL; } } } if (auth_status != AUTH_STATUS_PASS && auth_status != AUTH_STATUS_CONTINUE) { int auth_method_key_present = 0; int chap_alg_key_present = 0; /* * Suppress send keys on error, * except for AuthMethod and CHAP_A. */ if (client->node_type == TYPE_TARGET) { if (acl_get_key_val(&client->send_key_block, AUTH_KEY_TYPE_AUTH_METHOD)) auth_method_key_present = 1; else if (acl_get_key_val(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG)) chap_alg_key_present = 1; } acl_init_key_blk(&client->send_key_block); if (client->node_type == TYPE_TARGET) { if (auth_method_key_present && client->negotiated_auth_method == AUTH_OPTION_REJECT) acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_AUTH_METHOD, acl_reject_option_name); else if (chap_alg_key_present && client->negotiated_chap_alg == AUTH_OPTION_REJECT) acl_set_key_value(&client->send_key_block, AUTH_KEY_TYPE_CHAP_ALG, acl_reject_option_name); } } client->recv_in_progress_flag = 0; return auth_status; } int acl_recv_begin(struct iscsi_acl *client) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase == AUTH_PHASE_ERROR) return AUTH_STATUS_ERROR; if (client->phase == AUTH_PHASE_DONE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (client->recv_in_progress_flag) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } client->recv_in_progress_flag = 1; if (client->phase == AUTH_PHASE_CONFIGURE) acl_next_phase(client); client->transit_bit_sent_flag = client->send_key_block.transit_bit; acl_init_key_blk(&client->recv_key_block); acl_init_key_blk(&client->send_key_block); return AUTH_STATUS_NO_ERROR; } int acl_recv_end(struct iscsi_acl *client, iscsi_session_t *session_handle) { int next_phase_flag = 0; if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase == AUTH_PHASE_ERROR) return AUTH_STATUS_ERROR; if (!client->recv_in_progress_flag) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (client->recv_end_count > AUTH_RECV_END_MAX_COUNT) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_RECV_MSG_COUNT_LIMIT; } else if (client->recv_key_block.dup_set) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_RECV_DUP_SET_KEY_VALUE; } else if (client->recv_key_block.str_too_long) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_RECV_STR_TOO_LONG; } else if (client->recv_key_block.too_much_data) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_RECV_TOO_MUCH_DATA; } client->recv_end_count++; client->session_handle = session_handle; switch (client->phase) { case AUTH_PHASE_NEGOTIATE: acl_chk_auth_method_key(client); if (client->auth_method_valid_neg_role == AUTH_NEG_ROLE_RESPONDER) { if (client->negotiated_auth_method == AUTH_OPTION_NOT_PRESENT) { if (client->auth_rmt || !client->recv_key_block.transit_bit) { /* * No AuthMethod key from peer on * first message, try moving the * process along by sending the * AuthMethod key. */ client->auth_method_valid_neg_role = AUTH_NEG_ROLE_ORIGINATOR; acl_set_auth_method_key(client, client->auth_method_valid_count, client->auth_method_valid_list); break; } /* * Special case if peer sent no AuthMethod key, * but did set Transit Bit, allowing this side * to do a null authentication, and compelete * the iSCSI security phase without either side * sending the AuthMethod key. */ } else /* Send response to AuthMethod key. */ acl_set_auth_method_key(client, 1, &client->negotiated_auth_method); if (client->node_type == TYPE_INITIATOR) acl_next_phase(client); else next_phase_flag = 1; } else { if (client->negotiated_auth_method == AUTH_OPTION_NOT_PRESENT) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; client->dbg_status = AUTH_DBG_STATUS_AUTH_METHOD_EXPECTED; break; } acl_next_phase(client); } break; case AUTH_PHASE_AUTHENTICATE: case AUTH_PHASE_DONE: break; default: client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } switch (client->phase) { case AUTH_PHASE_NEGOTIATE: if (next_phase_flag) acl_next_phase(client); break; case AUTH_PHASE_AUTHENTICATE: /* * Must call acl_local_auth() * before acl_rmt_auth() * to insure processing of the CHAP algorithm key, * and to avoid leaving an in progress request to the * authentication service. */ acl_local_auth(client); if (client->local_state != AUTH_LOCAL_STATE_ERROR) acl_rmt_auth(client); if (client->local_state == AUTH_LOCAL_STATE_ERROR || client->rmt_state == AUTH_RMT_STATE_ERROR) { client->rmt_auth_status = AUTH_STATUS_FAIL; client->phase = AUTH_PHASE_DONE; /* client->dbg_status should already be set. */ } break; case AUTH_PHASE_DONE: break; default: client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } acl_hand_shake(client); return acl_rcv_end_status(client); } const char * acl_get_key_name(int key_type) { /* * Note: The ordering of this table must match the order * defined by enum auth_key_type in iscsi-auth-client.h. */ static char *const key_names[AUTH_KEY_TYPE_MAX_COUNT] = { "AuthMethod", "CHAP_A", "CHAP_N", "CHAP_R", "CHAP_I", "CHAP_C" }; if (key_type < AUTH_KEY_TYPE_FIRST || key_type > AUTH_KEY_TYPE_LAST) return NULL; return key_names[key_type]; } int acl_get_next_key_type(int *key_type) { if (*key_type >= AUTH_KEY_TYPE_LAST) return AUTH_STATUS_ERROR; if (*key_type < AUTH_KEY_TYPE_FIRST) *key_type = AUTH_KEY_TYPE_FIRST; else (*key_type)++; return AUTH_STATUS_NO_ERROR; } int acl_recv_key_value(struct iscsi_acl *client, int key_type, const char *user_key_val) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_NEGOTIATE && client->phase != AUTH_PHASE_AUTHENTICATE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (key_type < AUTH_KEY_TYPE_FIRST || key_type > AUTH_KEY_TYPE_LAST) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (key_type == AUTH_KEY_TYPE_CHAP_CHALLENGE) { client->recv_chap_challenge.length = AUTH_LARGE_BINARY_MAX_LEN; client->recv_chap_challenge_status = acl_text_to_data(user_key_val, client->recv_chap_challenge.large_binary, &client->recv_chap_challenge.length); user_key_val = ""; } acl_set_key_value(&client->recv_key_block, key_type, user_key_val); return AUTH_STATUS_NO_ERROR; } int acl_send_key_val(struct iscsi_acl *client, int key_type, int *key_present, char *user_key_val, unsigned int max_length) { const char *key_val; if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE && client->phase != AUTH_PHASE_NEGOTIATE && client->phase != AUTH_PHASE_AUTHENTICATE && client->phase != AUTH_PHASE_DONE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (key_type < AUTH_KEY_TYPE_FIRST || key_type > AUTH_KEY_TYPE_LAST) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } key_val = acl_get_key_val(&client->send_key_block, key_type); if (key_val) { if (key_type == AUTH_KEY_TYPE_CHAP_CHALLENGE) { if (acl_data_to_text(client->send_chap_challenge.large_binary, client->send_chap_challenge.length, user_key_val, max_length)) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } } else if (strlcpy(user_key_val, key_val, max_length) >= max_length) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } *key_present = 1; } else *key_present = 0; return AUTH_STATUS_NO_ERROR; } int acl_recv_transit_bit(struct iscsi_acl *client, int value) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_NEGOTIATE && client->phase != AUTH_PHASE_AUTHENTICATE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (value) client->recv_key_block.transit_bit = 1; else client->recv_key_block.transit_bit = 0; return AUTH_STATUS_NO_ERROR; } int acl_send_transit_bit(struct iscsi_acl *client, int *value) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE && client->phase != AUTH_PHASE_NEGOTIATE && client->phase != AUTH_PHASE_AUTHENTICATE && client->phase != AUTH_PHASE_DONE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } *value = client->send_key_block.transit_bit; return AUTH_STATUS_NO_ERROR; } static int acl_set_option_list(struct iscsi_acl *client, unsigned int opt_count, const int *opt_list, unsigned int *clnt_optn_count, int *clnt_optn_list, unsigned int optn_max_count, int (*chk_option)(int), int (*chk_list)(unsigned int opt_count, const int *opt_list)) { unsigned int i, j; if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE || opt_count > optn_max_count) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } for (i = 0; i < opt_count; i++) if (chk_option(opt_list[i])) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } /* Check for duplicate entries. */ for (i = 0; i < opt_count; i++) for (j = 0; j < opt_count; j++) { if (j == i) continue; if (opt_list[i] == opt_list[j]) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } } /* Check for key specific constraints. */ if (chk_list) if (chk_list(opt_count, opt_list)) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } for (i = 0; i < opt_count; i++) clnt_optn_list[i] = opt_list[i]; *clnt_optn_count = opt_count; return AUTH_STATUS_NO_ERROR; } static int acl_chk_auth_method_list(unsigned int option_count, const int *option_list) { unsigned int i; if (!option_list || option_count < 2) return 1; if (option_list[option_count - 1] != AUTH_OPTION_NONE) return 1; for (i = 0; i < (option_count - 1); i++) if (option_list[i] != AUTH_OPTION_NONE) return 0; return 0; } static void acl_set_auth_method_valid(struct iscsi_acl *client) { unsigned int i, j = 0; int option = 0; /* * Following checks may need to be revised if * authentication options other than CHAP and none * are supported. */ if (client->node_type == TYPE_INITIATOR) { if (client->auth_rmt) /* * If initiator doing authentication, * don't offer authentication option none. */ option = 1; else if (!client->passwd_present) /* * If initiator password not set, * only offer authentication option none. */ option = 2; } if (client->node_type == TYPE_TARGET) { if (client->auth_rmt) /* * If target doing authentication, * don't accept authentication option none. */ option = 1; else /* * If target not doing authentication, * only accept authentication option none. */ option = 2; } for (i = 0; i < client->auth_method_count; i++) { if (option == 1) { if (client->auth_method_list[i] == AUTH_OPTION_NONE) continue; } else if (option == 2) if (client->auth_method_list[i] != AUTH_OPTION_NONE) continue; client->auth_method_valid_list[j++] = client->auth_method_list[i]; } client->auth_method_valid_count = j; acl_init_key_blk(&client->send_key_block); if (client->node_type == TYPE_INITIATOR) { if (client->auth_rmt) { /* * Initiator wants to authenticate target, * always send AuthMethod key. */ client->send_key_block.transit_bit = 0; client->auth_method_valid_neg_role = AUTH_NEG_ROLE_ORIGINATOR; } else { client->send_key_block.transit_bit = 1; client->auth_method_valid_neg_role = client->auth_method_neg_role; } } else { client->send_key_block.transit_bit = 0; client->auth_method_valid_neg_role = AUTH_NEG_ROLE_RESPONDER; } if (client->auth_method_valid_neg_role == AUTH_NEG_ROLE_ORIGINATOR) acl_set_auth_method_key(client, client->auth_method_valid_count, client->auth_method_valid_list); else { int value = AUTH_OPTION_NOT_PRESENT; acl_set_auth_method_key(client, 1, &value); } } static int acl_set_auth_method_list(struct iscsi_acl *client, unsigned int option_count, const int *option_list) { int status; status = acl_set_option_list(client, option_count, option_list, &client->auth_method_count, client->auth_method_list, AUTH_METHOD_MAX_COUNT, acl_chk_auth_mthd_optn, acl_chk_auth_method_list); if (status != AUTH_STATUS_NO_ERROR) return status; /* Setting authMethod affects auth_method_valid. */ acl_set_auth_method_valid(client); return AUTH_STATUS_NO_ERROR; } static int acl_chk_chap_alg_list(unsigned int option_count, const int *option_list) { if (!option_list || option_count < 1) return 1; return 0; } static int acl_set_chap_alg_list(struct iscsi_acl *client, unsigned int option_count, const int *option_list) { return acl_set_option_list(client, option_count, option_list, &client->chap_alg_count, client->chap_alg_list, AUTH_CHAP_ALG_MAX_COUNT, acl_chk_chap_alg_optn, acl_chk_chap_alg_list); } int acl_init(int node_type, int buf_desc_count, struct auth_buffer_desc *buff_desc) { struct iscsi_acl *client; struct auth_str_block *recv_str_blk; struct auth_str_block *send_str_blk; struct auth_large_binary *recv_chap_challenge; struct auth_large_binary *send_chap_challenge; int value_list[2]; if (buf_desc_count != 5 || !buff_desc) return AUTH_STATUS_ERROR; if (!buff_desc[0].address || buff_desc[0].length != sizeof(*client)) return AUTH_STATUS_ERROR; client = (struct iscsi_acl *)buff_desc[0].address; if (!buff_desc[1].address || buff_desc[1].length != sizeof(*recv_str_blk)) return AUTH_STATUS_ERROR; recv_str_blk = (struct auth_str_block *)buff_desc[1].address; if (!buff_desc[2].address || buff_desc[2].length != sizeof(*send_str_blk)) return AUTH_STATUS_ERROR; send_str_blk = (struct auth_str_block *)buff_desc[2].address; if (!buff_desc[3].address || buff_desc[3].length != sizeof(*recv_chap_challenge)) return AUTH_STATUS_ERROR; recv_chap_challenge = (struct auth_large_binary *) buff_desc[3].address; if (!buff_desc[4].address || buff_desc[4].length != sizeof(*send_chap_challenge)) return AUTH_STATUS_ERROR; send_chap_challenge = (struct auth_large_binary *) buff_desc[4].address; memset(client, 0, sizeof(*client)); memset(recv_str_blk, 0, sizeof(*recv_str_blk)); memset(send_str_blk, 0, sizeof(*send_str_blk)); memset(recv_chap_challenge, 0, sizeof(*recv_chap_challenge)); memset(send_chap_challenge, 0, sizeof(*send_chap_challenge)); client->recv_key_block.str_block = recv_str_blk->str_block; client->send_key_block.str_block = send_str_blk->str_block; client->recv_chap_challenge.large_binary = recv_chap_challenge->large_binary; client->send_chap_challenge.large_binary = send_chap_challenge->large_binary; if (node_type != TYPE_INITIATOR && node_type != TYPE_TARGET) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } client->signature = ACL_SIGNATURE; client->node_type = (enum auth_node_type) node_type; client->auth_rmt = 1; client->passwd_present = 0; client->chap_challenge_len = AUTH_CHAP_RSP_LEN; client->ip_sec = 0; client->phase = AUTH_PHASE_CONFIGURE; client->negotiated_auth_method = AUTH_OPTION_NOT_PRESENT; client->negotiated_chap_alg = AUTH_OPTION_NOT_PRESENT; if (client->node_type == TYPE_INITIATOR) client->auth_method_neg_role = AUTH_NEG_ROLE_ORIGINATOR; else /* Initial value ignored for Target. */ client->auth_method_neg_role = AUTH_NEG_ROLE_RESPONDER; value_list[0] = AUTH_METHOD_CHAP; value_list[1] = AUTH_OPTION_NONE; /* * Must call after setting auth_rmt, password, * and auth_method_neg_role */ if (acl_set_auth_method_list(client, 2, value_list) != AUTH_STATUS_NO_ERROR) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } value_list[0] = AUTH_CHAP_ALG_MD5; if (acl_set_chap_alg_list(client, 1, value_list) != AUTH_STATUS_NO_ERROR) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } return AUTH_STATUS_NO_ERROR; } int acl_finish(struct iscsi_acl *client) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; memset(client, 0, sizeof(*client)); return AUTH_STATUS_NO_ERROR; } int acl_set_user_name(struct iscsi_acl *client, const char *username) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE || acl_chk_string(username, AUTH_STR_MAX_LEN, NULL)) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } if (!username) client->username[0] = '\0'; else if (strlcpy(client->username, username, AUTH_STR_MAX_LEN) >= AUTH_STR_MAX_LEN) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } return AUTH_STATUS_NO_ERROR; } int acl_set_passwd(struct iscsi_acl *client, const unsigned char *passwd_data, unsigned int passwd_length) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE || passwd_length > AUTH_STR_MAX_LEN) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } memcpy(client->passwd_data, passwd_data, passwd_length); client->passwd_length = passwd_length; client->passwd_present = 1; /* Setting password may affect auth_method_valid. */ acl_set_auth_method_valid(client); return AUTH_STATUS_NO_ERROR; } int acl_set_auth_rmt(struct iscsi_acl *client, int auth_rmt) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } client->auth_rmt = auth_rmt; /* Setting auth_rmt may affect auth_method_valid. */ acl_set_auth_method_valid(client); return AUTH_STATUS_NO_ERROR; } int acl_set_ip_sec(struct iscsi_acl *client, int ip_sec) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_CONFIGURE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } client->ip_sec = ip_sec; return AUTH_STATUS_NO_ERROR; } int acl_get_dbg_status(struct iscsi_acl *client, int *value) { if (!client || client->signature != ACL_SIGNATURE) return AUTH_STATUS_ERROR; if (client->phase != AUTH_PHASE_DONE) { client->phase = AUTH_PHASE_ERROR; return AUTH_STATUS_ERROR; } *value = client->dbg_status; return AUTH_STATUS_NO_ERROR; } const char * acl_dbg_status_to_text(int dbg_status) { /* * Note: The ordering of this table must match the order * defined by enum auth_dbg_status in iscsi-auth-client.h. */ static char *const dbg_text[AUTH_DBG_STATUS_MAX_COUNT] = { "Debug status not set", "Authentication request passed", "Authentication not enabled", "Authentication request failed", "AuthMethod bad", "CHAP algorithm bad", "Decrypt password failed", "Local password too short with no IPSec", "Unexpected error from authentication server", "Authentication request status bad", "Authentication pass status not valid", "Same key set more than once on send", "Key value too long on send", "Too much data on send", "AuthMethod key expected", "CHAP algorithm key expected", "CHAP identifier expected", "CHAP challenge expected", "CHAP response expected", "CHAP username expected", "AuthMethod key not present", "AuthMethod negotiation failed", "AuthMethod negotiated to none", "CHAP algorithm negotiation failed", "CHAP challange reflected", "Local password same as remote", "Local password not set", "CHAP identifier bad", "CHAP challenge bad", "CHAP response bad", "Unexpected key present", "T bit set on response, but not on previous message", "T bit set on response, but authenticaton not complete", "Message count limit reached on receive", "Same key set more than once on receive", "Key value too long on receive", "Too much data on receive" }; if (dbg_status < 0 || dbg_status >= AUTH_DBG_STATUS_MAX_COUNT) return "Unknown error"; return dbg_text[dbg_status]; } int acl_data(unsigned char *out_data, unsigned int *out_length, unsigned char *in_data, unsigned int in_length) { if (*out_length < in_length) return 1; /* error */ memcpy(out_data, in_data, in_length); *out_length = in_length; return 0; /* no error */ } open-iscsi-2.0.873/usr/auth.h000066400000000000000000000175721175631155400157130ustar00rootroot00000000000000/* * iSCSI Authorization Library * * maintained by open-iscsi@@googlegroups.com * * Originally based on: * Copyright (C) 2001 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef AUTH_CLIENT_H #define AUTH_CLIENT_H struct iscsi_session; enum { AUTH_STR_MAX_LEN = 256, AUTH_STR_BLOCK_MAX_LEN = 1024, AUTH_LARGE_BINARY_MAX_LEN = 1024, AUTH_RECV_END_MAX_COUNT = 10, ACL_SIGNATURE = 0x5984B2E3, AUTH_CHAP_RSP_LEN = 16, }; /* * Note: The ordering of these values are chosen to match * the ordering of the keys as shown in the iSCSI spec. * The order of table key_names in acl_get_key_name() * must match the order defined by enum auth_key_type. */ enum auth_key_type { AUTH_KEY_TYPE_NONE = -1, AUTH_KEY_TYPE_FIRST = 0, AUTH_KEY_TYPE_AUTH_METHOD = AUTH_KEY_TYPE_FIRST, AUTH_KEY_TYPE_CHAP_ALG, AUTH_KEY_TYPE_CHAP_USERNAME, AUTH_KEY_TYPE_CHAP_RSP, AUTH_KEY_TYPE_CHAP_IDENTIFIER, AUTH_KEY_TYPE_CHAP_CHALLENGE, AUTH_KEY_TYPE_MAX_COUNT, AUTH_KEY_TYPE_LAST = AUTH_KEY_TYPE_MAX_COUNT - 1 }; enum { /* Common options for all keys. */ AUTH_OPTION_REJECT = -2, AUTH_OPTION_NOT_PRESENT = -1, AUTH_OPTION_NONE = 1, AUTH_METHOD_CHAP = 2, AUTH_METHOD_MAX_COUNT = 2, AUTH_CHAP_ALG_MD5 = 5, AUTH_CHAP_ALG_MAX_COUNT = 2 }; enum auth_neg_role { AUTH_NEG_ROLE_ORIGINATOR = 1, AUTH_NEG_ROLE_RESPONDER = 2 }; enum auth_status { AUTH_STATUS_NO_ERROR = 0, AUTH_STATUS_ERROR, AUTH_STATUS_PASS, AUTH_STATUS_FAIL, AUTH_STATUS_CONTINUE, }; /* * Note: The order of table dbg_text in acl_dbg_status_to_text() * must match the ordered defined by enum auth_dbg_status. */ enum auth_dbg_status { AUTH_DBG_STATUS_NOT_SET = 0, AUTH_DBG_STATUS_AUTH_PASS, AUTH_DBG_STATUS_AUTH_RMT_FALSE, AUTH_DBG_STATUS_AUTH_FAIL, AUTH_DBG_STATUS_AUTH_METHOD_BAD, AUTH_DBG_STATUS_CHAP_ALG_BAD, AUTH_DBG_STATUS_PASSWD_DECRYPT_FAILED, AUTH_DBG_STATUS_PASSWD_TOO_SHORT_WITH_NO_IPSEC, AUTH_DBG_STATUS_AUTH_SERVER_ERROR, AUTH_DBG_STATUS_AUTH_STATUS_BAD, AUTH_DBG_STATUS_AUTHPASS_NOT_VALID, AUTH_DBG_STATUS_SEND_DUP_SET_KEY_VALUE, AUTH_DBG_STATUS_SEND_STR_TOO_LONG, AUTH_DBG_STATUS_SEND_TOO_MUCH_DATA, AUTH_DBG_STATUS_AUTH_METHOD_EXPECTED, AUTH_DBG_STATUS_CHAP_ALG_EXPECTED, AUTH_DBG_STATUS_CHAP_IDENTIFIER_EXPECTED, AUTH_DBG_STATUS_CHAP_CHALLENGE_EXPECTED, AUTH_DBG_STATUS_CHAP_RSP_EXPECTED, AUTH_DBG_STATUS_CHAP_USERNAME_EXPECTED, AUTH_DBG_STATUS_AUTH_METHOD_NOT_PRESENT, AUTH_DBG_STATUS_AUTH_METHOD_REJECT, AUTH_DBG_STATUS_AUTH_METHOD_NONE, AUTH_DBG_STATUS_CHAP_ALG_REJECT, AUTH_DBG_STATUS_CHAP_CHALLENGE_REFLECTED, AUTH_DBG_STATUS_PASSWD_IDENTICAL, AUTH_DBG_STATUS_LOCAL_PASSWD_NOT_SET, AUTH_DBG_STATUS_CHAP_IDENTIFIER_BAD, AUTH_DBG_STATUS_CHALLENGE_BAD, AUTH_DBG_STATUS_CHAP_RSP_BAD, AUTH_DBG_STATUS_UNEXPECTED_KEY_PRESENT, AUTH_DBG_STATUS_T_BIT_SET_ILLEGAL, AUTH_DBG_STATUS_T_BIT_SET_PREMATURE, AUTH_DBG_STATUS_RECV_MSG_COUNT_LIMIT, AUTH_DBG_STATUS_RECV_DUP_SET_KEY_VALUE, AUTH_DBG_STATUS_RECV_STR_TOO_LONG, AUTH_DBG_STATUS_RECV_TOO_MUCH_DATA, AUTH_DBG_STATUS_MAX_COUNT }; enum auth_node_type { TYPE_INITIATOR = 1, TYPE_TARGET = 2 }; enum auth_phase { AUTH_PHASE_CONFIGURE = 1, AUTH_PHASE_NEGOTIATE, AUTH_PHASE_AUTHENTICATE, AUTH_PHASE_DONE, AUTH_PHASE_ERROR }; enum auth_local_state { AUTH_LOCAL_STATE_SEND_ALG = 1, AUTH_LOCAL_STATE_RECV_ALG, AUTH_LOCAL_STATE_RECV_CHALLENGE, AUTH_LOCAL_STATE_DONE, AUTH_LOCAL_STATE_ERROR }; enum auth_rmt_state { AUTH_RMT_STATE_SEND_ALG = 1, AUTH_RMT_STATE_SEND_CHALLENGE, AUTH_RMT_STATE_RECV_RSP, AUTH_RMT_STATE_DONE, AUTH_RMT_STATE_ERROR }; struct auth_buffer_desc { unsigned int length; void *address; }; struct auth_key { unsigned int present:1; unsigned int processed:1; unsigned int value_set:1; char *string; }; struct auth_large_binary_key { unsigned int length; unsigned char *large_binary; }; struct auth_key_block { unsigned int transit_bit:1; unsigned int dup_set:1; unsigned int str_too_long:1; unsigned int too_much_data:1; unsigned int blk_length:16; char *str_block; struct auth_key key[AUTH_KEY_TYPE_MAX_COUNT]; }; struct auth_str_block { char str_block[AUTH_STR_BLOCK_MAX_LEN]; }; struct auth_large_binary { unsigned char large_binary[AUTH_LARGE_BINARY_MAX_LEN]; }; struct iscsi_acl { unsigned long signature; enum auth_node_type node_type; unsigned int auth_method_count; int auth_method_list[AUTH_METHOD_MAX_COUNT]; enum auth_neg_role auth_method_neg_role; unsigned int chap_alg_count; int chap_alg_list[AUTH_CHAP_ALG_MAX_COUNT]; int auth_rmt; char username[AUTH_STR_MAX_LEN]; int passwd_present; unsigned int passwd_length; unsigned char passwd_data[AUTH_STR_MAX_LEN]; unsigned int chap_challenge_len; int ip_sec; unsigned int auth_method_valid_count; int auth_method_valid_list[AUTH_METHOD_MAX_COUNT]; int auth_method_valid_neg_role; int recv_in_progress_flag; int recv_end_count; struct iscsi_session *session_handle; /* * session_handle can only be * used by acl_chap_auth_request */ enum auth_phase phase; enum auth_local_state local_state; enum auth_rmt_state rmt_state; enum auth_status rmt_auth_status; enum auth_dbg_status dbg_status; int negotiated_auth_method; int negotiated_chap_alg; int auth_rsp_flag; int auth_server_error_flag; int transit_bit_sent_flag; unsigned int send_chap_identifier; struct auth_large_binary_key send_chap_challenge; char chap_username[AUTH_STR_MAX_LEN]; int recv_chap_challenge_status; struct auth_large_binary_key recv_chap_challenge; char scratch_key_value[AUTH_STR_MAX_LEN]; struct auth_key_block recv_key_block; struct auth_key_block send_key_block; }; extern int acl_init(int node_type, int buf_desc_count, struct auth_buffer_desc *buff_desc); extern int acl_finish(struct iscsi_acl *client); extern int acl_recv_begin(struct iscsi_acl *client); extern int acl_recv_end(struct iscsi_acl *client, struct iscsi_session *session_handle); extern const char *acl_get_key_name(int key_type); extern int acl_get_next_key_type(int *key_type); extern int acl_recv_key_value(struct iscsi_acl *client, int key_type, const char *user_key_val); extern int acl_send_key_val(struct iscsi_acl *client, int key_type, int *key_present, char *user_key_val, unsigned int max_length); extern int acl_recv_transit_bit(struct iscsi_acl *client, int value); extern int acl_send_transit_bit(struct iscsi_acl *client, int *value); extern int acl_set_user_name(struct iscsi_acl *client, const char *username); extern int acl_set_passwd(struct iscsi_acl *client, const unsigned char *pw_data, unsigned int pw_len); extern int acl_set_auth_rmt(struct iscsi_acl *client, int auth_rmt); extern int acl_set_ip_sec(struct iscsi_acl *client, int ip_sec); extern int acl_get_dbg_status(struct iscsi_acl *client, int *value); extern const char *acl_dbg_status_to_text(int dbg_status); extern enum auth_dbg_status acl_chap_compute_rsp(struct iscsi_acl *client, int rmt_auth, unsigned int id, unsigned char *challenge_data, unsigned int challenge_len, unsigned char *response_data); extern int acl_chap_auth_request(struct iscsi_acl *client, char *username, unsigned int id, unsigned char *challenge_data, unsigned int challenge_length, unsigned char *response_data, unsigned int rsp_length); extern int acl_data(unsigned char *out_data, unsigned int *out_length, unsigned char *in_data, unsigned int in_length); #endif /* #ifndef ISCSIAUTHCLIENT_H */ open-iscsi-2.0.873/usr/be2iscsi.c000066400000000000000000000024141175631155400164350ustar00rootroot00000000000000/* * be2iscsi helpers * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include "initiator.h" void be2iscsi_create_conn(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; conn_rec_t *conn_rec = &session->nrec.conn[conn->id]; if (conn->max_recv_dlength > 65536) conn->max_recv_dlength = 65536; if (session->first_burst > 8192) session->first_burst = 8192; if (session->max_burst > 262144) session->max_burst = 262144; if (conn->max_xmit_dlength > 65536) conn->max_xmit_dlength = 65536; if (!conn_rec->iscsi.MaxXmitDataSegmentLength || conn_rec->iscsi.MaxXmitDataSegmentLength > 65536) conn_rec->iscsi.MaxXmitDataSegmentLength = 65536; session->erl = 0; session->initial_r2t_en = 1; } open-iscsi-2.0.873/usr/be2iscsi.h000066400000000000000000000002161175631155400164400ustar00rootroot00000000000000#ifndef BE2ISCSI_TRANSPORT #define BE2ISCSI_TRANSPORT struct iscsi_conn; extern void be2iscsi_create_conn(struct iscsi_conn *conn); #endif open-iscsi-2.0.873/usr/config.h000066400000000000000000000163671175631155400162200ustar00rootroot00000000000000/* * iSCSI Configuration * * Copyright (C) 2002 Cisco Systems, Inc. * maintained by linux-iscsi-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef CONFIG_H #define CONFIG_H #include #include #include "types.h" #include "auth.h" /* for the username and password sizes */ #include "list.h" #include "iscsi_proto.h" #include "iscsi_net_util.h" /* ISIDs now have a typed naming authority in them. We use an OUI */ #define DRIVER_ISID_0 0x00 #define DRIVER_ISID_1 0x02 #define DRIVER_ISID_2 0x3D /* number of possible connections per session */ #define ISCSI_CONN_MAX 1 /* max len of interface */ #define ISCSI_MAX_IFACE_LEN 65 /* the following structures store the options set in the config file. * a structure is defined for each logically-related group of options. * if you are adding a new option, first check if it should belong * to one of the existing groups. If it does, add it. If not, define * a new structure. */ /* all authentication-related options should be added to this structure. * this structure is per-session, and can be configured * by TargetName but not Subnet. */ struct iscsi_auth_config { unsigned int authmethod; char username[AUTH_STR_MAX_LEN]; unsigned char password[AUTH_STR_MAX_LEN]; unsigned int password_length; char username_in[AUTH_STR_MAX_LEN]; unsigned char password_in[AUTH_STR_MAX_LEN]; unsigned int password_in_length; }; /* all per-connection timeouts go in this structure. * this structure is per-portal, and can be configured * both by TargetName and Subnet. */ struct iscsi_connection_timeout_config { int login_timeout; int logout_timeout; int auth_timeout; int active_timeout; int noop_out_interval; int noop_out_timeout; }; /* all per-session timeouts go in this structure. * this structure is per-session, and can be configured * by TargetName but not by Subnet. */ struct iscsi_session_timeout_config { int replacement_timeout; }; /* all error handling timeouts go in this structure. * this structure is per-portal, and can be configured * both by TargetName and Subnet. */ struct iscsi_error_timeout_config { int abort_timeout; int host_reset_timeout; int lu_reset_timeout; int tgt_reset_timeout; }; /* all TCP options go in this structure. * this structure is per-portal, and can be configured * both by TargetName and Subnet. */ struct iscsi_tcp_config { int window_size; int type_of_service; /* try to set IP TOS bits */ }; struct iscsi_conn_operational_config { int MaxRecvDataSegmentLength; int MaxXmitDataSegmentLength; int HeaderDigest; int DataDigest; int IFMarker; int OFMarker; }; /* all iSCSI operational params go in this structure. * this structure is per-portal, and can be configured * both by TargetName and Subnet. */ struct iscsi_session_operational_config { int DataPDUInOrder; int DataSequenceInOrder; int protocol; int InitialR2T; int ImmediateData; int FirstBurstLength; int MaxBurstLength; int DefaultTime2Wait; int DefaultTime2Retain; int MaxConnections; int MaxOutstandingR2T; int ERL; int FastAbort; }; #define CONFIG_DIGEST_NEVER 0 #define CONFIG_DIGEST_ALWAYS 1 #define CONFIG_DIGEST_PREFER_ON 2 #define CONFIG_DIGEST_PREFER_OFF 3 struct iscsi_sendtargets_config { int reopen_max; int use_discoveryd; int discoveryd_poll_inval; struct iscsi_auth_config auth; struct iscsi_connection_timeout_config conn_timeo; struct iscsi_conn_operational_config conn_conf; struct iscsi_session_operational_config session_conf; }; struct iscsi_isns_config { int use_discoveryd; int discoveryd_poll_inval; }; struct iscsi_slp_config { char *scopes; char *interfaces; /* for multicast, list of interfaces names, * "all", or "none" */ int poll_interval; struct iscsi_auth_config auth; }; typedef enum iscsi_startup { ISCSI_STARTUP_MANUAL, ISCSI_STARTUP_AUTOMATIC, ISCSI_STARTUP_ONBOOT, } iscsi_startup_e; typedef enum discovery_type { DISCOVERY_TYPE_SENDTARGETS, DISCOVERY_TYPE_ISNS, DISCOVERY_TYPE_OFFLOAD_SENDTARGETS, DISCOVERY_TYPE_SLP, DISCOVERY_TYPE_STATIC, DISCOVERY_TYPE_FW, } discovery_type_e; typedef struct conn_rec { iscsi_startup_e startup; char address[NI_MAXHOST]; int port; struct iscsi_tcp_config tcp; struct iscsi_connection_timeout_config timeo; struct iscsi_conn_operational_config iscsi; } conn_rec_t; typedef struct session_rec { int initial_cmdsn; int reopen_max; int xmit_thread_priority; int cmds_max; int queue_depth; int initial_login_retry_max; int nr_sessions; struct iscsi_auth_config auth; struct iscsi_session_timeout_config timeo; struct iscsi_error_timeout_config err_timeo; struct iscsi_session_operational_config iscsi; struct session_info *info; unsigned sid; /* * This is a flag passed to iscsid. If set, multiple sessions are * allowed to be initiated on this record */ unsigned char multiple; } session_rec_t; #define ISCSI_TRANSPORT_NAME_MAXLEN 16 #define ISCSI_MAX_STR_LEN 80 typedef struct iface_rec { struct list_head list; /* iscsi iface record name */ char name[ISCSI_MAX_IFACE_LEN]; uint32_t iface_num; /* network layer iface name (eth0) */ char netdev[IFNAMSIZ]; char ipaddress[NI_MAXHOST]; char subnet_mask[NI_MAXHOST]; char gateway[NI_MAXHOST]; char bootproto[ISCSI_MAX_STR_LEN]; char ipv6_linklocal[NI_MAXHOST]; char ipv6_router[NI_MAXHOST]; char ipv6_autocfg[NI_MAXHOST]; char linklocal_autocfg[NI_MAXHOST]; char router_autocfg[NI_MAXHOST]; uint16_t vlan_id; uint8_t vlan_priority; char vlan_state[ISCSI_MAX_STR_LEN]; char state[ISCSI_MAX_STR_LEN]; /* 0 = disable, * 1 = enable */ uint16_t mtu; uint16_t port; char port_state[ISCSI_MAX_STR_LEN]; char port_speed[ISCSI_MAX_STR_LEN]; /* * TODO: we may have to make this bigger and interconnect * specific for infinniband */ char hwaddress[ISCSI_HWADDRESS_BUF_SIZE]; char transport_name[ISCSI_TRANSPORT_NAME_MAXLEN]; /* * This is only used for boot now, but the iser guys * can use this for their virtualization idea. */ char alias[TARGET_NAME_MAXLEN + 1]; char iname[TARGET_NAME_MAXLEN + 1]; } iface_rec_t; typedef struct node_rec { struct list_head list; char name[TARGET_NAME_MAXLEN]; int tpgt; iscsi_startup_e startup; int leading_login; session_rec_t session; conn_rec_t conn[ISCSI_CONN_MAX]; iface_rec_t iface; discovery_type_e disc_type; char disc_address[NI_MAXHOST]; int disc_port; } node_rec_t; typedef struct discovery_rec { iscsi_startup_e startup; discovery_type_e type; char address[NI_MAXHOST]; int port; union { struct iscsi_sendtargets_config sendtargets; struct iscsi_slp_config slp; struct iscsi_isns_config isns; } u; } discovery_rec_t; #endif /* CONFIG_H */ open-iscsi-2.0.873/usr/cxgbi.c000066400000000000000000000014611175631155400160270ustar00rootroot00000000000000/* * cxgb3i/cxgb4i helpers * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include "initiator.h" void cxgbi_create_conn(struct iscsi_conn *conn) { /* card can handle up to 15360 bytes */ if (conn->max_recv_dlength > 8192) conn->max_recv_dlength = 8192; } open-iscsi-2.0.873/usr/cxgbi.h000066400000000000000000000002051175631155400160270ustar00rootroot00000000000000#ifndef CXGBI_TRANSPORT #define CXGBI_TRANSPORT struct iscsi_conn; extern void cxgbi_create_conn(struct iscsi_conn *conn); #endif open-iscsi-2.0.873/usr/discovery.c000066400000000000000000001255761175631155400167600ustar00rootroot00000000000000/* * iSCSI Discovery * * Copyright (C) 2002 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "strings.h" #include "types.h" #include "iscsi_proto.h" #include "initiator.h" #include "log.h" #include "idbm.h" #include "iscsi_settings.h" #include "sysdeps.h" #include "fw_context.h" #include "iscsid_req.h" #include "iscsi_util.h" #include "transport.h" #include "iscsi_sysfs.h" #include "iscsi_ipc.h" #include "iface.h" #include "iscsi_timer.h" #include "iscsi_err.h" /* libisns includes */ #include "isns.h" #include "paths.h" #include "message.h" #ifdef SLP_ENABLE #include "iscsi-slp-discovery.h" #endif #define DISCOVERY_NEED_RECONNECT 0xdead0001 static char initiator_name[TARGET_NAME_MAXLEN + 1]; static char initiator_alias[TARGET_NAME_MAXLEN + 1]; static struct iscsi_ev_context ipc_ev_context; static int request_initiator_name(void) { int rc; iscsiadm_req_t req; iscsiadm_rsp_t rsp; memset(initiator_name, 0, sizeof(initiator_name)); initiator_name[0] = '\0'; memset(initiator_alias, 0, sizeof(initiator_alias)); initiator_alias[0] = '\0'; memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_CONFIG_INAME; rc = iscsid_exec_req(&req, &rsp, 1); if (rc) return rc; if (rsp.u.config.var[0] != '\0') strcpy(initiator_name, rsp.u.config.var); memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_CONFIG_IALIAS; rc = iscsid_exec_req(&req, &rsp, 0); if (rc) /* alias is optional so return ok */ return 0; if (rsp.u.config.var[0] != '\0') strcpy(initiator_alias, rsp.u.config.var); return 0; } void discovery_isns_free_servername(void) { if (isns_config.ic_server_name) free(isns_config.ic_server_name); isns_config.ic_server_name = NULL; } int discovery_isns_set_servername(char *address, int port) { char *server; int len; if (port > USHRT_MAX) { log_error("Invalid port %d\n", port); return ISCSI_ERR_INVAL; } /* 5 for port and 1 for colon and 1 for null */ len = strlen(address) + 7; server = calloc(1, len); if (!server) return ISCSI_ERR_NOMEM; snprintf(server, len, "%s:%d", address, port); isns_assign_string(&isns_config.ic_server_name, server); free(server); return 0; } int discovery_isns_query(struct discovery_rec *drec, const char *iname, const char *targetname, struct list_head *rec_list) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_source_t *source; isns_simple_t *qry; isns_client_t *clnt; uint32_t status; int rc, i; isns_config.ic_security = 0; source = isns_source_create_iscsi(iname); if (!source) return ISCSI_ERR_NOMEM; clnt = isns_create_client(NULL, iname); if (!clnt) { rc = ISCSI_ERR_NOMEM; goto free_src; } /* do not retry forever */ isns_socket_set_disconnect_fatal(clnt->ic_socket); if (targetname) isns_attr_list_append_string(&key_attrs, ISNS_TAG_ISCSI_NAME, targetname); else /* Query for all visible targets */ isns_attr_list_append_uint32(&key_attrs, ISNS_TAG_ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); qry = isns_create_query2(clnt, &key_attrs, source); if (!qry) { rc = ISCSI_ERR_NOMEM; goto free_clnt; } isns_query_request_attr_tag(qry, ISNS_TAG_ISCSI_NAME); isns_query_request_attr_tag(qry, ISNS_TAG_ISCSI_NODE_TYPE); isns_query_request_attr_tag(qry, ISNS_TAG_PORTAL_IP_ADDRESS); isns_query_request_attr_tag(qry, ISNS_TAG_PORTAL_TCP_UDP_PORT); isns_query_request_attr_tag(qry, ISNS_TAG_PG_ISCSI_NAME); isns_query_request_attr_tag(qry, ISNS_TAG_PG_PORTAL_IP_ADDR); isns_query_request_attr_tag(qry, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT); isns_query_request_attr_tag(qry, ISNS_TAG_PG_TAG); status = isns_client_call(clnt, &qry); switch (status) { case ISNS_SUCCESS: break; case ISNS_SOURCE_UNKNOWN: /* server requires that we are registered but we are not */ rc = ISCSI_ERR_ISNS_REG_FAILED; goto free_query; default: log_error("iSNS discovery failed: %s", isns_strerror(status)); rc = ISCSI_ERR_ISNS_QUERY; goto free_query; } status = isns_query_response_get_objects(qry, &objects); if (status) { log_error("Unable to extract object list from query " "response: %s\n", isns_strerror(status)); rc = ISCSI_ERR; goto free_query; } for (i = 0; i < objects.iol_count; ++i) { isns_object_t *obj = objects.iol_data[i]; const char *pg_tgt = NULL; struct in6_addr in_addr; uint32_t pg_port = ISCSI_LISTEN_PORT; uint32_t pg_tag = PORTAL_GROUP_TAG_UNKNOWN; char pg_addr[INET6_ADDRSTRLEN + 1]; struct node_rec *rec; if (!isns_object_is_pg(obj)) continue; if (!isns_object_get_string(obj, ISNS_TAG_PG_ISCSI_NAME, &pg_tgt)) { log_debug(1, "Missing target name"); continue; } if (!isns_object_get_ipaddr(obj, ISNS_TAG_PG_PORTAL_IP_ADDR, &in_addr)) { log_debug(1, "Missing addr"); continue; } if (IN6_IS_ADDR_V4MAPPED(&in_addr) || IN6_IS_ADDR_V4COMPAT(&in_addr)) { struct in_addr ipv4; ipv4.s_addr = in_addr.s6_addr32[3]; inet_ntop(AF_INET, &ipv4, pg_addr, sizeof(pg_addr)); } else inet_ntop(AF_INET6, &in_addr, pg_addr, sizeof(pg_addr)); if (!isns_object_get_uint32(obj, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, &pg_port)) { log_debug(1, "Missing port"); continue; } if (!isns_object_get_uint32(obj, ISNS_TAG_PG_TAG, &pg_tag)) { log_debug(1, "Missing tag"); continue; } rec = calloc(1, sizeof(*rec)); if (!rec) { rc = ISCSI_ERR_NOMEM; goto destroy_list; } idbm_node_setup_from_conf(rec); if (drec) { rec->disc_type = drec->type; rec->disc_port = drec->port; strcpy(rec->disc_address, drec->address); } strlcpy(rec->name, pg_tgt, TARGET_NAME_MAXLEN); rec->tpgt = pg_tag; rec->conn[0].port = pg_port; strlcpy(rec->conn[0].address, pg_addr, NI_MAXHOST); list_add_tail(&rec->list, rec_list); } rc = 0; isns_flush_events(); destroy_list: isns_object_list_destroy(&objects); free_query: isns_simple_free(qry); free_clnt: isns_client_destroy(clnt); free_src: isns_source_release(source); return rc; } /* * discovery_isns_reg_node - register/deregister node * @iname: initiator name * @reg: bool indicating if we are supposed to register or deregister node. * * We do a very simple registration just so we can query. */ static int discovery_isns_reg_node(const char *iname, int op_reg) { isns_simple_t *reg; isns_client_t *clnt; isns_source_t *source; int rc = 0, status; isns_config.ic_security = 0; log_debug(1, "trying to %s %s with iSNS server.", op_reg ? "register" : "deregister", iname); source = isns_source_create_iscsi(iname); if (!source) return ISCSI_ERR_NOMEM; clnt = isns_create_client(NULL, iname); if (!clnt) { rc = ISCSI_ERR_NOMEM; goto free_src; } reg = isns_simple_create(op_reg ? ISNS_DEVICE_ATTRIBUTE_REGISTER : ISNS_DEVICE_DEREGISTER, source, NULL); if (!reg) { rc = ISCSI_ERR_NOMEM; goto free_clnt; } isns_attr_list_append_string(®->is_operating_attrs, ISNS_TAG_ISCSI_NAME, iname); if (op_reg) isns_attr_list_append_uint32(®->is_operating_attrs, ISNS_TAG_ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) { log_error("Could not %s %s with iSNS server: %s.", reg ? "register" : "deregister", iname, isns_strerror(status)); rc = ISCSI_ERR_ISNS_REG_FAILED; } else log_debug(1, "%s %s with iSNS server successful.", op_reg ? "register" : "deregister", iname); free_clnt: isns_client_destroy(clnt); free_src: isns_source_release(source); return rc; } int discovery_isns(void *data, struct iface_rec *iface, struct list_head *rec_list) { struct discovery_rec *drec = data; char *iname; int rc, registered = 0; if (iface && strlen(iface->iname)) iname = iface->iname; else { rc = request_initiator_name(); if (rc) { log_error("Cannot perform discovery. Initiatorname " "required."); return rc; } else if (initiator_name[0] == '\0') { log_error("Cannot perform discovery. Invalid " "Initiatorname."); return ISCSI_ERR_INVAL; } iname = initiator_name; } rc = discovery_isns_set_servername(drec->address, drec->port); if (rc) return rc; retry: rc = discovery_isns_query(drec, iname, NULL, rec_list); if (!registered && rc == ISCSI_ERR_ISNS_REG_FAILED) { rc = discovery_isns_reg_node(iname, 1); if (!rc) { registered = 1; goto retry; } } if (registered) discovery_isns_reg_node(iname, 0); discovery_isns_free_servername(); return rc; } int discovery_fw(void *data, struct iface_rec *iface, struct list_head *rec_list) { struct discovery_rec *drec = data; struct boot_context *bcontext; struct list_head targets; struct node_rec *rec; int rc; INIT_LIST_HEAD(&targets); rc = fw_get_targets(&targets); if (rc) { log_error("Could not get list of targets from firmware. " "(err %d)\n", rc); return rc; } if (list_empty(&targets)) return 0; /* * TODO: Do we want to match the iface MAC/netdev with what is in * the firmware or could the user want to bind based on what is * in passed in or in the default ifaces? */ list_for_each_entry(bcontext, &targets, list) { rec = idbm_create_rec_from_boot_context(bcontext); if (!rec) { log_error("Could not convert firmware info to " "node record.\n"); rc = ISCSI_ERR_NOMEM; goto free_targets; } rec->disc_type = drec->type; list_add_tail(&rec->list, rec_list); } free_targets: fw_free_targets(&targets); return rc; } int discovery_offload_sendtargets(int host_no, int do_login, discovery_rec_t *drec) { struct sockaddr_storage ss; char default_port[NI_MAXSERV]; iscsiadm_req_t req; iscsiadm_rsp_t rsp; int rc; log_debug(4, "offload st though host %d to %s", host_no, drec->address); memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_SEND_TARGETS; req.u.st.host_no = host_no; req.u.st.do_login = do_login; /* resolve the DiscoveryAddress to an IP address */ sprintf(default_port, "%d", drec->port); rc = resolve_address(drec->address, default_port, &ss); if (rc) return rc; req.u.st.ss = ss; /* * We only know how ask qla4xxx to do discovery and login * to what it finds. We are not able to get what it finds or * is able to log into so we just send the command and proceed. * * There is a way to just use the hw to send a sendtargets command * and get back the results. We should do this since it would * allows us to then process the results like software iscsi. */ rc = iscsid_exec_req(&req, &rsp, 1); if (rc) { log_error("Could not offload sendtargets to %s.\n", drec->address); iscsi_err_print_msg(rc); return rc; } return 0; } static int iscsi_make_text_pdu(iscsi_session_t *session, struct iscsi_hdr *hdr, char *data, int max_data_length) { struct iscsi_text *text_pdu = (struct iscsi_text *)hdr; /* initialize the PDU header */ memset(text_pdu, 0, sizeof (*text_pdu)); text_pdu->opcode = ISCSI_OP_TEXT; text_pdu->itt = htonl(session->itt); text_pdu->ttt = ISCSI_RESERVED_TAG; text_pdu->cmdsn = htonl(session->cmdsn++); text_pdu->exp_statsn = htonl(session->conn[0].exp_statsn); return 1; } static int request_targets(iscsi_session_t *session) { char data[64]; struct iscsi_text text; struct iscsi_hdr *hdr = (struct iscsi_hdr *) &text; memset(&text, 0, sizeof (text)); memset(data, 0, sizeof (data)); /* make a text PDU with SendTargets=All */ if (!iscsi_make_text_pdu(session, hdr, data, sizeof (data))) { log_error("failed to make a SendTargets PDU"); return 0; } if (!iscsi_add_text(hdr, data, sizeof (data), "SendTargets", "All")) { log_error("failed to add SendTargets text key"); return 0; } text.ttt = ISCSI_RESERVED_TAG; text.flags = ISCSI_FLAG_CMD_FINAL; if (!iscsi_io_send_pdu(&session->conn[0], hdr, ISCSI_DIGEST_NONE, data, ISCSI_DIGEST_NONE, session->conn[0].active_timeout)) { log_error("failed to send SendTargets PDU"); return 0; } return 1; } static int iterate_targets(iscsi_session_t *session, uint32_t ttt) { char data[64]; struct iscsi_text text; struct iscsi_hdr *pdu = (struct iscsi_hdr *) &text; memset(&text, 0, sizeof (text)); memset(data, 0, sizeof (data)); /* make an empty text PDU */ if (!iscsi_make_text_pdu(session, pdu, data, sizeof (data))) { log_error("failed to make an empty text PDU"); return 0; } text.ttt = ttt; text.flags = ISCSI_FLAG_CMD_FINAL; if (!iscsi_io_send_pdu(&session->conn[0], pdu, ISCSI_DIGEST_NONE, data, ISCSI_DIGEST_NONE, session->conn[0].active_timeout)) { log_error("failed to send empty text PDU"); return 0; } return 1; } static int add_portal(struct list_head *rec_list, discovery_rec_t *drec, char *targetname, char *address, char *port, char *tag) { struct sockaddr_storage ss; struct node_rec *rec; if (resolve_address(address, port, &ss)) { log_error("cannot resolve %s", address); return 0; } rec = calloc(1, sizeof(*rec)); if (!rec) return 0; idbm_node_setup_from_conf(rec); rec->disc_type = drec->type; rec->disc_port = drec->port; strcpy(rec->disc_address, drec->address); strlcpy(rec->name, targetname, TARGET_NAME_MAXLEN); if (tag && *tag) rec->tpgt = atoi(tag); else rec->tpgt = PORTAL_GROUP_TAG_UNKNOWN; if (port && *port) rec->conn[0].port = atoi(port); else rec->conn[0].port = ISCSI_LISTEN_PORT; strlcpy(rec->conn[0].address, address, NI_MAXHOST); list_add_tail(&rec->list, rec_list); return 1; } static int add_target_record(char *name, char *end, discovery_rec_t *drec, struct list_head *rec_list) { char *text = NULL; char *nul = name; size_t length; /* address = IPv4 * address = [IPv6] * address = DNSname * address = IPv4:port * address = [IPv6]:port * address = DNSname:port * address = IPv4,tag * address = [IPv6],tag * address = DNSname,tag * address = IPv4:port,tag * address = [IPv6]:port,tag * address = DNSname:port,tag */ log_debug(7, "adding target record %p, end %p", name, end); /* find the end of the name */ while ((nul < end) && (*nul != '\0')) nul++; length = nul - name; if (length > TARGET_NAME_MAXLEN) { log_error("TargetName %s too long, ignoring", name); return 0; } text = name + length; /* skip NULs after the name */ while ((text < end) && (*text == '\0')) text++; /* if no address is provided, use the default */ if (text >= end) { if (drec->address == NULL) { log_error("no default address known for target %s", name); return 0; } else { char default_port[NI_MAXSERV]; sprintf(default_port, "%d", drec->port); if (!add_portal(rec_list, drec, name, drec->address, default_port, NULL)) { log_error("failed to add default portal, " "ignoring target %s", name); return 0; } } /* finished adding the default */ return 1; } /* process TargetAddresses */ while (text < end) { char *next = text + strlen(text) + 1; log_debug(7, "text %p, next %p, end %p, %s", text, next, end, text); if (strncmp(text, "TargetAddress=", 14) == 0) { char *port = NULL; char *tag = NULL; char *address = text + 14; char *temp; if ((tag = strrchr(text, ','))) { *tag = '\0'; tag++; } if ((port = strrchr(text, ':'))) { *port = '\0'; port++; } if (*address == '[') { address++; if ((temp = strrchr(text, ']'))) *temp = '\0'; } if (!add_portal(rec_list, drec, name, address, port, tag)) { log_error("failed to add default portal, " "ignoring target %s", name); return 0; } } else log_error("unexpected SendTargets data: %s", text); text = next; } return 1; } static int process_sendtargets_response(struct str_buffer *sendtargets, int final, discovery_rec_t *drec, struct list_head *rec_list) { char *start = str_buffer_data(sendtargets); char *text = start; char *end = text + str_data_length(sendtargets); char *nul = end - 1; char *record = NULL; int num_targets = 0; if (start == end) { /* no SendTargets data */ goto done; } /* scan backwards to find the last NUL in the data, to ensure we * don't walk off the end. Since key=value pairs can span PDU * boundaries, we're not guaranteed that the end of the data has a * NUL. */ while ((nul > start) && *nul) nul--; if (nul == start) { /* couldn't find anything we can process now, * it's one big partial string */ goto done; } /* find the boundaries between target records (TargetName or final PDU) */ for (;;) { /* skip NULs */ while ((text < nul) && (*text == '\0')) text++; if (text == nul) break; log_debug(7, "processing sendtargets record %p, text %p, line %s", record, text, text); /* look for the start of a new target record */ if (strncmp(text, "TargetName=", 11) == 0) { if (record) { /* send the last record, which we just found * the end of. don't bother passing the * "TargetName=" prefix. */ if (!add_target_record(record + 11, text, drec, rec_list)) { log_error( "failed to add target record"); str_truncate_buffer(sendtargets, 0); goto done; } num_targets++; } record = text; } /* everything up til the next NUL must be part of the * current target record */ while ((text < nul) && (*text != '\0')) text++; } if (record) { if (final) { /* if this is the last PDU of the text sequence, * it also ends a target record */ log_debug(7, "processing final sendtargets record %p, " "line %s", record, record); if (add_target_record (record + 11, text, drec, rec_list)) { num_targets++; record = NULL; str_truncate_buffer(sendtargets, 0); } else { log_error("failed to add target record"); str_truncate_buffer(sendtargets, 0); goto done; } } else { /* remove the parts of the sendtargets buffer we've * processed, and move the parts we haven't to the * beginning of the buffer. */ log_debug(7, "processed %d bytes of sendtargets data, " "%d remaining", (int)(record - str_buffer_data(sendtargets)), (int)(str_buffer_data(sendtargets) + str_data_length(sendtargets) - record)); str_remove_initial(sendtargets, record - str_buffer_data(sendtargets)); } } done: return 1; } static void iscsi_free_session(struct iscsi_session *session) { list_del_init(&session->list); free(session); } static iscsi_session_t * iscsi_alloc_session(struct iscsi_sendtargets_config *config, struct iface_rec *iface, int *rc) { iscsi_session_t *session; *rc = 0; session = calloc(1, sizeof (*session)); if (session == NULL) { *rc = ISCSI_ERR_NOMEM; return NULL; } session->t = iscsi_sysfs_get_transport_by_name(iface->transport_name); if (!session->t) { log_error("iSCSI driver %s is not loaded. Load the module " "then retry the command.\n", iface->transport_name); *rc = ISCSI_ERR_TRANS_NOT_FOUND; goto fail; } INIT_LIST_HEAD(&session->list); /* initialize the session's leading connection */ session->conn[0].id = 0; session->conn[0].socket_fd = -1; session->conn[0].session = session; session->conn[0].login_timeout = config->conn_timeo.login_timeout; session->conn[0].auth_timeout = config->conn_timeo.auth_timeout; session->conn[0].active_timeout = config->conn_timeo.active_timeout; session->conn[0].noop_out_timeout = 0; session->conn[0].noop_out_interval = 0; session->reopen_cnt = config->reopen_max + 1; iscsi_copy_operational_params(&session->conn[0], &config->session_conf, &config->conn_conf); /* OUI and uniqifying number */ session->isid[0] = DRIVER_ISID_0; session->isid[1] = DRIVER_ISID_1; session->isid[2] = DRIVER_ISID_2; session->isid[3] = 0; session->isid[4] = 0; session->isid[5] = 0; if (strlen(iface->iname)) { strcpy(initiator_name, iface->iname); /* MNC TODO add iface alias */ } else { *rc = request_initiator_name(); if (*rc) { log_error("Cannot perform discovery. Initiatorname " "required."); goto fail; } else if (initiator_name[0] == '\0') { log_error("Cannot perform discovery. Invalid " "Initiatorname."); *rc = ISCSI_ERR_INVAL; goto fail; } } iface_copy(&session->nrec.iface, iface); session->initiator_name = initiator_name; session->initiator_alias = initiator_alias; session->portal_group_tag = PORTAL_GROUP_TAG_UNKNOWN; session->type = ISCSI_SESSION_TYPE_DISCOVERY; session->id = -1; /* setup authentication variables for the session*/ *rc = iscsi_setup_authentication(session, &config->auth); if (*rc) goto fail; list_add_tail(&session->list, &session->t->sessions); return session; fail: free(session); return NULL; } static int process_recvd_pdu(struct iscsi_hdr *pdu, discovery_rec_t *drec, struct list_head *rec_list, iscsi_session_t *session, struct str_buffer *sendtargets, int *active, int *valid_text, char *data) { int rc=0; switch (pdu->opcode) { case ISCSI_OP_TEXT_RSP:{ struct iscsi_text_rsp *text_response = (struct iscsi_text_rsp *) pdu; int dlength = ntoh24(pdu->dlength); int final = (text_response->flags & ISCSI_FLAG_CMD_FINAL) || (text_response-> ttt == ISCSI_RESERVED_TAG); size_t curr_data_length; log_debug(4, "discovery session to %s:%d received text" " response, %d data bytes, ttt 0x%x, " "final 0x%x", drec->address, drec->port, dlength, ntohl(text_response->ttt), text_response->flags & ISCSI_FLAG_CMD_FINAL); /* mark how much more data in the sendtargets * buffer is now valid */ curr_data_length = str_data_length(sendtargets); if (str_enlarge_data(sendtargets, dlength)) { log_error("Could not allocate memory to " "process SendTargets response."); rc = 0; goto done; } memcpy(str_buffer_data(sendtargets) + curr_data_length, data, dlength); *valid_text = 1; /* process as much as we can right now */ process_sendtargets_response(sendtargets, final, drec, rec_list); if (final) { /* SendTargets exchange is now complete */ *active = 0; /* from now on, after any reconnect, * assume LUNs may have changed */ } else { /* ask for more targets */ if (!iterate_targets(session, text_response->ttt)) { rc = DISCOVERY_NEED_RECONNECT; goto done; } } break; } default: log_warning( "discovery session to %s:%d received " "unexpected opcode 0x%x", drec->address, drec->port, pdu->opcode); rc = DISCOVERY_NEED_RECONNECT; goto done; } done: return(rc); } #if 0 /* Unused */ /* * Make a best effort to logout the session. */ static void iscsi_logout(iscsi_session_t * session) { struct iscsi_logout logout_req; struct iscsi_logout_rsp logout_resp; int rc; /* * Build logout request header */ memset(&logout_req, 0, sizeof (logout_req)); logout_req.opcode = ISCSI_OP_LOGOUT | ISCSI_OP_IMMEDIATE; logout_req.flags = ISCSI_FLAG_CMD_FINAL | (ISCSI_LOGOUT_REASON_CLOSE_SESSION & ISCSI_FLAG_LOGOUT_REASON_MASK); logout_req.itt = htonl(session->itt); if (++session->itt == ISCSI_RESERVED_TAG) session->itt = 1; logout_req.cmdsn = htonl(session->cmdsn); logout_req.exp_statsn = htonl(++session->conn[0].exp_statsn); /* * Send the logout request */ rc = iscsi_io_send_pdu(&session->conn[0],(struct iscsi_hdr *)&logout_req, ISCSI_DIGEST_NONE, NULL, ISCSI_DIGEST_NONE, 3); if (!rc) { log_error( "iscsid: iscsi_logout - failed to send logout PDU."); return; } /* * Read the logout response */ memset(&logout_resp, 0, sizeof(logout_resp)); rc = iscsi_io_recv_pdu(&session->conn[0], (struct iscsi_hdr *)&logout_resp, ISCSI_DIGEST_NONE, NULL, 0, ISCSI_DIGEST_NONE, 1); if (rc < 0) { log_error("iscsid: logout - failed to receive logout resp"); return; } if (logout_resp.response != ISCSI_LOGOUT_SUCCESS) { log_error("iscsid: logout failed - response = 0x%x", logout_resp.response); } } #endif /* Unused */ static void iscsi_destroy_session(struct iscsi_session *session) { struct iscsi_transport *t = session->t; struct iscsi_conn *conn = &session->conn[0]; int rc; if (session->id == -1) return; if (!(t->caps & CAP_TEXT_NEGO)) { iscsi_io_disconnect(&session->conn[0]); goto done; } log_debug(2, "%s ep disconnect", __FUNCTION__); t->template->ep_disconnect(conn); log_debug(2, "stop conn"); rc = ipc->stop_conn(session->t->handle, session->id, conn->id, STOP_CONN_TERM); if (rc) { log_error("Could not stop conn %d:%d cleanly (err %d)\n", session->id, conn->id, rc); goto done; } log_debug(2, "%s destroy conn", __FUNCTION__); rc = ipc->destroy_conn(session->t->handle, session->id, conn->id); if (rc) { log_error("Could not safely destroy conn %d:%d (err %d)", session->id, conn->id, rc); goto done; } log_debug(2, "%s destroy session", __FUNCTION__); rc = ipc->destroy_session(session->t->handle, session->id); if (rc) log_error("Could not safely destroy session %d (err %d)", session->id, rc); done: if (conn->socket_fd >= 0) { ipc->ctldev_close(); conn->socket_fd = -1; } session->id = -1; } static int iscsi_create_leading_conn(struct iscsi_session *session) { struct iface_rec *iface = &session->nrec.iface; struct iscsi_transport *t = session->t; struct iscsi_conn *conn = &session->conn[0]; uint32_t host_no; int rc, sleep_count = 0; if (!(t->caps & CAP_TEXT_NEGO)) { /* * If the LLD does not support TEXT PDUs then we do * discovery in userspace. */ session->use_ipc = 0; if (!iscsi_io_connect(conn)) return ISCSI_ERR_TRANS; session->id = 1; return 0; } session->use_ipc = 1; /* * for software this is the tcp socket fd set in iscsi_io_connect * and for offload this is the iscsi netlink socket fd */ conn->socket_fd = ipc->ctldev_open(); if (conn->socket_fd < 0) { log_error("Could not open netlink interface (err %d)\n", errno); return ISCSI_ERR_INTERNAL; } host_no = iscsi_sysfs_get_host_no_from_hwinfo(iface, &rc); if (!rc) { /* * if the netdev or mac was set, then we are going to want * to want to bind the all the conns/eps to a specific host * if offload is used. */ session->conn[0].bind_ep = 1; session->hostno = host_no; } rc = iscsi_host_set_net_params(iface, session); if (rc) { log_error("Could not set host net params (err %d)\n", rc); rc = ISCSI_ERR_INTERNAL; goto close_ipc; } /* create interconnect endpoint */ log_debug(2, "%s discovery ep connect\n", __FUNCTION__); rc = t->template->ep_connect(conn, 1); if (rc < 0) { rc = ISCSI_ERR_TRANS; goto close_ipc; } do { rc = t->template->ep_poll(conn, 1); if (rc < 0) { rc = ISCSI_ERR_TRANS; goto disconnect; } else if (rc == 0) { if (sleep_count == conn->login_timeout) { rc = ISCSI_ERR_TRANS_TIMEOUT; goto disconnect; } sleep_count++; sleep(1); } else break; } while (1); log_debug(2, "%s discovery create session\n", __FUNCTION__); /* create kernel structs */ rc = ipc->create_session(session->t->handle, conn->transport_ep_handle, 1, 32, 1, &session->id, &host_no); if (rc) { log_error("Could not create kernel session (err %d).\n", rc); rc = ISCSI_ERR_INTERNAL; goto disconnect; } log_debug(2, "%s discovery created session %u\n", __FUNCTION__, session->id); session->isid[3] = session->id; log_debug(2, "%s discovery create conn\n", __FUNCTION__); rc = ipc->create_conn(t->handle, session->id, conn->id, &conn->id); if (rc) { log_error("Could not create connection (err %d)", rc); rc = ISCSI_ERR_INTERNAL; goto disconnect; } log_debug(2, "%s discovery bind conn\n", __FUNCTION__); if (ipc->bind_conn(t->handle, session->id, conn->id, conn->transport_ep_handle, (conn->id == 0), &rc) || rc) { log_error("Could not bind conn %d:%d to session %d, " "(err %d)", session->id, conn->id, session->id, rc); rc = ISCSI_ERR_INTERNAL; goto disconnect; } /* all set */ return 0; disconnect: t->template->ep_disconnect(conn); if (session->id != -1 && iscsi_sysfs_session_has_leadconn(session->id)) { if (ipc->destroy_conn(session->t->handle, session->id, conn->id)) log_error("Could not safely destroy connection %d:%d", session->id, conn->id); } if (session->id != -1) { if (ipc->destroy_session(session->t->handle, session->id)) log_error("Could not safely destroy session %d", session->id); session->id = -1; } close_ipc: if (conn->socket_fd >= 0) { ipc->ctldev_close(); conn->socket_fd = -1; } log_error("Connection to discovery portal %s failed: %s", conn->host, iscsi_err_to_str(rc)); return rc; } static struct iscsi_ev_context * iscsi_ev_context_get(struct iscsi_conn *conn, int ev_size) { log_debug(2, "%s: ev_size %d\n", __FUNCTION__, ev_size); ipc_ev_context.data = calloc(1, ev_size); if (!ipc_ev_context.data) return NULL; return &ipc_ev_context; } static void iscsi_ev_context_put(struct iscsi_ev_context *ev_context) { if (ev_context->data) free(ev_context->data); ev_context->data = NULL; } static int iscsi_sched_ev_context(struct iscsi_ev_context *ev_context, struct iscsi_conn *conn, unsigned long tmo, int event) { if (event == EV_CONN_RECV_PDU || event == EV_CONN_LOGIN) { conn->recv_context = ev_context; return 0; } return -EIO; } static struct iscsi_ipc_ev_clbk ipc_clbk = { .get_ev_context = iscsi_ev_context_get, .put_ev_context = iscsi_ev_context_put, .sched_ev_context = iscsi_sched_ev_context, }; static int iscsi_wait_for_login(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; struct iscsi_transport *t = session->t; struct pollfd pfd; struct timeval connection_timer; int timeout, rc; uint32_t conn_state; int status = 0; if (!(t->caps & CAP_LOGIN_OFFLOAD)) return 0; iscsi_timer_set(&connection_timer, conn->active_timeout); /* prepare to poll */ memset(&pfd, 0, sizeof(pfd)); pfd.fd = conn->socket_fd; pfd.events = POLLIN | POLLPRI; timeout = iscsi_timer_msecs_until(&connection_timer); login_repoll: log_debug(4, "discovery login process polling fd %d, " "timeout in %f seconds", pfd.fd, timeout / 1000.0); pfd.revents = 0; rc = poll(&pfd, 1, timeout); log_debug(7, "discovery login process returned from poll, rc %d", rc); if (iscsi_timer_expired(&connection_timer)) { log_warning("Discovery login session timed out."); rc = ISCSI_ERR_INTERNAL; goto done; } if (rc > 0) { if (pfd.revents & (POLLIN | POLLPRI)) { timeout = iscsi_timer_msecs_until(&connection_timer); status = ipc->recv_conn_state(conn, &conn_state); if (status == -EAGAIN) goto login_repoll; else if (status < 0) { rc = ISCSI_ERR_TRANS; goto done; } if (conn_state != ISCSI_CONN_STATE_LOGGED_IN) rc = ISCSI_ERR_TRANS; else rc = 0; goto done; } if (pfd.revents & POLLHUP) { log_warning("discovery session" "terminating after hangup"); rc = ISCSI_ERR_TRANS; goto done; } if (pfd.revents & POLLNVAL) { log_warning("discovery POLLNVAL"); rc = ISCSI_ERR_INTERNAL; goto done; } if (pfd.revents & POLLERR) { log_warning("discovery POLLERR"); rc = ISCSI_ERR_INTERNAL; goto done; } } else if (rc < 0) { log_error("Login poll error"); rc = ISCSI_ERR_INTERNAL; goto done; } done: return rc; } static int iscsi_create_session(struct iscsi_session *session, struct iscsi_sendtargets_config *config, char *data, unsigned int data_len) { struct iscsi_conn *conn = &session->conn[0]; int login_status, rc = 0, login_delay = 0; uint8_t status_class = 0, status_detail = 0; unsigned int login_failures = 0; char serv[NI_MAXSERV]; struct iscsi_transport *t = session->t; set_address: /* * copy the saved address to the session, * undoing any temporary redirect */ conn->saddr = conn->failback_saddr; reconnect: /* fix decrement and test */ if (--session->reopen_cnt < 0) { log_error("connection login retries (reopen_max) %d exceeded", config->reopen_max); goto login_failed; } redirect_reconnect: session->cmdsn = 1; session->itt = 1; session->portal_group_tag = PORTAL_GROUP_TAG_UNKNOWN; /* * On reconnect, just destroy the kernel structs and start over. */ iscsi_destroy_session(session); /* slowly back off the frequency of login attempts */ if (login_failures == 0) login_delay = 0; else if (login_failures < 10) login_delay = 1; /* 10 seconds at 1 sec each */ else if (login_failures < 20) login_delay = 2; /* 20 seconds at 2 sec each */ else if (login_failures < 26) login_delay = 5; /* 30 seconds at 5 sec each */ else if (login_failures < 34) login_delay = 15; /* 60 seconds at 15 sec each */ else login_delay = 60; /* after 2 minutes, try once a minute */ getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); if (login_delay) { log_debug(4, "discovery session to %s:%s sleeping for %d " "seconds before next login attempt", conn->host, serv, login_delay); sleep(login_delay); } rc = iscsi_create_leading_conn(session); if (rc) { login_failures++; goto reconnect; } log_debug(1, "connected to discovery address %s", conn->host); log_debug(4, "discovery session to %s:%s starting iSCSI login", conn->host, serv); /* * Need to re-init settings because a previous login could * have set them to what was negotiated for. */ iscsi_copy_operational_params(&session->conn[0], &config->session_conf, &config->conn_conf); if ((session->t->caps & CAP_LOGIN_OFFLOAD)) goto start_conn; status_class = 0; status_detail = 0; rc = ISCSI_ERR_LOGIN; memset(data, 0, data_len); login_status = iscsi_login(session, 0, data, data_len, &status_class, &status_detail); switch (login_status) { case LOGIN_OK: case LOGIN_REDIRECT: break; case LOGIN_IO_ERROR: case LOGIN_REDIRECTION_FAILED: /* try again */ log_warning("retrying discovery login to %s", conn->host); login_failures++; goto set_address; default: case LOGIN_FAILED: case LOGIN_NEGOTIATION_FAILED: case LOGIN_AUTHENTICATION_FAILED: case LOGIN_VERSION_MISMATCH: case LOGIN_INVALID_PDU: log_error("discovery login to %s failed, giving up %d", conn->host, login_status); rc = ISCSI_ERR_FATAL_LOGIN; goto login_failed; } /* check the login status */ switch (status_class) { case ISCSI_STATUS_CLS_SUCCESS: log_debug(4, "discovery login success to %s", conn->host); login_failures = 0; break; case ISCSI_STATUS_CLS_REDIRECT: switch (status_detail) { /* the session IP address was changed by the login * library, so just try again with this portal * config but the new address. */ case ISCSI_LOGIN_STATUS_TGT_MOVED_TEMP: log_warning( "discovery login temporarily redirected to " "%s port %s", conn->host, serv); goto redirect_reconnect; case ISCSI_LOGIN_STATUS_TGT_MOVED_PERM: log_warning( "discovery login permanently redirected to " "%s port %s", conn->host, serv); /* make the new address permanent */ memset(&conn->failback_saddr, 0, sizeof(struct sockaddr_storage)); conn->failback_saddr = conn->saddr; goto redirect_reconnect; default: log_error( "discovery login rejected: redirection type " "0x%x not supported", status_detail); goto set_address; } break; case ISCSI_STATUS_CLS_INITIATOR_ERR: switch (status_detail) { case ISCSI_LOGIN_STATUS_AUTH_FAILED: case ISCSI_LOGIN_STATUS_TGT_FORBIDDEN: log_error("discovery login to %s rejected: " "initiator failed authorization\n", conn->host); rc = ISCSI_ERR_LOGIN_AUTH_FAILED; goto login_failed; default: log_error("discovery login to %s rejected: initiator " "error (%02x/%02x), non-retryable, giving up", conn->host, status_class, status_detail); rc = ISCSI_ERR_FATAL_LOGIN; } goto login_failed; case ISCSI_STATUS_CLS_TARGET_ERR: log_error( "discovery login to %s rejected: " "target error (%02x/%02x)", conn->host, status_class, status_detail); login_failures++; goto reconnect; default: log_error( "discovery login to %s failed, response " "with unknown status class 0x%x, detail 0x%x", conn->host, status_class, status_detail); login_failures++; goto reconnect; } if (!(t->caps & CAP_TEXT_NEGO)) return 0; start_conn: log_debug(2, "%s discovery set params\n", __FUNCTION__); rc = iscsi_session_set_params(conn); if (rc) { log_error("Could not set iscsi params for conn %d:%d (err " "%d)\n", session->id, conn->id, rc); rc = ISCSI_ERR_INTERNAL; goto login_failed; } log_debug(2, "%s discovery start conn\n", __FUNCTION__); if (ipc->start_conn(t->handle, session->id, conn->id, &rc) || rc) { log_error("Cannot start conn %d:%d (err %d)", session->id, conn->id, rc); rc = ISCSI_ERR_INTERNAL; goto login_failed; } rc = iscsi_wait_for_login(conn); if (!rc) return 0; login_failed: iscsi_destroy_session(session); return rc; } int discovery_sendtargets(void *fndata, struct iface_rec *iface, struct list_head *rec_list) { discovery_rec_t *drec = fndata; iscsi_session_t *session; struct pollfd pfd; struct iscsi_hdr pdu_buffer; struct iscsi_hdr *pdu = &pdu_buffer; char *data = NULL; int active = 0, valid_text = 0; struct timeval connection_timer; int timeout; int rc = 0; struct str_buffer sendtargets; unsigned int data_len; struct iscsi_sendtargets_config *config = &drec->u.sendtargets; /* initial setup */ log_debug(1, "starting sendtargets discovery, address %s:%d, ", drec->address, drec->port); memset(&pdu_buffer, 0, sizeof (pdu_buffer)); iscsi_timer_clear(&connection_timer); /* allocate a new session, and initialize default values */ session = iscsi_alloc_session(config, iface, &rc); if (rc) return rc; ipc_ev_context.conn = &session->conn[0]; ipc_register_ev_callback(&ipc_clbk); log_debug(4, "sendtargets discovery to %s:%d using " "isid 0x%02x%02x%02x%02x%02x%02x", drec->address, drec->port, session->isid[0], session->isid[1], session->isid[2], session->isid[3], session->isid[4], session->isid[5]); /* allocate data buffers for SendTargets data */ data = malloc(session->conn[0].max_recv_dlength); if (!data) { rc = ISCSI_ERR_NOMEM; goto free_session; } data_len = session->conn[0].max_recv_dlength; str_init_buffer(&sendtargets, 0); /* resolve the DiscoveryAddress to an IP address */ rc = iscsi_setup_portal(&session->conn[0], drec->address, drec->port); if (rc) { log_error("cannot resolve host name %s", drec->address); goto free_sendtargets; } log_debug(4, "discovery timeouts: login %d, reopen_cnt %d, auth %d.", session->conn[0].login_timeout, session->reopen_cnt, session->conn[0].auth_timeout); reconnect: rc = iscsi_create_session(session, &drec->u.sendtargets, data, data_len); if (rc) goto free_sendtargets; /* reinitialize */ str_truncate_buffer(&sendtargets, 0); /* ask for targets */ if (!request_targets(session)) { goto reconnect; } active = 1; /* set timeouts */ iscsi_timer_set(&connection_timer, session->conn[0].active_timeout); /* prepare to poll */ memset(&pfd, 0, sizeof (pfd)); pfd.fd = session->conn[0].socket_fd; pfd.events = POLLIN | POLLPRI; repoll: timeout = iscsi_timer_msecs_until(&connection_timer); /* block until we receive a PDU, a TCP FIN, a TCP RST, * or a timeout */ log_debug(4, "discovery process %s:%d polling fd %d, " "timeout in %f seconds", drec->address, drec->port, pfd.fd, timeout / 1000.0); pfd.revents = 0; rc = poll(&pfd, 1, timeout); log_debug(7, "discovery process to %s:%d returned from poll, rc %d", drec->address, drec->port, rc); if (iscsi_timer_expired(&connection_timer)) { log_warning("Discovery session to %s:%d timed out.", drec->address, drec->port); rc = ISCSI_ERR_TRANS_TIMEOUT; goto reconnect; } if (rc > 0) { if (pfd.revents & (POLLIN | POLLPRI)) { timeout = iscsi_timer_msecs_until(&connection_timer); rc = iscsi_io_recv_pdu(&session->conn[0], pdu, ISCSI_DIGEST_NONE, data, data_len, ISCSI_DIGEST_NONE, timeout); if (rc == -EAGAIN) goto repoll; else if (rc < 0) { log_debug(1, "discovery session to " "%s:%d failed to recv a PDU " "response, terminating", drec->address, drec->port); rc = ISCSI_ERR_PDU_TIMEOUT; goto free_sendtargets; } /* * process iSCSI PDU received */ rc = process_recvd_pdu(pdu, drec, rec_list, session, &sendtargets, &active, &valid_text, data); if (rc == DISCOVERY_NEED_RECONNECT) goto reconnect; /* reset timers after receiving a PDU */ if (active) { iscsi_timer_set(&connection_timer, session->conn[0].active_timeout); goto repoll; } } if (pfd.revents & POLLHUP) { log_warning("discovery session to %s:%d " "terminating after hangup", drec->address, drec->port); rc = ISCSI_ERR_TRANS; goto free_sendtargets; } if (pfd.revents & POLLNVAL) { log_warning("discovery POLLNVAL"); sleep(1); goto reconnect; } if (pfd.revents & POLLERR) { log_warning("discovery POLLERR"); sleep(1); goto reconnect; } } else if (rc < 0) { log_error("poll error"); rc = ISCSI_ERR; goto free_sendtargets; } log_debug(1, "discovery process to %s:%d exiting", drec->address, drec->port); rc = 0; free_sendtargets: str_free_buffer(&sendtargets); free(data); iscsi_destroy_session(session); free_session: iscsi_free_session(session); return rc; } #ifdef SLP_ENABLE int slp_discovery(struct iscsi_slp_config *config) { struct sigaction action; char *pl; unsigned short flag = 0; memset(&action, 0, sizeof (struct sigaction)); action.sa_sigaction = NULL; action.sa_flags = 0; action.sa_handler = SIG_DFL; sigaction(SIGTERM, &action, NULL); sigaction(SIGINT, &action, NULL); sigaction(SIGPIPE, &action, NULL); action.sa_handler = sighup_handler; sigaction(SIGHUP, &action, NULL); if (iscsi_process_should_exit()) { log_debug(1, "slp discovery process %p exiting", discovery); exit(0); } discovery->pid = getpid(); pl = generate_predicate_list(discovery, &flag); while (1) { if (flag == SLP_MULTICAST_ENABLED) { discovery->flag = SLP_MULTICAST_ENABLED; slp_multicast_srv_query(discovery, pl, GENERIC_QUERY); } if (flag == SLP_UNICAST_ENABLED) { discovery->flag = SLP_UNICAST_ENABLED; slp_unicast_srv_query(discovery, pl, GENERIC_QUERY); } sleep(config->poll_interval); } exit(0); } #endif open-iscsi-2.0.873/usr/discovery.h000066400000000000000000000030061175631155400167440ustar00rootroot00000000000000/* * iSCSI discovery * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef DISCOVERY_H #define DISCOVERY_H /* discovery.c */ struct discovery_rec; struct list_head; struct iface_rec; struct node_rec; struct boot_context; extern int discovery_isns_query(struct discovery_rec *drec, const char *iname, const char *targetname, struct list_head *rec_list); extern void discovery_isns_free_servername(void); extern int discovery_isns_set_servername(char *address, int port); extern int discovery_isns(void *data, struct iface_rec *iface, struct list_head *rec_list); extern int discovery_fw(void *data, struct iface_rec *iface, struct list_head *rec_list); extern int discovery_sendtargets(void *data, struct iface_rec *iface, struct list_head *rec_list); extern int discovery_offload_sendtargets(int host_no, int do_login, struct discovery_rec *drec); #endif /* DISCOVERY_H */ open-iscsi-2.0.873/usr/discoveryd.c000066400000000000000000000653001175631155400171100ustar00rootroot00000000000000/* * iSCSI Initiator discovery daemon * * Copyright (C) 2010 Mike Christie * Copyright (C) 2010 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include "discovery.h" #include "idbm.h" #include "list.h" #include "iscsi_proto.h" #include "sysdeps.h" #include "log.h" #include "session_mgmt.h" #include "iscsi_util.h" #include "event_poll.h" #include "iface.h" #include "session_mgmt.h" #include "session_info.h" #include "isns-proto.h" #include "isns.h" #include "paths.h" #include "message.h" #include "iscsi_err.h" #define DISC_DEF_POLL_INVL 30 static LIST_HEAD(iscsi_targets); static int stop_discoveryd; static LIST_HEAD(isns_initiators); static LIST_HEAD(isns_refresh_list); static char *isns_entity_id = NULL; static uint32_t isns_refresh_interval; static int isns_register_nodes = 1; static void isns_reg_refresh_by_eid_qry(void *data); typedef void (do_disc_and_login_fn)(const char *def_iname, struct discovery_rec *drec, int poll_inval); static int logout_session(void *data, struct list_head *list, struct session_info *info) { struct list_head *rec_list = data; struct node_rec *rec; list_for_each_entry(rec, rec_list, list) { if (iscsi_match_session(rec, info)) return iscsi_logout_portal(info, list); } return -1; } static void discoveryd_stop(void) { struct node_rec *rec, *tmp_rec; int nr_found = 0; if (list_empty(&iscsi_targets)) goto done; /* * User requested to just login and exit. */ if (!stop_discoveryd) goto done; iscsi_logout_portals(&iscsi_targets, &nr_found, 1, logout_session); list_for_each_entry_safe(rec, tmp_rec, &iscsi_targets, list) { list_del(&rec->list); free(rec); } done: exit(0); } static void catch_signal(int signo) { log_debug(1, "%d caught signal -%d...", signo, getpid()); switch (signo) { case SIGTERM: stop_discoveryd = 1; break; default: break; } } static void setup_signal_handler(void) { struct sigaction sa_old; struct sigaction sa_new; sa_new.sa_handler = catch_signal; sigemptyset(&sa_new.sa_mask); sa_new.sa_flags = 0; sigaction(SIGTERM, &sa_new, &sa_old ); } /* * update_sessions - login/logout sessions * @new_rec_list: new target portals recs bound to ifaces * @targetname: if set we only update sessions for this target * @iname: if set we only update session for that initiator * * This will login/logout of portals. When it returns the recs on * new_rec_list will be freed or put on the iscsi_targets list. * * FIXME: if we are hitting a per problem this may be it. With targets * that do a target per lun this could get ugly. */ static void update_sessions(struct list_head *new_rec_list, const char *targetname, const char *iname) { struct node_rec *rec, *tmp_rec; struct list_head stale_rec_list; int nr_found; INIT_LIST_HEAD(&stale_rec_list); /* * Check if a target portal is no longer being sent. * Note: Due to how we reread ifaces this will also detect * changes in ifaces being access through portals. */ list_for_each_entry_safe(rec, tmp_rec, &iscsi_targets, list) { log_debug(7, "Trying to match %s %s to %s %s %s", targetname, iname, rec->name, rec->conn[0].address, rec->iface.name); if (targetname && strcmp(rec->name, targetname)) continue; if (iname) { if (strlen(rec->iface.iname) && strcmp(rec->iface.iname, iname)) continue; else if (strcmp(iname, isns_config.ic_source_name)) continue; } log_debug(5, "Matched %s %s, checking if in new targets.", targetname, iname); if (!idbm_find_rec_in_list(new_rec_list, rec->name, rec->conn[0].address, rec->conn[0].port, &rec->iface)) { log_debug(5, "Not found. Marking for logout"); list_move_tail(&rec->list, &stale_rec_list); } } list_for_each_entry_safe(rec, tmp_rec, new_rec_list, list) { if (!iscsi_check_for_running_session(rec)) iscsi_login_portal_nowait(rec); if (!idbm_find_rec_in_list(&iscsi_targets, rec->name, rec->conn[0].address, rec->conn[0].port, &rec->iface)) { log_debug(5, "%s %s %s %s not on curr target list. " "Adding.", rec->name, rec->conn[0].address, rec->iface.name, rec->iface.iname); list_move_tail(&rec->list, &iscsi_targets); } else { list_del(&rec->list); free(rec); } } if (!list_empty(&stale_rec_list)) { iscsi_logout_portals(&stale_rec_list, &nr_found, 0, logout_session); list_for_each_entry_safe(rec, tmp_rec, &stale_rec_list, list) { list_del(&rec->list); free(rec); } } } static void fork_disc(const char *def_iname, struct discovery_rec *drec, int poll_inval, do_disc_and_login_fn *do_disc_and_login) { pid_t pid; pid = fork(); if (pid == 0) { setup_signal_handler(); do_disc_and_login(def_iname, drec, poll_inval); exit(0); } else if (pid < 0) log_error("Fork failed (err %d - %s). Will not be able " "to perform discovery to %s.\n", errno, strerror(errno), drec->address); else { shutdown_callback(pid); log_debug(1, "iSCSI disc and login helper pid=%d", pid); reap_inc(); } } struct isns_node_list { isns_source_t *source; struct list_head list; }; /* iSNS */ static int isns_build_objs(isns_portal_info_t *portal_info, isns_object_list_t *objs) { struct isns_node_list *node; isns_object_t *inode, *entity; unsigned int i, nportals = 1; int rc = 0; log_debug(7, "isns_build_objs"); /* we currently just use all portals */ if (isns_portal_is_wildcard(portal_info)) { static isns_portal_info_t *iflist; nportals = isns_get_nr_portals(); log_debug(4, "got %d portals", nportals); if (!nportals) return ISCSI_ERR_NO_OBJS_FOUND; iflist = calloc(nportals, sizeof(isns_portal_info_t)); if (!iflist) { log_error("Unable to allocate %d portals.", nportals); return ISCSI_ERR_NOMEM; } nportals = isns_enumerate_portals(iflist, nportals); if (nportals == 0) { log_error("Unable to enumerate portals - " "no usable interfaces found\n"); free(iflist); return ISCSI_ERR_NO_OBJS_FOUND; } for (i = 0; i < nportals; ++i) { iflist[i].addr.sin6_port = portal_info->addr.sin6_port; iflist[i].proto = portal_info->proto; } portal_info = iflist; } if (!isns_entity_id) { isns_entity_id = calloc(1, 256); if (!isns_entity_id) return ISCSI_ERR_NOMEM; rc = getnameinfo((struct sockaddr *) &portal_info->addr, sizeof(portal_info->addr), isns_entity_id, 256, NULL, 0, 0); if (rc) { free(isns_entity_id); isns_entity_id = NULL; log_error("Could not get hostname for EID."); return ISCSI_ERR; } } entity = isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, isns_entity_id); if (!entity) { log_error("Could not create iSNS entity."); return ISCSI_ERR_NOMEM; } isns_object_list_append(objs, entity); for (i = 0; i < nportals; ++i, ++portal_info) { isns_object_t *portal; portal = isns_create_portal(portal_info, entity); if (!portal) { rc = ISCSI_ERR_NOMEM; goto fail; } isns_object_list_append(objs, portal); if (!isns_object_set_uint32(portal, ISNS_TAG_SCN_PORT, isns_portal_tcpudp_port(portal_info))) { rc = ISCSI_ERR_INVAL; goto fail; } } list_for_each_entry(node, &isns_initiators, list) { inode = isns_create_storage_node2(node->source, ISNS_ISCSI_INITIATOR_MASK, NULL); if (!inode) { rc = ISCSI_ERR_NOMEM; goto fail; } isns_object_list_append(objs, inode); } return 0; fail: isns_object_list_destroy(objs); return rc; } struct isns_qry_data { const char *iname; const char *targetname; }; static int isns_query_node(void *data, struct iface_rec *iface, struct list_head *recs) { struct isns_qry_data *qry_data = data; int is_def_iname = 0; const char *iname; if (qry_data->iname) { if (!strcmp(qry_data->iname, isns_config.ic_source_name)) is_def_iname = 1; if ((!is_def_iname || strlen(iface->iname)) && strcmp(iface->iname, qry_data->iname)) return 0; iname = qry_data->iname; } else { if (strlen(iface->iname)) iname = iface->iname; else iname = isns_config.ic_source_name; } return discovery_isns_query(NULL, iname, qry_data->targetname, recs); } static int isns_disc_new_portals(const char *targetname, const char *iname) { struct list_head ifaces, rec_list; struct iface_rec *iface, *tmp_iface; struct isns_qry_data qry_data; int rc; INIT_LIST_HEAD(&rec_list); INIT_LIST_HEAD(&ifaces); qry_data.targetname = targetname; qry_data.iname = iname; iface_link_ifaces(&ifaces); rc = idbm_bind_ifaces_to_nodes(isns_query_node, &qry_data, &ifaces, &rec_list); if (rc) { log_error("Could not perform iSNS DevAttrQuery for node %s.", targetname); goto free_ifaces; } update_sessions(&rec_list, targetname, iname); rc = 0; free_ifaces: list_for_each_entry_safe(iface, tmp_iface, &ifaces, list) { list_del(&iface->list); free(iface); } return rc; } static void isns_reg_refresh_with_disc(void *data) { int retries = 0, rc; log_debug(1, "Refresh registration using DevAttrQuery"); /* * it is ok to block here since we are not expecting SCNs * from the server. */ do { /* * Some servers do not support SCNs so we ping * the server by doing discovery. */ rc = isns_disc_new_portals(NULL, NULL); if (rc) { log_debug(4, "Registration refresh using DevAttrQuery " "failed (retires %d) err %d", retries, rc); sleep(1); retries++; continue; } } while (rc && retries < 3); if (rc) /* * Try to reregister from scratch. */ isns_register_nodes = 1; } struct isns_refresh_data { isns_client_t *clnt; isns_simple_t *qry; uint32_t xid; uint32_t interval; time_t start_time; struct list_head list; }; static void isns_free_refresh_data(struct isns_refresh_data *refresh_data) { list_del(&refresh_data->list); if (refresh_data->qry) isns_simple_free(refresh_data->qry); if (refresh_data->clnt) isns_client_destroy(refresh_data->clnt); free(refresh_data); } static struct isns_refresh_data *isns_find_refresh_data(uint32_t xid) { struct isns_refresh_data *refresh_data; list_for_each_entry(refresh_data, &isns_refresh_list, list) { if (refresh_data->xid == xid) return refresh_data; } return NULL; } static void isns_eid_qry_rsp(uint32_t xid, int status, isns_simple_t *rsp) { struct isns_refresh_data *refresh_data; refresh_data = isns_find_refresh_data(xid); if (!refresh_data) { log_error("EID Query respond could not match xid"); return; } if (refresh_data->clnt) { isns_client_destroy(refresh_data->clnt); refresh_data->clnt = NULL; } if (!rsp || status != ISNS_SUCCESS) { log_debug(1, "Registration refresh using eid qry failed: %s", isns_strerror(status)); isns_add_oneshot_timer(2, isns_reg_refresh_by_eid_qry, refresh_data); return; } log_debug(1, "eid qry successful"); refresh_data->start_time = time(NULL); isns_add_oneshot_timer(isns_refresh_interval, isns_reg_refresh_by_eid_qry, refresh_data); } static void isns_reg_refresh_by_eid_qry(void *data) { struct isns_refresh_data *refresh_data = data; isns_attr_list_t qry_key = ISNS_ATTR_LIST_INIT; isns_simple_t *qry; isns_client_t *clnt; int status, timeout; log_debug(1, "Refresh registration using eid qry"); if (refresh_data->start_time + refresh_data->interval <= time(NULL)) { log_error("Could not refresh registration with server " "before registration period. Starting new " "registration."); isns_free_refresh_data(refresh_data); isns_register_nodes = 1; return; } clnt = isns_create_default_client(NULL); if (!clnt) { log_error("iSNS registration refresh failed. Could not " "connect to server."); goto rearm; } refresh_data->clnt = clnt; /* * if a operation has failed we will want to adjust timers * and possibly reregister. */ isns_socket_set_report_failure(clnt->ic_socket); /* * if this is a retry or re-refresh then there will be a qry */ qry = refresh_data->qry; if (qry) goto send; isns_attr_list_append_string(&qry_key, ISNS_TAG_ENTITY_IDENTIFIER, isns_entity_id); qry = isns_create_query(clnt, &qry_key); isns_attr_list_destroy(&qry_key); if (!qry) goto rearm; isns_query_request_attr_tag(qry, ISNS_TAG_ENTITY_PROTOCOL); refresh_data->qry = qry; send: timeout = (refresh_data->start_time + refresh_data->interval) - time(NULL); status = isns_simple_transmit(clnt->ic_socket, qry, NULL, timeout, isns_eid_qry_rsp); if (status == ISNS_SUCCESS) { log_debug(7, "sent eid qry with xid %u", qry->is_xid); refresh_data->xid = qry->is_xid; return; } rearm: if (refresh_data->clnt) { isns_client_destroy(refresh_data->clnt); refresh_data->clnt = NULL; } log_debug(1, "Could not send eid qry to refresh registration."); isns_add_oneshot_timer(2, isns_reg_refresh_by_eid_qry, refresh_data); } static int isns_setup_registration_refresh(isns_simple_t *rsp, int poll_inval) { isns_object_list_t objs = ISNS_OBJECT_LIST_INIT; struct isns_refresh_data *refresh_data; int status, i, rc = 0; uint32_t interval = 0; status = isns_query_response_get_objects(rsp, &objs); if (status) { log_error("Unable to extract object list from " "registration response: %s\n", isns_strerror(status)); return ISCSI_ERR; } for (i = 0; i < objs.iol_count; ++i) { isns_object_t *obj = objs.iol_data[i]; if (!isns_object_is_entity(obj)) continue; if (isns_object_get_uint32(obj, ISNS_TAG_REGISTRATION_PERIOD, &interval)) break; } if (!interval) goto free_objs; refresh_data = calloc(1, sizeof(*refresh_data)); if (!refresh_data) { rc = ISCSI_ERR_NOMEM; goto free_objs; } INIT_LIST_HEAD(&refresh_data->list); list_add_tail(&refresh_data->list, &isns_refresh_list); refresh_data->start_time = time(NULL); /* * Several servers do not support SCNs properly, so for the * registration period refresh we do a DevAttrQuery for all targets * if the poll_inval is greater than 0. * * If the target does support SCNs then we just send a query * for our entity's protocol. */ /* we cut in half to give us time to handle errors */ isns_refresh_interval = interval / 2; if (!isns_refresh_interval) { log_warning("iSNS Registration Period only %d seconds.", interval); isns_refresh_interval = interval; } refresh_data->interval = interval; if (poll_inval > 0) { /* user wants to override server and do disc */ if (isns_refresh_interval > poll_inval) isns_refresh_interval = poll_inval; isns_add_timer(isns_refresh_interval, isns_reg_refresh_with_disc, refresh_data); } else /* * user wants to use server value so we just ping * with a simple qry */ isns_add_oneshot_timer(isns_refresh_interval, isns_reg_refresh_by_eid_qry, refresh_data); log_debug(5, "Got registration period of %u " "internval. Using interval of %u", interval, isns_refresh_interval); free_objs: isns_flush_events(); isns_object_list_destroy(&objs); return rc; } static void isns_cancel_refresh_timers(void) { isns_cancel_timer(isns_reg_refresh_with_disc, NULL); isns_cancel_timer(isns_reg_refresh_by_eid_qry, NULL); } static int isns_register_objs(isns_client_t *clnt, isns_object_list_t *objs, int poll_inval) { struct isns_node_list *node; isns_object_t *entity = NULL; isns_simple_t *reg; unsigned int i; int status, rc = 0; log_debug(7, "isns_register_objs"); for (i = 0; i < objs->iol_count; ++i) { if (isns_object_is_entity(objs->iol_data[i])) { entity = objs->iol_data[i]; break; } } reg = isns_create_registration(clnt, entity); if (!reg) return ISCSI_ERR_NOMEM; for (i = 0; i < objs->iol_count; ++i) isns_registration_add_object(reg, objs->iol_data[i]); isns_registration_set_replace(reg, 1); status = isns_simple_call(clnt->ic_socket, ®); if (status != ISNS_SUCCESS) { log_error("Could not register with iSNS server: %s", isns_strerror(status)); rc = ISCSI_ERR; goto free_reg; } log_debug(4, "Registered objs"); if (!poll_inval) goto free_reg; rc = isns_setup_registration_refresh(reg, poll_inval); if (rc) goto free_reg; list_for_each_entry(node, &isns_initiators, list) { isns_simple_free(reg); reg = isns_create_scn_registration2(clnt, ISNS_SCN_OBJECT_UPDATED_MASK | ISNS_SCN_OBJECT_ADDED_MASK | ISNS_SCN_OBJECT_REMOVED_MASK | ISNS_SCN_TARGET_AND_SELF_ONLY_MASK, node->source); if (!reg) { isns_cancel_refresh_timers(); rc = ISCSI_ERR_NOMEM; goto done; } status = isns_simple_call(clnt->ic_socket, ®); if (status != ISNS_SUCCESS) { log_error("SCN registration for node %s failed: %s\n", isns_source_name(node->source), isns_strerror(status)); /* * if the user was going to poll then ignore error * since user was probably using polling because SCNs * were not supported by server */ if (poll_inval < 0) { isns_cancel_refresh_timers(); rc = ISCSI_ERR; break; } } log_debug(4, "Registered %s for SCNs", isns_source_name(node->source)); } free_reg: isns_simple_free(reg); done: return rc; } static int isns_scn_register(isns_socket_t *svr_sock, int poll_inval) { isns_object_list_t objs = ISNS_OBJECT_LIST_INIT; isns_portal_info_t portal_info; isns_client_t *clnt; int rc; clnt = isns_create_default_client(NULL); if (!clnt) { log_error("iSNS setup failed. Could not connect to server."); return ISCSI_ERR_TRANS; } isns_socket_set_disconnect_fatal(clnt->ic_socket); log_debug(7, "isns_scn_register"); if (!isns_socket_get_portal_info(svr_sock, &portal_info)) { log_error("Could not get portal info for iSNS registration."); rc = ISCSI_ERR_NO_OBJS_FOUND; goto destroy_clnt; } rc = isns_build_objs(&portal_info, &objs); if (rc) goto destroy_clnt; rc = isns_register_objs(clnt, &objs, poll_inval); isns_object_list_destroy(&objs); if (!rc) log_warning("iSNS: Registered network entity with EID %s with " "server.", isns_entity_id); destroy_clnt: isns_client_destroy(clnt); return rc; } static isns_source_t *isns_lookup_node(char *iname) { struct isns_node_list *node; list_for_each_entry(node, &isns_initiators, list) { if (!strcmp(iname, isns_source_name(node->source))) return node->source; } return NULL; } static struct isns_node_list *isns_create_node(const char *iname) { isns_source_t *source; struct isns_node_list *node; source = isns_source_create_iscsi(iname); if (!source) return NULL; node = calloc(1, sizeof(*node)); if (!node) { isns_source_release(source); return NULL; } INIT_LIST_HEAD(&node->list); node->source = source; return node; } static int isns_create_node_list(const char *def_iname) { struct iface_rec *iface, *tmp_iface; struct list_head ifaces; struct isns_node_list *node, *tmp_node; int rc = 0; INIT_LIST_HEAD(&ifaces); iface_link_ifaces(&ifaces); if (def_iname) { node = isns_create_node(def_iname); if (!node) { rc = ISCSI_ERR_NOMEM; goto fail; } list_add_tail(&node->list, &isns_initiators); } list_for_each_entry(iface, &ifaces, list) { if (strlen(iface->iname) && !isns_lookup_node(iface->iname)) { node = isns_create_node(iface->iname); if (!node) { rc = ISCSI_ERR_NOMEM; goto fail; } list_add_tail(&node->list, &isns_initiators); } } /* fix me */ rc = 0; goto done; fail: list_for_each_entry_safe(node, tmp_node, &isns_initiators, list) { list_del(&node->list); free(node); } done: list_for_each_entry_safe(iface, tmp_iface, &ifaces, list) { list_del(&iface->list); free(iface); } return rc; } static void isns_scn_callback(isns_db_t *db, uint32_t bitmap, isns_object_template_t *node_type, const char *node_name, const char *dst_name) { log_error("SCN for initiator: %s (Target: %s, Event: %s.)", dst_name, node_name, isns_event_string(bitmap)); isns_disc_new_portals(node_name, dst_name); } static void isns_clear_refresh_list(void) { struct isns_refresh_data *refresh_data, *tmp_refresh; list_for_each_entry_safe(refresh_data, tmp_refresh, &isns_refresh_list, list) isns_free_refresh_data(refresh_data); } static int isns_scn_recv(isns_server_t *svr, isns_socket_t *svr_sock, int poll_inval) { isns_message_t *msg, *rsp; struct timeval timeout = { 0, 0 }; time_t now, then, next_timeout; unsigned int function; int rc = 0; log_debug(1, "isns_scn_recv"); while (!stop_discoveryd) { /* reap disc/login procs */ reap_proc(); /* * timer func could force a scn registration so check timers * first */ then = isns_run_timers(); now = time(NULL); next_timeout = now + 3600; if (then && then < next_timeout) next_timeout = then; if (isns_register_nodes) { isns_clear_refresh_list(); /* * it is ok to block here, because the server * should have unregistered us or this is our * first time registerting. */ rc = isns_scn_register(svr_sock, poll_inval); if (rc) { sleep(5); continue; } isns_disc_new_portals(NULL, NULL); if (!poll_inval) break; isns_register_nodes = 0; /* * the scn reg may have added timers or changed * timeout values so recheck. */ continue; } /* Determine how long we can sleep */ if (next_timeout <= now) continue; timeout.tv_sec = next_timeout - now; if ((msg = isns_recv_message(&timeout)) == NULL) continue; function = isns_message_function(msg); if (function != ISNS_STATE_CHANGE_NOTIFICATION) { log_warning("Discarding unexpected %s message\n", isns_function_name(function)); isns_message_release(msg); continue; } if ((rsp = isns_process_message(svr, msg)) != NULL) { isns_socket_t *sock = isns_message_socket(msg); isns_socket_send(sock, rsp); isns_message_release(rsp); } isns_message_release(msg); } log_debug(1, "isns_scn_recv done"); reap_proc(); return rc; } #define ISNS_EVENTD_PIDFILE ISNS_RUNDIR"/iscsid.isns.pid" #define ISNS_EVENTD_CTL ISNS_RUNDIR"/iscsid.isns.isnsctl" static int isns_eventd(const char *def_iname, char *disc_addr, int port, int poll_inval) { static isns_socket_t *svr_sock; isns_server_t *svr; isns_db_t *db; struct isns_node_list *tmp_node, *node; int rc = 0; isns_create_node_list(def_iname); if (list_empty(&isns_initiators)) { log_error("iSNS registration failed. Initiatorname not set."); return ISCSI_ERR_INVAL; } /* use def_iname or if not set the first iface's iname for the src */ node = list_entry(isns_initiators.next, struct isns_node_list, list); isns_assign_string(&isns_config.ic_source_name, isns_source_name(node->source)); isns_config.ic_security = 0; isns_config.ic_pidfile = ISNS_EVENTD_PIDFILE; isns_config.ic_control_socket = ISNS_EVENTD_CTL; if (discovery_isns_set_servername(disc_addr, port)) { rc = ISCSI_ERR_NOMEM; goto fail; } isns_write_pidfile(isns_config.ic_pidfile); db = isns_db_open(NULL); if (!db) { log_error("iSNS setup failed. Could not create db."); rc = ISCSI_ERR_NOMEM; goto fail; } svr = isns_create_server(node->source, db, &isns_callback_service_ops); if (!svr) { log_error("iSNS setup failed. Could not create server."); rc = ISCSI_ERR_TRANS; goto fail; } isns_server_set_scn_callback(svr, isns_scn_callback); svr_sock = isns_create_server_socket(NULL, NULL, AF_INET6, SOCK_DGRAM); if (!svr_sock) { log_error("iSNS setup failed. Could not create server socket."); rc = ISCSI_ERR_TRANS; goto fail; } rc = isns_scn_recv(svr, svr_sock, poll_inval); isns_cancel_refresh_timers(); fail: isns_clear_refresh_list(); list_for_each_entry_safe(node, tmp_node, &isns_initiators, list) { list_del(&node->list); free(node); } if (isns_entity_id) free(isns_entity_id); isns_entity_id = NULL; discovery_isns_free_servername(); if (isns_config.ic_source_name) free(isns_config.ic_source_name); isns_config.ic_source_name = NULL; return rc; } static void start_isns(const char *def_iname, struct discovery_rec *drec, int poll_inval) { int rc, port = drec->port; if (port < 0) port = ISNS_DEFAULT_PORT; rc = isns_eventd(def_iname, drec->address, port, poll_inval); log_debug(1, "start isns done %d.", rc); discoveryd_stop(); } /* SendTargets */ static void __do_st_disc_and_login(struct discovery_rec *drec) { struct list_head rec_list, setup_ifaces; struct iface_rec *iface, *tmp_iface; int rc; INIT_LIST_HEAD(&rec_list); INIT_LIST_HEAD(&setup_ifaces); /* * The disc daemon will try again in poll_interval secs * so no need to retry here */ drec->u.sendtargets.reopen_max = 0; iface_link_ifaces(&setup_ifaces); /* * disc code assumes this is not set and wants to use * the userspace IO code. */ ipc = NULL; rc = idbm_bind_ifaces_to_nodes(discovery_sendtargets, drec, &setup_ifaces, &rec_list); if (rc) { log_error("Could not perform SendTargets to %s:%d.", drec->address, drec->port); goto free_ifaces; } update_sessions(&rec_list, NULL, NULL); free_ifaces: list_for_each_entry_safe(iface, tmp_iface, &setup_ifaces, list) { list_del(&iface->list); free(iface); } } static void do_st_disc_and_login(const char *def_iname, struct discovery_rec *drec, int poll_inval) { if (poll_inval < 0) poll_inval = DISC_DEF_POLL_INVL; do { __do_st_disc_and_login(drec); if (!poll_inval) break; } while (!stop_discoveryd && !sleep(poll_inval)); discoveryd_stop(); } static int st_start(void *data, struct discovery_rec *drec) { log_debug(1, "st_start %s:%d %d", drec->address, drec->port, drec->u.sendtargets.use_discoveryd); if (!drec->u.sendtargets.use_discoveryd) return ISCSI_ERR_INVAL; fork_disc(NULL, drec, drec->u.sendtargets.discoveryd_poll_inval, do_st_disc_and_login); return 0; } static void discoveryd_st_start(void) { idbm_for_each_st_drec(NULL, st_start); } static int isns_start(void *data, struct discovery_rec *drec) { log_debug(1, "isns_start %s:%d %d", drec->address, drec->port, drec->u.isns.use_discoveryd); if (!drec->u.isns.use_discoveryd) return ISCSI_ERR_INVAL; fork_disc(data, drec, drec->u.isns.discoveryd_poll_inval, start_isns); return 0; } static void discoveryd_isns_start(const char *def_iname) { idbm_for_each_isns_drec((void *)def_iname, isns_start); } void discoveryd_start(const char *def_iname) { discoveryd_isns_start(def_iname); discoveryd_st_start(); } open-iscsi-2.0.873/usr/discoveryd.h000066400000000000000000000001541175631155400171110ustar00rootroot00000000000000#ifndef _DISC_DAEMON_H #define _DISC_DAEMON_H extern void discoveryd_start(const char *def_iname); #endif open-iscsi-2.0.873/usr/ethtool-copy.h000066400000000000000000000460551175631155400173760ustar00rootroot00000000000000/* * ethtool.h: Defines for Linux ethtool. * * Copyright (C) 1998 David S. Miller (davem@redhat.com) * Copyright 2001 Jeff Garzik * Portions Copyright 2001 Sun Microsystems (thockin@sun.com) * Portions Copyright 2002 Intel (eli.kupermann@intel.com, * christopher.leech@intel.com, * scott.feldman@intel.com) * Portions Copyright (C) Sun Microsystems 2008 */ #ifndef _LINUX_ETHTOOL_H #define _LINUX_ETHTOOL_H #include /* This should work for both 32 and 64 bit userland. */ struct ethtool_cmd { __u32 cmd; __u32 supported; /* Features this interface supports */ __u32 advertising; /* Features this interface advertises */ __u16 speed; /* The forced speed, 10Mb, 100Mb, gigabit */ __u8 duplex; /* Duplex, half or full */ __u8 port; /* Which connector port */ __u8 phy_address; __u8 transceiver; /* Which transceiver to use */ __u8 autoneg; /* Enable or disable autonegotiation */ __u8 mdio_support; __u32 maxtxpkt; /* Tx pkts before generating tx int */ __u32 maxrxpkt; /* Rx pkts before generating rx int */ __u16 speed_hi; __u8 eth_tp_mdix; __u8 reserved2; __u32 lp_advertising; /* Features the link partner advertises */ __u32 reserved[2]; }; static inline void ethtool_cmd_speed_set(struct ethtool_cmd *ep, __u32 speed) { ep->speed = (__u16)speed; ep->speed_hi = (__u16)(speed >> 16); } static inline __u32 ethtool_cmd_speed(struct ethtool_cmd *ep) { return (ep->speed_hi << 16) | ep->speed; } #define ETHTOOL_BUSINFO_LEN 32 /* these strings are set to whatever the driver author decides... */ struct ethtool_drvinfo { __u32 cmd; char driver[32]; /* driver short name, "tulip", "eepro100" */ char version[32]; /* driver version string */ char fw_version[32]; /* firmware version string, if applicable */ char bus_info[ETHTOOL_BUSINFO_LEN]; /* Bus info for this IF. */ /* For PCI devices, use pci_name(pci_dev). */ char reserved1[32]; char reserved2[12]; __u32 n_priv_flags; /* number of flags valid in ETHTOOL_GPFLAGS */ __u32 n_stats; /* number of u64's from ETHTOOL_GSTATS */ __u32 testinfo_len; __u32 eedump_len; /* Size of data from ETHTOOL_GEEPROM (bytes) */ __u32 regdump_len; /* Size of data from ETHTOOL_GREGS (bytes) */ }; #define SOPASS_MAX 6 /* wake-on-lan settings */ struct ethtool_wolinfo { __u32 cmd; __u32 supported; __u32 wolopts; __u8 sopass[SOPASS_MAX]; /* SecureOn(tm) password */ }; /* for passing single values */ struct ethtool_value { __u32 cmd; __u32 data; }; /* for passing big chunks of data */ struct ethtool_regs { __u32 cmd; __u32 version; /* driver-specific, indicates different chips/revs */ __u32 len; /* bytes */ __u8 data[0]; }; /* for passing EEPROM chunks */ struct ethtool_eeprom { __u32 cmd; __u32 magic; __u32 offset; /* in bytes */ __u32 len; /* in bytes */ __u8 data[0]; }; /* for configuring coalescing parameters of chip */ struct ethtool_coalesce { __u32 cmd; /* ETHTOOL_{G,S}COALESCE */ /* How many usecs to delay an RX interrupt after * a packet arrives. If 0, only rx_max_coalesced_frames * is used. */ __u32 rx_coalesce_usecs; /* How many packets to delay an RX interrupt after * a packet arrives. If 0, only rx_coalesce_usecs is * used. It is illegal to set both usecs and max frames * to zero as this would cause RX interrupts to never be * generated. */ __u32 rx_max_coalesced_frames; /* Same as above two parameters, except that these values * apply while an IRQ is being serviced by the host. Not * all cards support this feature and the values are ignored * in that case. */ __u32 rx_coalesce_usecs_irq; __u32 rx_max_coalesced_frames_irq; /* How many usecs to delay a TX interrupt after * a packet is sent. If 0, only tx_max_coalesced_frames * is used. */ __u32 tx_coalesce_usecs; /* How many packets to delay a TX interrupt after * a packet is sent. If 0, only tx_coalesce_usecs is * used. It is illegal to set both usecs and max frames * to zero as this would cause TX interrupts to never be * generated. */ __u32 tx_max_coalesced_frames; /* Same as above two parameters, except that these values * apply while an IRQ is being serviced by the host. Not * all cards support this feature and the values are ignored * in that case. */ __u32 tx_coalesce_usecs_irq; __u32 tx_max_coalesced_frames_irq; /* How many usecs to delay in-memory statistics * block updates. Some drivers do not have an in-memory * statistic block, and in such cases this value is ignored. * This value must not be zero. */ __u32 stats_block_coalesce_usecs; /* Adaptive RX/TX coalescing is an algorithm implemented by * some drivers to improve latency under low packet rates and * improve throughput under high packet rates. Some drivers * only implement one of RX or TX adaptive coalescing. Anything * not implemented by the driver causes these values to be * silently ignored. */ __u32 use_adaptive_rx_coalesce; __u32 use_adaptive_tx_coalesce; /* When the packet rate (measured in packets per second) * is below pkt_rate_low, the {rx,tx}_*_low parameters are * used. */ __u32 pkt_rate_low; __u32 rx_coalesce_usecs_low; __u32 rx_max_coalesced_frames_low; __u32 tx_coalesce_usecs_low; __u32 tx_max_coalesced_frames_low; /* When the packet rate is below pkt_rate_high but above * pkt_rate_low (both measured in packets per second) the * normal {rx,tx}_* coalescing parameters are used. */ /* When the packet rate is (measured in packets per second) * is above pkt_rate_high, the {rx,tx}_*_high parameters are * used. */ __u32 pkt_rate_high; __u32 rx_coalesce_usecs_high; __u32 rx_max_coalesced_frames_high; __u32 tx_coalesce_usecs_high; __u32 tx_max_coalesced_frames_high; /* How often to do adaptive coalescing packet rate sampling, * measured in seconds. Must not be zero. */ __u32 rate_sample_interval; }; /* for configuring RX/TX ring parameters */ struct ethtool_ringparam { __u32 cmd; /* ETHTOOL_{G,S}RINGPARAM */ /* Read only attributes. These indicate the maximum number * of pending RX/TX ring entries the driver will allow the * user to set. */ __u32 rx_max_pending; __u32 rx_mini_max_pending; __u32 rx_jumbo_max_pending; __u32 tx_max_pending; /* Values changeable by the user. The valid values are * in the range 1 to the "*_max_pending" counterpart above. */ __u32 rx_pending; __u32 rx_mini_pending; __u32 rx_jumbo_pending; __u32 tx_pending; }; /* for configuring link flow control parameters */ struct ethtool_pauseparam { __u32 cmd; /* ETHTOOL_{G,S}PAUSEPARAM */ /* If the link is being auto-negotiated (via ethtool_cmd.autoneg * being true) the user may set 'autonet' here non-zero to have the * pause parameters be auto-negotiated too. In such a case, the * {rx,tx}_pause values below determine what capabilities are * advertised. * * If 'autoneg' is zero or the link is not being auto-negotiated, * then {rx,tx}_pause force the driver to use/not-use pause * flow control. */ __u32 autoneg; __u32 rx_pause; __u32 tx_pause; }; #define ETH_GSTRING_LEN 32 enum ethtool_stringset { ETH_SS_TEST = 0, ETH_SS_STATS, ETH_SS_PRIV_FLAGS, }; /* for passing string sets for data tagging */ struct ethtool_gstrings { __u32 cmd; /* ETHTOOL_GSTRINGS */ __u32 string_set; /* string set id e.c. ETH_SS_TEST, etc*/ __u32 len; /* number of strings in the string set */ __u8 data[0]; }; enum ethtool_test_flags { ETH_TEST_FL_OFFLINE = (1 << 0), /* online / offline */ ETH_TEST_FL_FAILED = (1 << 1), /* test passed / failed */ }; /* for requesting NIC test and getting results*/ struct ethtool_test { __u32 cmd; /* ETHTOOL_TEST */ __u32 flags; /* ETH_TEST_FL_xxx */ __u32 reserved; __u32 len; /* result length, in number of u64 elements */ __u64 data[0]; }; /* for dumping NIC-specific statistics */ struct ethtool_stats { __u32 cmd; /* ETHTOOL_GSTATS */ __u32 n_stats; /* number of u64's being returned */ __u64 data[0]; }; struct ethtool_perm_addr { __u32 cmd; /* ETHTOOL_GPERMADDR */ __u32 size; __u8 data[0]; }; /* boolean flags controlling per-interface behavior characteristics. * When reading, the flag indicates whether or not a certain behavior * is enabled/present. When writing, the flag indicates whether * or not the driver should turn on (set) or off (clear) a behavior. * * Some behaviors may read-only (unconditionally absent or present). * If such is the case, return EINVAL in the set-flags operation if the * flag differs from the read-only value. */ enum ethtool_flags { ETH_FLAG_LRO = (1 << 15), /* LRO is enabled */ }; /* The following structures are for supporting RX network flow * classification configuration. Note, all multibyte fields, e.g., * ip4src, ip4dst, psrc, pdst, spi, etc. are expected to be in network * byte order. */ struct ethtool_tcpip4_spec { __be32 ip4src; __be32 ip4dst; __be16 psrc; __be16 pdst; __u8 tos; }; struct ethtool_ah_espip4_spec { __be32 ip4src; __be32 ip4dst; __be32 spi; __u8 tos; }; struct ethtool_rawip4_spec { __be32 ip4src; __be32 ip4dst; __u8 hdata[64]; }; struct ethtool_ether_spec { __be16 ether_type; __u8 frame_size; __u8 eframe[16]; }; #define ETH_RX_NFC_IP4 1 #define ETH_RX_NFC_IP6 2 struct ethtool_usrip4_spec { __be32 ip4src; __be32 ip4dst; __be32 l4_4_bytes; __u8 tos; __u8 ip_ver; __u8 proto; }; struct ethtool_rx_flow_spec { __u32 flow_type; union { struct ethtool_tcpip4_spec tcp_ip4_spec; struct ethtool_tcpip4_spec udp_ip4_spec; struct ethtool_tcpip4_spec sctp_ip4_spec; struct ethtool_ah_espip4_spec ah_ip4_spec; struct ethtool_ah_espip4_spec esp_ip4_spec; struct ethtool_rawip4_spec raw_ip4_spec; struct ethtool_ether_spec ether_spec; struct ethtool_usrip4_spec usr_ip4_spec; __u8 hdata[64]; } h_u, m_u; /* entry, mask */ __u64 ring_cookie; __u32 location; }; struct ethtool_rxnfc { __u32 cmd; __u32 flow_type; /* The rx flow hash value or the rule DB size */ __u64 data; struct ethtool_rx_flow_spec fs; __u32 rule_cnt; __u32 rule_locs[0]; }; #define ETHTOOL_FLASH_MAX_FILENAME 128 enum ethtool_flash_op_type { ETHTOOL_FLASH_ALL_REGIONS = 0, }; /* for passing firmware flashing related parameters */ struct ethtool_flash { __u32 cmd; __u32 region; char data[ETHTOOL_FLASH_MAX_FILENAME]; }; /* CMDs currently supported */ #define ETHTOOL_GSET 0x00000001 /* Get settings. */ #define ETHTOOL_SSET 0x00000002 /* Set settings. */ #define ETHTOOL_GDRVINFO 0x00000003 /* Get driver info. */ #define ETHTOOL_GREGS 0x00000004 /* Get NIC registers. */ #define ETHTOOL_GWOL 0x00000005 /* Get wake-on-lan options. */ #define ETHTOOL_SWOL 0x00000006 /* Set wake-on-lan options. */ #define ETHTOOL_GMSGLVL 0x00000007 /* Get driver message level */ #define ETHTOOL_SMSGLVL 0x00000008 /* Set driver msg level. */ #define ETHTOOL_NWAY_RST 0x00000009 /* Restart autonegotiation. */ #define ETHTOOL_GLINK 0x0000000a /* Get link status (ethtool_value) */ #define ETHTOOL_GEEPROM 0x0000000b /* Get EEPROM data */ #define ETHTOOL_SEEPROM 0x0000000c /* Set EEPROM data. */ #define ETHTOOL_GCOALESCE 0x0000000e /* Get coalesce config */ #define ETHTOOL_SCOALESCE 0x0000000f /* Set coalesce config. */ #define ETHTOOL_GRINGPARAM 0x00000010 /* Get ring parameters */ #define ETHTOOL_SRINGPARAM 0x00000011 /* Set ring parameters. */ #define ETHTOOL_GPAUSEPARAM 0x00000012 /* Get pause parameters */ #define ETHTOOL_SPAUSEPARAM 0x00000013 /* Set pause parameters. */ #define ETHTOOL_GRXCSUM 0x00000014 /* Get RX hw csum enable (ethtool_value) */ #define ETHTOOL_SRXCSUM 0x00000015 /* Set RX hw csum enable (ethtool_value) */ #define ETHTOOL_GTXCSUM 0x00000016 /* Get TX hw csum enable (ethtool_value) */ #define ETHTOOL_STXCSUM 0x00000017 /* Set TX hw csum enable (ethtool_value) */ #define ETHTOOL_GSG 0x00000018 /* Get scatter-gather enable * (ethtool_value) */ #define ETHTOOL_SSG 0x00000019 /* Set scatter-gather enable * (ethtool_value). */ #define ETHTOOL_TEST 0x0000001a /* execute NIC self-test. */ #define ETHTOOL_GSTRINGS 0x0000001b /* get specified string set */ #define ETHTOOL_PHYS_ID 0x0000001c /* identify the NIC */ #define ETHTOOL_GSTATS 0x0000001d /* get NIC-specific statistics */ #define ETHTOOL_GTSO 0x0000001e /* Get TSO enable (ethtool_value) */ #define ETHTOOL_STSO 0x0000001f /* Set TSO enable (ethtool_value) */ #define ETHTOOL_GPERMADDR 0x00000020 /* Get permanent hardware address */ #define ETHTOOL_GUFO 0x00000021 /* Get UFO enable (ethtool_value) */ #define ETHTOOL_SUFO 0x00000022 /* Set UFO enable (ethtool_value) */ #define ETHTOOL_GGSO 0x00000023 /* Get GSO enable (ethtool_value) */ #define ETHTOOL_SGSO 0x00000024 /* Set GSO enable (ethtool_value) */ #define ETHTOOL_GFLAGS 0x00000025 /* Get flags bitmap(ethtool_value) */ #define ETHTOOL_SFLAGS 0x00000026 /* Set flags bitmap(ethtool_value) */ #define ETHTOOL_GPFLAGS 0x00000027 /* Get driver-private flags bitmap */ #define ETHTOOL_SPFLAGS 0x00000028 /* Set driver-private flags bitmap */ #define ETHTOOL_GRXFH 0x00000029 /* Get RX flow hash configuration */ #define ETHTOOL_SRXFH 0x0000002a /* Set RX flow hash configuration */ #define ETHTOOL_GGRO 0x0000002b /* Get GRO enable (ethtool_value) */ #define ETHTOOL_SGRO 0x0000002c /* Set GRO enable (ethtool_value) */ #define ETHTOOL_GRXRINGS 0x0000002d /* Get RX rings available for LB */ #define ETHTOOL_GRXCLSRLCNT 0x0000002e /* Get RX class rule count */ #define ETHTOOL_GRXCLSRULE 0x0000002f /* Get RX classification rule */ #define ETHTOOL_GRXCLSRLALL 0x00000030 /* Get all RX classification rule */ #define ETHTOOL_SRXCLSRLDEL 0x00000031 /* Delete RX classification rule */ #define ETHTOOL_SRXCLSRLINS 0x00000032 /* Insert RX classification rule */ #define ETHTOOL_FLASHDEV 0x00000033 /* Flash firmware to device */ #define ETHTOOL_RESET 0x00000034 /* Reset hardware */ /* compatibility with older code */ #define SPARC_ETH_GSET ETHTOOL_GSET #define SPARC_ETH_SSET ETHTOOL_SSET /* Indicates what features are supported by the interface. */ #define SUPPORTED_10baseT_Half (1 << 0) #define SUPPORTED_10baseT_Full (1 << 1) #define SUPPORTED_100baseT_Half (1 << 2) #define SUPPORTED_100baseT_Full (1 << 3) #define SUPPORTED_1000baseT_Half (1 << 4) #define SUPPORTED_1000baseT_Full (1 << 5) #define SUPPORTED_Autoneg (1 << 6) #define SUPPORTED_TP (1 << 7) #define SUPPORTED_AUI (1 << 8) #define SUPPORTED_MII (1 << 9) #define SUPPORTED_FIBRE (1 << 10) #define SUPPORTED_BNC (1 << 11) #define SUPPORTED_10000baseT_Full (1 << 12) #define SUPPORTED_Pause (1 << 13) #define SUPPORTED_Asym_Pause (1 << 14) #define SUPPORTED_2500baseX_Full (1 << 15) #define SUPPORTED_Backplane (1 << 16) #define SUPPORTED_1000baseKX_Full (1 << 17) #define SUPPORTED_10000baseKX4_Full (1 << 18) #define SUPPORTED_10000baseKR_Full (1 << 19) #define SUPPORTED_10000baseR_FEC (1 << 20) /* Indicates what features are advertised by the interface. */ #define ADVERTISED_10baseT_Half (1 << 0) #define ADVERTISED_10baseT_Full (1 << 1) #define ADVERTISED_100baseT_Half (1 << 2) #define ADVERTISED_100baseT_Full (1 << 3) #define ADVERTISED_1000baseT_Half (1 << 4) #define ADVERTISED_1000baseT_Full (1 << 5) #define ADVERTISED_Autoneg (1 << 6) #define ADVERTISED_TP (1 << 7) #define ADVERTISED_AUI (1 << 8) #define ADVERTISED_MII (1 << 9) #define ADVERTISED_FIBRE (1 << 10) #define ADVERTISED_BNC (1 << 11) #define ADVERTISED_10000baseT_Full (1 << 12) #define ADVERTISED_Pause (1 << 13) #define ADVERTISED_Asym_Pause (1 << 14) #define ADVERTISED_2500baseX_Full (1 << 15) #define ADVERTISED_Backplane (1 << 16) #define ADVERTISED_1000baseKX_Full (1 << 17) #define ADVERTISED_10000baseKX4_Full (1 << 18) #define ADVERTISED_10000baseKR_Full (1 << 19) #define ADVERTISED_10000baseR_FEC (1 << 20) /* The following are all involved in forcing a particular link * mode for the device for setting things. When getting the * devices settings, these indicate the current mode and whether * it was foced up into this mode or autonegotiated. */ /* The forced speed, 10Mb, 100Mb, gigabit, 2.5Gb, 10GbE. */ #define SPEED_10 10 #define SPEED_100 100 #define SPEED_1000 1000 #define SPEED_2500 2500 #define SPEED_10000 10000 /* Duplex, half or full. */ #define DUPLEX_HALF 0x00 #define DUPLEX_FULL 0x01 /* Which connector port. */ #define PORT_TP 0x00 #define PORT_AUI 0x01 #define PORT_MII 0x02 #define PORT_FIBRE 0x03 #define PORT_BNC 0x04 #define PORT_DA 0x05 #define PORT_NONE 0xef #define PORT_OTHER 0xff /* Which transceiver to use. */ #define XCVR_INTERNAL 0x00 #define XCVR_EXTERNAL 0x01 #define XCVR_DUMMY1 0x02 #define XCVR_DUMMY2 0x03 #define XCVR_DUMMY3 0x04 /* Enable or disable autonegotiation. If this is set to enable, * the forced link modes above are completely ignored. */ #define AUTONEG_DISABLE 0x00 #define AUTONEG_ENABLE 0x01 /* Mode MDI or MDI-X */ #define ETH_TP_MDI_INVALID 0x00 #define ETH_TP_MDI 0x01 #define ETH_TP_MDI_X 0x02 /* Wake-On-Lan options. */ #define WAKE_PHY (1 << 0) #define WAKE_UCAST (1 << 1) #define WAKE_MCAST (1 << 2) #define WAKE_BCAST (1 << 3) #define WAKE_ARP (1 << 4) #define WAKE_MAGIC (1 << 5) #define WAKE_MAGICSECURE (1 << 6) /* only meaningful if WAKE_MAGIC */ /* L3-L4 network traffic flow types */ #define TCP_V4_FLOW 0x01 #define UDP_V4_FLOW 0x02 #define SCTP_V4_FLOW 0x03 #define AH_ESP_V4_FLOW 0x04 #define TCP_V6_FLOW 0x05 #define UDP_V6_FLOW 0x06 #define SCTP_V6_FLOW 0x07 #define AH_ESP_V6_FLOW 0x08 #define AH_V4_FLOW 0x09 #define ESP_V4_FLOW 0x0a #define AH_V6_FLOW 0x0b #define ESP_V6_FLOW 0x0c #define IP_USER_FLOW 0x0d #define IPV4_FLOW 0x10 #define IPV6_FLOW 0x11 /* L3-L4 network traffic flow hash options */ #define RXH_L2DA (1 << 1) #define RXH_VLAN (1 << 2) #define RXH_L3_PROTO (1 << 3) #define RXH_IP_SRC (1 << 4) #define RXH_IP_DST (1 << 5) #define RXH_L4_B_0_1 (1 << 6) /* src port in case of TCP/UDP/SCTP */ #define RXH_L4_B_2_3 (1 << 7) /* dst port in case of TCP/UDP/SCTP */ #define RXH_DISCARD (1 << 31) #define RX_CLS_FLOW_DISC 0xffffffffffffffffULL /* Reset flags */ /* The reset() operation must clear the flags for the components which * were actually reset. On successful return, the flags indicate the * components which were not reset, either because they do not exist * in the hardware or because they cannot be reset independently. The * driver must never reset any components that were not requested. */ enum ethtool_reset_flags { /* These flags represent components dedicated to the interface * the command is addressed to. Shift any flag left by * ETH_RESET_SHARED_SHIFT to reset a shared component of the * same type. */ ETH_RESET_MGMT = 1 << 0, /* Management processor */ ETH_RESET_IRQ = 1 << 1, /* Interrupt requester */ ETH_RESET_DMA = 1 << 2, /* DMA engine */ ETH_RESET_FILTER = 1 << 3, /* Filtering/flow direction */ ETH_RESET_OFFLOAD = 1 << 4, /* Protocol offload */ ETH_RESET_MAC = 1 << 5, /* Media access controller */ ETH_RESET_PHY = 1 << 6, /* Transceiver/PHY */ ETH_RESET_RAM = 1 << 7, /* RAM shared between * multiple components */ ETH_RESET_DEDICATED = 0x0000ffff, /* All components dedicated to * this interface */ ETH_RESET_ALL = 0xffffffff, /* All components used by this * interface, even if shared */ }; #define ETH_RESET_SHARED_SHIFT 16 #endif /* _LINUX_ETHTOOL_H */ open-iscsi-2.0.873/usr/event_poll.c000066400000000000000000000076561175631155400171160ustar00rootroot00000000000000/* * iSCSI daemon event handler * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * Originally based on: * (C) 2004 FUJITA Tomonori * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include "mgmt_ipc.h" #include "iscsi_ipc.h" #include "sysfs.h" #include "iscsid.h" #include "log.h" #include "iscsi_ipc.h" #include "actor.h" #include "initiator.h" #include "iscsi_err.h" static int reap_count; void reap_inc(void) { reap_count++; } void reap_proc(void) { int rc, i, max_reaps; /* * We don't really need reap_count, but calling wait() all the * time seems execessive. */ max_reaps = reap_count; for (i = 0; i < max_reaps; i++) { rc = waitpid(0, NULL, WNOHANG); if (rc > 0) { reap_count--; log_debug(6, "reaped pid %d, reap_count now %d", rc, reap_count); } } } static LIST_HEAD(shutdown_callbacks); struct shutdown_callback { struct list_head list; pid_t pid; }; int shutdown_callback(pid_t pid) { struct shutdown_callback *cb; cb = calloc(1, sizeof(*cb)); if (!cb) return ENOMEM; INIT_LIST_HEAD(&cb->list); cb->pid = pid; log_debug(1, "adding %d for shutdown cb\n", pid); list_add_tail(&cb->list, &shutdown_callbacks); return 0; } static void shutdown_notify_pids(void) { struct shutdown_callback *cb; list_for_each_entry(cb, &shutdown_callbacks, list) { log_debug(1, "Killing %d\n", cb->pid); kill(cb->pid, SIGTERM); } } static int shutdown_wait_pids(void) { struct shutdown_callback *cb, *tmp; list_for_each_entry_safe(cb, tmp, &shutdown_callbacks, list) { /* * the proc reaper could clean it up, so wait for any * sign that it is gone. */ if (waitpid(cb->pid, NULL, WNOHANG)) { log_debug(1, "%d done\n", cb->pid); list_del(&cb->list); free(cb); } } return list_empty(&shutdown_callbacks); } #define POLL_CTRL 0 #define POLL_IPC 1 #define POLL_MAX 2 static int event_loop_stop; static queue_task_t *shutdown_qtask; void event_loop_exit(queue_task_t *qtask) { shutdown_qtask = qtask; event_loop_stop = 1; } void event_loop(struct iscsi_ipc *ipc, int control_fd, int mgmt_ipc_fd) { struct pollfd poll_array[POLL_MAX]; int res, has_shutdown_children = 0; poll_array[POLL_CTRL].fd = control_fd; poll_array[POLL_CTRL].events = POLLIN; poll_array[POLL_IPC].fd = mgmt_ipc_fd; poll_array[POLL_IPC].events = POLLIN; event_loop_stop = 0; while (1) { if (event_loop_stop) { if (!has_shutdown_children) { has_shutdown_children = 1; shutdown_notify_pids(); } if (shutdown_wait_pids()) break; } res = poll(poll_array, POLL_MAX, ACTOR_RESOLUTION); if (res > 0) { log_debug(6, "poll result %d", res); if (poll_array[POLL_CTRL].revents) ipc->ctldev_handle(); if (poll_array[POLL_IPC].revents) mgmt_ipc_handle(mgmt_ipc_fd); } else if (res < 0) { if (errno == EINTR) { log_debug(1, "event_loop interrupted"); } else { log_error("got poll() error (%d), errno (%d), " "exiting", res, errno); break; } } else actor_poll(); reap_proc(); /* * flush sysfs cache since kernel objs may * have changed as a result of handling op */ sysfs_cleanup(); } if (shutdown_qtask) mgmt_ipc_write_rsp(shutdown_qtask, ISCSI_SUCCESS); } open-iscsi-2.0.873/usr/event_poll.h000066400000000000000000000017461175631155400171150ustar00rootroot00000000000000/* * iSCSI event poll/loop * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef EVENT_POLL_H #define EVENT_POLL_H struct iscsi_ipc; struct queue_task; int shutdown_callback(pid_t pid); void reap_proc(void); void reap_inc(void); void event_loop(struct iscsi_ipc *ipc, int control_fd, int mgmt_ipc_fd); void event_loop_exit(struct queue_task *qtask); #endif open-iscsi-2.0.873/usr/host.c000066400000000000000000000202401175631155400157040ustar00rootroot00000000000000/* * iSCSI host helpers * * Copyright (C) 2008 Mike Christie * Copyright (C) 2008 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include "list.h" #include "iscsi_util.h" #include "log.h" #include "iscsi_sysfs.h" #include "version.h" #include "iscsi_settings.h" #include "mgmt_ipc.h" #include "host.h" #include "session_info.h" #include "transport.h" #include "initiator.h" #include "iface.h" #include "iscsi_err.h" static int match_host_to_session(void *data, struct session_info *info) { uint32_t host_no = *(uint32_t *) data; uint32_t info_host_no; int rc; info_host_no = iscsi_sysfs_get_host_no_from_sid(info->sid, &rc); if (rc) { log_error("could not get host_no for session%d err %d.", info->sid, rc); return 0; } return host_no == info_host_no; } static void print_host_info(struct iface_rec *iface, char *prefix) { if (strlen(iface->transport_name)) printf("%sTransport: %s\n", prefix, iface->transport_name); else printf("%sTransport: %s\n", prefix, UNKNOWN_VALUE); if (strlen(iface->iname)) printf("%sInitiatorname: %s\n", prefix, iface->iname); else printf("%sInitiatorname: %s\n", prefix, UNKNOWN_VALUE); if (!strlen(iface->ipaddress)) printf("%sIPaddress: %s\n", prefix, UNKNOWN_VALUE); else if (strchr(iface->ipaddress, '.')) printf("%sIPaddress: %s\n", prefix, iface->ipaddress); else printf("%sIPaddress: [%s]\n", prefix, iface->ipaddress); if (strlen(iface->hwaddress)) printf("%sHWaddress: %s\n", prefix, iface->hwaddress); else printf("%sHWaddress: %s\n", prefix, UNKNOWN_VALUE); if (strlen(iface->netdev)) printf("%sNetdev: %s\n", prefix, iface->netdev); else printf("%sNetdev: %s\n", prefix, UNKNOWN_VALUE); } static int host_info_print_flat(void *data, struct host_info *hinfo) { struct iface_rec *iface = &hinfo->iface; if (strlen(iface->transport_name)) printf("%s: ", iface->transport_name); else printf("%s: ", UNKNOWN_VALUE); printf("[%u] ", hinfo->host_no); if (!strlen(iface->ipaddress)) printf("%s,", UNKNOWN_VALUE); else if (strchr(iface->ipaddress, '.')) printf("%s,", iface->ipaddress); else printf("[%s],", iface->ipaddress); if (strlen(iface->hwaddress)) printf("[%s],", iface->hwaddress); else printf("[%s],", UNKNOWN_VALUE); if (strlen(iface->netdev)) printf("%s ", iface->netdev); else printf("%s ", UNKNOWN_VALUE); if (strlen(iface->iname)) printf("%s\n", iface->iname); else printf("%s\n", UNKNOWN_VALUE); return 0; } static int print_host_iface(void *data, struct iface_rec *iface) { char *prefix = data; printf("%s**********\n", prefix); printf("%sInterface:\n", prefix); printf("%s**********\n", prefix); printf("%sKernel Name: %s\n", prefix, iface->name); if (!strlen(iface->ipaddress)) printf("%sIPaddress: %s\n", prefix, UNKNOWN_VALUE); else if (strchr(iface->ipaddress, '.')) { printf("%sIPaddress: %s\n", prefix, iface->ipaddress); if (!strlen(iface->gateway)) printf("%sGateway: %s\n", prefix, UNKNOWN_VALUE); else printf("%sGateway: %s\n", prefix, iface->gateway); if (!strlen(iface->subnet_mask)) printf("%sSubnet: %s\n", prefix, UNKNOWN_VALUE); else printf("%sSubnet: %s\n", prefix, iface->subnet_mask); if (!strlen(iface->bootproto)) printf("%sBootProto: %s\n", prefix, UNKNOWN_VALUE); else printf("%sBootProto: %s\n", prefix, iface->bootproto); } else { printf("%sIPaddress: [%s]\n", prefix, iface->ipaddress); if (!strlen(iface->ipv6_autocfg)) printf("%sIPaddress Autocfg: %s\n", prefix, UNKNOWN_VALUE); else printf("%sIPaddress Autocfg: %s\n", prefix, iface->ipv6_autocfg); if (!strlen(iface->ipv6_linklocal)) printf("%sLink Local Address: %s\n", prefix, UNKNOWN_VALUE); else printf("%sLink Local Address: [%s]\n", prefix, iface->ipv6_linklocal); if (!strlen(iface->linklocal_autocfg)) printf("%sLink Local Autocfg: %s\n", prefix, UNKNOWN_VALUE); else printf("%sLink Local Autocfg: %s\n", prefix, iface->linklocal_autocfg); if (!strlen(iface->ipv6_router)) printf("%sRouter Address: %s\n", prefix, UNKNOWN_VALUE); else printf("%sRouter Address: [%s]\n", prefix, iface->ipv6_router); } if (!strlen(iface->port_state)) printf("%sPort State: %s\n", prefix, UNKNOWN_VALUE); else printf("%sPort State: %s\n", prefix, iface->port_state); if (!strlen(iface->port_speed)) printf("%sPort Speed: %s\n", prefix, UNKNOWN_VALUE); else printf("%sPort Speed: %s\n", prefix, iface->port_speed); if (!iface->port) printf("%sPort: %s\n", prefix, UNKNOWN_VALUE); else printf("%sPort: %u\n", prefix, iface->port); if (!iface->mtu) printf("%sMTU: %s\n", prefix, UNKNOWN_VALUE); else printf("%sMTU: %u\n", prefix, iface->mtu); if (iface->vlan_id == UINT16_MAX) printf("%sVLAN ID: %s\n", prefix, UNKNOWN_VALUE); else printf("%sVLAN ID: %u\n", prefix, iface->vlan_id); if (iface->vlan_priority == UINT8_MAX) printf("%sVLAN priority: %s\n", prefix, UNKNOWN_VALUE); else printf("%sVLAN priority: %u\n", prefix, iface->vlan_priority); return 0; } static void print_host_ifaces(struct host_info *hinfo, char *prefix) { int nr_found; iscsi_sysfs_for_each_iface_on_host(prefix, hinfo->host_no, &nr_found, print_host_iface); } static int host_info_print_tree(void *data, struct host_info *hinfo) { struct list_head sessions; struct session_link_info link_info; int err, num_found = 0; unsigned int session_info_flags = *(unsigned int *)data; char state[SCSI_MAX_STATE_VALUE]; INIT_LIST_HEAD(&sessions); printf("Host Number: %u\n", hinfo->host_no); if (!iscsi_sysfs_get_host_state(state, hinfo->host_no)) printf("\tState: %s\n", state); else printf("\tState: Unknown\n"); print_host_info(&hinfo->iface, "\t"); print_host_ifaces(hinfo, "\t"); if (!session_info_flags) return 0; link_info.list = &sessions; link_info.match_fn = match_host_to_session; link_info.data = &hinfo->host_no; err = iscsi_sysfs_for_each_session(&link_info, &num_found, session_info_create_list); if (err || !num_found) return 0; printf("\t*********\n"); printf("\tSessions:\n"); printf("\t*********\n"); session_info_print_tree(&sessions, "\t", session_info_flags, 0); session_info_free_list(&sessions); return 0; } int host_info_print(int info_level, uint32_t host_no) { int num_found = 0, err = 0; char *version; unsigned int flags = 0; switch (info_level) { case 0: case -1: err = iscsi_sysfs_for_each_host(NULL, &num_found, host_info_print_flat); break; case 4: version = iscsi_sysfs_get_iscsi_kernel_version(); if (version) { printf("iSCSI Transport Class version %s\n", version); printf("version %s\n", ISCSI_VERSION_STR); } flags |= SESSION_INFO_SCSI_DEVS; /* fall through */ case 3: flags |= SESSION_INFO_ISCSI_PARAMS; /* fall through */ case 2: flags |= SESSION_INFO_ISCSI_STATE | SESSION_INFO_IFACE; /* fall through */ case 1: if (host_no != -1) { struct host_info hinfo; memset(&hinfo, 0, sizeof(struct host_info)); hinfo.host_no = host_no; iscsi_sysfs_get_hostinfo_by_host_no(&hinfo); host_info_print_tree(&flags, &hinfo); num_found = 1; break; } transport_probe_for_offload(); err = iscsi_sysfs_for_each_host(&flags, &num_found, host_info_print_tree); break; default: log_error("Invalid info level %d. Try 0 - 4.", info_level); return ISCSI_ERR_INVAL; } if (err) { log_error("Can not get list of iSCSI hosts: %s", iscsi_err_to_str(err)); return err; } else if (!num_found) { log_error("No iSCSI hosts."); return ISCSI_ERR_NO_OBJS_FOUND; } return 0; } open-iscsi-2.0.873/usr/host.h000066400000000000000000000005471175631155400157210ustar00rootroot00000000000000#ifndef ISCSI_HOST_H #define ISCSI_HOST_H #include #include "types.h" #include "config.h" #define MAX_CHAP_BUF_SZ 4096 #define REQ_CHAP_BUF_SZ (MAX_CHAP_BUF_SZ + sizeof(struct iscsi_uevent)) struct host_info { struct iface_rec iface; uint32_t host_no; }; extern int host_info_print(int info_level, uint32_t host_no); #endif open-iscsi-2.0.873/usr/idbm.c000066400000000000000000002066451175631155400156610ustar00rootroot00000000000000/* * iSCSI Discovery Database Library * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include "idbm.h" #include "idbm_fields.h" #include "log.h" #include "iscsi_util.h" #include "iscsi_settings.h" #include "transport.h" #include "iscsi_sysfs.h" #include "iface.h" #include "sysdeps.h" #include "fw_context.h" #include "iscsi_err.h" #define IDBM_HIDE 0 /* Hide parameter when print. */ #define IDBM_SHOW 1 /* Show parameter when print. */ #define IDBM_MASKED 2 /* Show "stars" instead of real value when print */ static struct idbm *db; #define __recinfo_str(_key, _info, _rec, _name, _show, _n, _mod) do { \ _info[_n].type = TYPE_STR; \ strlcpy(_info[_n].name, _key, NAME_MAXVAL); \ if (strlen((char*)_rec->_name)) \ strlcpy((char*)_info[_n].value, (char*)_rec->_name, \ VALUE_MAXVAL); \ _info[_n].data = &_rec->_name; \ _info[_n].data_len = sizeof(_rec->_name); \ _info[_n].visible = _show; \ _info[_n].can_modify = _mod; \ _n++; \ } while(0) #define __recinfo_int(_key, _info, _rec, _name, _show, _n, _mod) do { \ _info[_n].type = TYPE_INT; \ strlcpy(_info[_n].name, _key, NAME_MAXVAL); \ snprintf(_info[_n].value, VALUE_MAXVAL, "%d", _rec->_name); \ _info[_n].data = &_rec->_name; \ _info[_n].data_len = sizeof(_rec->_name); \ _info[_n].visible = _show; \ _info[_n].can_modify = _mod; \ _n++; \ } while(0) #define __recinfo_uint8(_key, _info, _rec, _name, _show, _n, _mod) do { \ _info[_n].type = TYPE_UINT8; \ strlcpy(_info[_n].name, _key, NAME_MAXVAL); \ snprintf(_info[_n].value, VALUE_MAXVAL, "%d", _rec->_name); \ _info[_n].data = &_rec->_name; \ _info[_n].data_len = sizeof(_rec->_name); \ _info[_n].visible = _show; \ _info[_n].can_modify = _mod; \ _n++; \ } while (0) #define __recinfo_uint16(_key, _info, _rec, _name, _show, _n, _mod) do { \ _info[_n].type = TYPE_UINT16; \ strlcpy(_info[_n].name, _key, NAME_MAXVAL); \ snprintf(_info[_n].value, VALUE_MAXVAL, "%d", _rec->_name); \ _info[_n].data = &_rec->_name; \ _info[_n].data_len = sizeof(_rec->_name); \ _info[_n].visible = _show; \ _info[_n].can_modify = _mod; \ _n++; \ } while (0) #define __recinfo_int_o2(_key,_info,_rec,_name,_show,_op0,_op1,_n, _mod) do { \ _info[_n].type = TYPE_INT_O; \ strlcpy(_info[_n].name, _key, NAME_MAXVAL); \ if (_rec->_name == 0) strlcpy(_info[_n].value, _op0, VALUE_MAXVAL); \ if (_rec->_name == 1) strlcpy(_info[_n].value, _op1, VALUE_MAXVAL); \ _info[_n].data = &_rec->_name; \ _info[_n].data_len = sizeof(_rec->_name); \ _info[_n].visible = _show; \ _info[_n].opts[0] = _op0; \ _info[_n].opts[1] = _op1; \ _info[_n].numopts = 2; \ _info[_n].can_modify = _mod; \ _n++; \ } while(0) #define __recinfo_int_o3(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_n, \ _mod) do { \ __recinfo_int_o2(_key,_info,_rec,_name,_show,_op0,_op1,_n, _mod); \ _n--; \ if (_rec->_name == 2) strlcpy(_info[_n].value, _op2, VALUE_MAXVAL);\ _info[_n].opts[2] = _op2; \ _info[_n].numopts = 3; \ _n++; \ } while(0) #define __recinfo_int_o4(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_op3,_n, \ _mod) do { \ __recinfo_int_o3(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_n, _mod); \ _n--; \ if (_rec->_name == 3) strlcpy(_info[_n].value, _op3, VALUE_MAXVAL); \ _info[_n].opts[3] = _op3; \ _info[_n].numopts = 4; \ _n++; \ } while(0) #define __recinfo_int_o5(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_op3, \ _op4,_n, _mod) do { \ __recinfo_int_o4(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_op3, \ _n,_mod); \ _n--; \ if (_rec->_name == 4) strlcpy(_info[_n].value, _op4, VALUE_MAXVAL); \ _info[_n].opts[4] = _op4; \ _info[_n].numopts = 5; \ _n++; \ } while(0) #define __recinfo_int_o6(_key,_info,_rec,_name,_show,_op0,_op1,_op2, \ _op3,_op4,_op5,_n,_mod) do { \ __recinfo_int_o5(_key,_info,_rec,_name,_show,_op0,_op1,_op2,_op3, \ _op4,_n,_mod); \ _n--; \ if (_rec->_name == 5) strlcpy(_info[_n].value, _op5, VALUE_MAXVAL); \ _info[_n].opts[5] = _op5; \ _info[_n].numopts = 6; \ _n++; \ } while(0) static void idbm_recinfo_discovery(discovery_rec_t *r, recinfo_t *ri) { int num = 0; __recinfo_int_o2(DISC_STARTUP, ri, r, startup, IDBM_SHOW, "manual", "automatic", num, 1); __recinfo_int_o6(DISC_TYPE, ri, r, type, IDBM_SHOW, "sendtargets", "isns", "offload_send_targets", "slp", "static", "fw", num, 0); switch (r->type) { case DISCOVERY_TYPE_SENDTARGETS: __recinfo_str(DISC_ST_ADDR, ri, r, address, IDBM_SHOW, num, 0); __recinfo_int(DISC_ST_PORT, ri, r, port, IDBM_SHOW, num, 0); __recinfo_int_o2(DISC_ST_AUTH_METHOD, ri, r, u.sendtargets.auth.authmethod, IDBM_SHOW, "None", "CHAP", num, 1); __recinfo_str(DISC_ST_USERNAME, ri, r, u.sendtargets.auth.username, IDBM_SHOW, num, 1); __recinfo_str(DISC_ST_PASSWORD, ri, r, u.sendtargets.auth.password, IDBM_MASKED, num, 1); __recinfo_int(DISC_ST_PASSWORD_LEN, ri, r, u.sendtargets.auth.password_length, IDBM_HIDE, num, 1); __recinfo_str(DISC_ST_USERNAME_IN, ri, r, u.sendtargets.auth.username_in, IDBM_SHOW, num, 1); __recinfo_str(DISC_ST_PASSWORD_IN, ri, r, u.sendtargets.auth.password_in, IDBM_MASKED, num, 1); __recinfo_int(DISC_ST_PASSWORD_IN_LEN, ri, r, u.sendtargets.auth.password_in_length, IDBM_HIDE, num, 1); __recinfo_int(DISC_ST_LOGIN_TMO, ri, r, u.sendtargets.conn_timeo.login_timeout, IDBM_SHOW, num, 1); __recinfo_int_o2(DISC_ST_USE_DISC_DAEMON, ri, r, u.sendtargets.use_discoveryd, IDBM_SHOW, "No", "Yes", num, 1); __recinfo_int(DISC_ST_DISC_DAEMON_POLL_INVAL, ri, r, u.sendtargets.discoveryd_poll_inval, IDBM_SHOW, num, 1); __recinfo_int(DISC_ST_REOPEN_MAX, ri, r, u.sendtargets.reopen_max, IDBM_SHOW, num, 1); __recinfo_int(DISC_ST_AUTH_TMO, ri, r, u.sendtargets.conn_timeo.auth_timeout, IDBM_SHOW, num, 1); __recinfo_int(DISC_ST_ACTIVE_TMO, ri, r, u.sendtargets.conn_timeo.active_timeout, IDBM_SHOW, num, 1); __recinfo_int(DISC_ST_MAX_RECV_DLEN, ri, r, u.sendtargets.conn_conf.MaxRecvDataSegmentLength, IDBM_SHOW, num, 1); break; case DISCOVERY_TYPE_ISNS: __recinfo_str(DISC_ISNS_ADDR, ri, r, address, IDBM_SHOW, num, 0); __recinfo_int(DISC_ISNS_PORT, ri, r, port, IDBM_SHOW, num, 0); __recinfo_int_o2(DISC_ISNS_USE_DISC_DAEMON, ri, r, u.isns.use_discoveryd, IDBM_SHOW, "No", "Yes", num, 1); __recinfo_int(DISC_ISNS_DISC_DAEMON_POLL_INVAL, ri, r, u.isns.discoveryd_poll_inval, IDBM_SHOW, num, 1); break; default: break; } } void idbm_recinfo_node(node_rec_t *r, recinfo_t *ri) { int num = 0, i; __recinfo_str(NODE_NAME, ri, r, name, IDBM_SHOW, num, 0); __recinfo_int(NODE_TPGT, ri, r, tpgt, IDBM_SHOW, num, 0); __recinfo_int_o3(NODE_STARTUP, ri, r, startup, IDBM_SHOW, "manual", "automatic", "onboot", num, 1); __recinfo_int_o2(NODE_LEADING_LOGIN, ri, r, leading_login, IDBM_SHOW, "No", "Yes", num, 1); /* * Note: because we do not add the iface.iscsi_ifacename to * sysfs iscsiadm does some weird matching. We can change the iface * values if a session is not running, but node record ifaces values * have to be changed and so do the iface record ones. * * Users should nornmally not want to change the iface ones * in the node record directly and instead do it through * the iface mode which will do the right thing (althought that * needs some locking). */ __recinfo_str(IFACE_HWADDR, ri, r, iface.hwaddress, IDBM_SHOW, num, 1); __recinfo_str(IFACE_IPADDR, ri, r, iface.ipaddress, IDBM_SHOW, num, 1); __recinfo_str(IFACE_ISCSINAME, ri, r, iface.name, IDBM_SHOW, num, 1); __recinfo_str(IFACE_NETNAME, ri, r, iface.netdev, IDBM_SHOW, num, 1); /* * svn 780 compat: older versions used node.transport_name and * rec->transport_name */ __recinfo_str(IFACE_TRANSPORTNAME, ri, r, iface.transport_name, IDBM_SHOW, num, 1); __recinfo_str(IFACE_INAME, ri, r, iface.iname, IDBM_SHOW, num, 1); __recinfo_str(IFACE_BOOT_PROTO, ri, r, iface.bootproto, IDBM_SHOW, num, 1); __recinfo_str(IFACE_SUBNET_MASK, ri, r, iface.subnet_mask, IDBM_SHOW, num, 1); __recinfo_str(IFACE_GATEWAY, ri, r, iface.gateway, IDBM_SHOW, num, 1); __recinfo_str(IFACE_IPV6_AUTOCFG, ri, r, iface.ipv6_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_LINKLOCAL_AUTOCFG, ri, r, iface.linklocal_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_ROUTER_AUTOCFG, ri, r, iface.router_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_LINKLOCAL, ri, r, iface.ipv6_linklocal, IDBM_SHOW, num, 1); __recinfo_str(IFACE_ROUTER, ri, r, iface.ipv6_router, IDBM_SHOW, num, 1); __recinfo_str(IFACE_STATE, ri, r, iface.state, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_VLAN_ID, ri, r, iface.vlan_id, IDBM_SHOW, num, 1); __recinfo_uint8(IFACE_VLAN_PRIORITY, ri, r, iface.vlan_priority, IDBM_SHOW, num, 1); __recinfo_str(IFACE_VLAN_STATE, ri, r, iface.vlan_state, IDBM_SHOW, num, 1); __recinfo_int(IFACE_NUM, ri, r, iface.iface_num, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_MTU, ri, r, iface.mtu, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_PORT, ri, r, iface.port, IDBM_SHOW, num, 1); __recinfo_str(NODE_DISC_ADDR, ri, r, disc_address, IDBM_SHOW, num, 0); __recinfo_int(NODE_DISC_PORT, ri, r, disc_port, IDBM_SHOW, num, 0); __recinfo_int_o6(NODE_DISC_TYPE, ri, r, disc_type, IDBM_SHOW, "send_targets", "isns", "offload_send_targets", "slp", "static", "fw", num, 0); __recinfo_int(SESSION_INIT_CMDSN, ri, r, session.initial_cmdsn, IDBM_SHOW, num, 1); __recinfo_int(SESSION_INIT_LOGIN_RETRY, ri, r, session.initial_login_retry_max, IDBM_SHOW, num, 1); __recinfo_int(SESSION_XMIT_THREAD_PRIORITY, ri, r, session.xmit_thread_priority, IDBM_SHOW, num, 1); __recinfo_int(SESSION_CMDS_MAX, ri, r, session.cmds_max, IDBM_SHOW, num, 1); __recinfo_int(SESSION_QDEPTH, ri, r, session.queue_depth, IDBM_SHOW, num, 1); __recinfo_int(SESSION_NR_SESSIONS, ri, r, session.nr_sessions, IDBM_SHOW, num, 1); __recinfo_int_o2(SESSION_AUTH_METHOD, ri, r, session.auth.authmethod, IDBM_SHOW, "None", "CHAP", num, 1); __recinfo_str(SESSION_USERNAME, ri, r, session.auth.username, IDBM_SHOW, num, 1); __recinfo_str(SESSION_PASSWORD, ri, r, session.auth.password, IDBM_MASKED, num, 1); __recinfo_int(SESSION_PASSWORD_LEN, ri, r, session.auth.password_length, IDBM_HIDE, num, 1); __recinfo_str(SESSION_USERNAME_IN, ri, r, session.auth.username_in, IDBM_SHOW, num, 1); __recinfo_str(SESSION_PASSWORD_IN, ri, r, session.auth.password_in, IDBM_MASKED, num, 1); __recinfo_int(SESSION_PASSWORD_IN_LEN, ri, r, session.auth.password_in_length, IDBM_HIDE, num, 1); __recinfo_int(SESSION_REPLACEMENT_TMO, ri, r, session.timeo.replacement_timeout, IDBM_SHOW, num, 1); __recinfo_int(SESSION_ABORT_TMO, ri, r, session.err_timeo.abort_timeout, IDBM_SHOW, num, 1); __recinfo_int(SESSION_LU_RESET_TMO, ri, r, session.err_timeo.lu_reset_timeout, IDBM_SHOW, num, 1); __recinfo_int(SESSION_TGT_RESET_TMO, ri, r, session.err_timeo.tgt_reset_timeout, IDBM_SHOW, num, 1); __recinfo_int(SESSION_HOST_RESET_TMO, ri, r, session.err_timeo.host_reset_timeout, IDBM_SHOW, num, 1); __recinfo_int_o2(SESSION_FAST_ABORT, ri, r, session.iscsi.FastAbort, IDBM_SHOW, "No", "Yes", num, 1); __recinfo_int_o2(SESSION_INITIAL_R2T, ri, r, session.iscsi.InitialR2T, IDBM_SHOW, "No", "Yes", num, 1); __recinfo_int_o2(SESSION_IMM_DATA, ri, r, session.iscsi.ImmediateData, IDBM_SHOW, "No", "Yes", num, 1); __recinfo_int(SESSION_FIRST_BURST, ri, r, session.iscsi.FirstBurstLength, IDBM_SHOW, num, 1); __recinfo_int(SESSION_MAX_BURST, ri, r, session.iscsi.MaxBurstLength, IDBM_SHOW, num, 1); __recinfo_int(SESSION_DEF_TIME2RETAIN, ri, r, session.iscsi.DefaultTime2Retain, IDBM_SHOW, num, 1); __recinfo_int(SESSION_DEF_TIME2WAIT, ri, r, session.iscsi.DefaultTime2Wait, IDBM_SHOW, num, 1); __recinfo_int(SESSION_MAX_CONNS, ri, r, session.iscsi.MaxConnections, IDBM_SHOW, num, 1); __recinfo_int(SESSION_MAX_R2T, ri, r, session.iscsi.MaxOutstandingR2T, IDBM_SHOW, num, 1); __recinfo_int(SESSION_ERL, ri, r, session.iscsi.ERL, IDBM_SHOW, num, 1); for (i = 0; i < ISCSI_CONN_MAX; i++) { char key[NAME_MAXVAL]; sprintf(key, CONN_ADDR, i); __recinfo_str(key, ri, r, conn[i].address, IDBM_SHOW, num, 0); sprintf(key, CONN_PORT, i); __recinfo_int(key, ri, r, conn[i].port, IDBM_SHOW, num, 0); sprintf(key, CONN_STARTUP, i); __recinfo_int_o3(key, ri, r, conn[i].startup, IDBM_SHOW, "manual", "automatic", "onboot", num, 1); sprintf(key, CONN_WINDOW_SIZE, i); __recinfo_int(key, ri, r, conn[i].tcp.window_size, IDBM_SHOW, num, 1); sprintf(key, CONN_SERVICE_TYPE, i); __recinfo_int(key, ri, r, conn[i].tcp.type_of_service, IDBM_SHOW, num, 1); sprintf(key, CONN_LOGOUT_TMO, i); __recinfo_int(key, ri, r, conn[i].timeo.logout_timeout, IDBM_SHOW, num, 1); sprintf(key, CONN_LOGIN_TMO, i); __recinfo_int(key, ri, r, conn[i].timeo.login_timeout, IDBM_SHOW, num, 1); sprintf(key, CONN_AUTH_TMO, i); __recinfo_int(key, ri, r, conn[i].timeo.auth_timeout, IDBM_SHOW, num, 1); sprintf(key, CONN_NOP_INT, i); __recinfo_int(key, ri, r, conn[i].timeo.noop_out_interval, IDBM_SHOW, num, 1); sprintf(key, CONN_NOP_TMO, i); __recinfo_int(key, ri, r, conn[i].timeo.noop_out_timeout, IDBM_SHOW, num, 1); sprintf(key, CONN_MAX_XMIT_DLEN, i); __recinfo_int(key, ri, r, conn[i].iscsi.MaxXmitDataSegmentLength, IDBM_SHOW, num, 1); sprintf(key, CONN_MAX_RECV_DLEN, i); __recinfo_int(key, ri, r, conn[i].iscsi.MaxRecvDataSegmentLength, IDBM_SHOW, num, 1); sprintf(key, CONN_HDR_DIGEST, i); __recinfo_int_o4(key, ri, r, conn[i].iscsi.HeaderDigest, IDBM_SHOW, "None", "CRC32C", "CRC32C,None", "None,CRC32C", num, 1); sprintf(key, CONN_DATA_DIGEST, i); __recinfo_int_o4(key, ri, r, conn[i].iscsi.DataDigest, IDBM_SHOW, "None", "CRC32C", "CRC32C,None", "None,CRC32C", num, 1); sprintf(key, CONN_IFMARKER, i); __recinfo_int_o2(key, ri, r, conn[i].iscsi.IFMarker, IDBM_SHOW, "No", "Yes", num, 1); sprintf(key, CONN_OFMARKER, i); __recinfo_int_o2(key, ri, r, conn[i].iscsi.OFMarker, IDBM_SHOW, "No", "Yes", num, 1); } } void idbm_recinfo_iface(iface_rec_t *r, recinfo_t *ri) { int num = 0; __recinfo_str(IFACE_ISCSINAME, ri, r, name, IDBM_SHOW, num, 0); __recinfo_str(IFACE_NETNAME, ri, r, netdev, IDBM_SHOW, num, 1); __recinfo_str(IFACE_IPADDR, ri, r, ipaddress, IDBM_SHOW, num, 1); __recinfo_str(IFACE_HWADDR, ri, r, hwaddress, IDBM_SHOW, num, 1); __recinfo_str(IFACE_TRANSPORTNAME, ri, r, transport_name, IDBM_SHOW, num, 1); __recinfo_str(IFACE_INAME, ri, r, iname, IDBM_SHOW, num, 1); __recinfo_str(IFACE_BOOT_PROTO, ri, r, bootproto, IDBM_SHOW, num, 1); __recinfo_str(IFACE_SUBNET_MASK, ri, r, subnet_mask, IDBM_SHOW, num, 1); __recinfo_str(IFACE_GATEWAY, ri, r, gateway, IDBM_SHOW, num, 1); __recinfo_str(IFACE_IPV6_AUTOCFG, ri, r, ipv6_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_LINKLOCAL_AUTOCFG, ri, r, linklocal_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_ROUTER_AUTOCFG, ri, r, router_autocfg, IDBM_SHOW, num, 1); __recinfo_str(IFACE_LINKLOCAL, ri, r, ipv6_linklocal, IDBM_SHOW, num, 1); __recinfo_str(IFACE_ROUTER, ri, r, ipv6_router, IDBM_SHOW, num, 1); __recinfo_str(IFACE_STATE, ri, r, state, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_VLAN_ID, ri, r, vlan_id, IDBM_SHOW, num, 1); __recinfo_uint8(IFACE_VLAN_PRIORITY, ri, r, vlan_priority, IDBM_SHOW, num, 1); __recinfo_str(IFACE_VLAN_STATE, ri, r, vlan_state, IDBM_SHOW, num, 1); __recinfo_int(IFACE_NUM, ri, r, iface_num, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_MTU, ri, r, mtu, IDBM_SHOW, num, 1); __recinfo_uint16(IFACE_PORT, ri, r, port, IDBM_SHOW, num, 1); } static void idbm_recinfo_host_chap(struct iscsi_chap_rec *r, recinfo_t *ri) { int num = 0; __recinfo_uint16(HOST_AUTH_INDEX, ri, r, chap_tbl_idx, IDBM_SHOW, num, 1); if (r->chap_type == CHAP_TYPE_OUT) { __recinfo_str(HOST_AUTH_USERNAME, ri, r, username, IDBM_SHOW, num, 0); __recinfo_str(HOST_AUTH_PASSWORD, ri, r, password, IDBM_MASKED, num, 1); __recinfo_int(HOST_AUTH_PASSWORD_LEN, ri, r, password_length, IDBM_HIDE, num, 1); } else { __recinfo_str(HOST_AUTH_USERNAME_IN, ri, r, username, IDBM_SHOW, num, 0); __recinfo_str(HOST_AUTH_PASSWORD_IN, ri, r, password, IDBM_MASKED, num, 1); __recinfo_int(HOST_AUTH_PASSWORD_IN_LEN, ri, r, password_length, IDBM_HIDE, num, 1); } } recinfo_t *idbm_recinfo_alloc(int max_keys) { recinfo_t *info; info = malloc(sizeof(recinfo_t)*max_keys); if (!info) return NULL; memset(info, 0, sizeof(recinfo_t)*max_keys); return info; } void idbm_print(int type, void *rec, int show, FILE *f) { int i; recinfo_t *info; info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return; switch (type) { case IDBM_PRINT_TYPE_DISCOVERY: idbm_recinfo_discovery((discovery_rec_t*)rec, info); break; case IDBM_PRINT_TYPE_NODE: idbm_recinfo_node((node_rec_t*)rec, info); break; case IDBM_PRINT_TYPE_IFACE: idbm_recinfo_iface((struct iface_rec *)rec, info); break; case IDBM_PRINT_TYPE_HOST_CHAP: idbm_recinfo_host_chap((struct iscsi_chap_rec *)rec, info); break; } fprintf(f, "%s\n", ISCSI_BEGIN_REC); for (i = 0; i < MAX_KEYS; i++) { if (!info[i].visible) continue; if (!show && info[i].visible == IDBM_MASKED) { if (*(char*)info[i].data) { fprintf(f, "%s = ********\n", info[i].name); continue; } /* fall through */ } if (strlen(info[i].value)) fprintf(f, "%s = %s\n", info[i].name, info[i].value); else if (f == stdout) fprintf(f, "%s = \n", info[i].name); } fprintf(f, "%s\n", ISCSI_END_REC); free(info); } static void idbm_setup_session_defaults(struct iscsi_session_operational_config *conf) { conf->InitialR2T = 0; conf->ImmediateData = 1; conf->FirstBurstLength = DEF_INI_FIRST_BURST_LEN; conf->MaxBurstLength = DEF_INI_MAX_BURST_LEN; conf->DefaultTime2Wait = ISCSI_DEF_TIME2WAIT; conf->DefaultTime2Retain = 0; conf->MaxConnections = 1; conf->MaxOutstandingR2T = 1; conf->ERL = 0; conf->FastAbort = 1; } static void idbm_setup_conn_defaults(struct iscsi_conn_operational_config *conf) { conf->MaxXmitDataSegmentLength = 0; conf->MaxRecvDataSegmentLength = DEF_INI_MAX_RECV_SEG_LEN; conf->HeaderDigest = CONFIG_DIGEST_NEVER; conf->DataDigest = CONFIG_DIGEST_NEVER; conf->IFMarker = 0; conf->OFMarker = 0; } static void idbm_discovery_setup_defaults(discovery_rec_t *rec, discovery_type_e type) { memset(rec, 0, sizeof(discovery_rec_t)); rec->startup = ISCSI_STARTUP_MANUAL; rec->type = type; switch (type) { case DISCOVERY_TYPE_SENDTARGETS: rec->u.sendtargets.discoveryd_poll_inval = 30; rec->u.sendtargets.use_discoveryd = 0; rec->u.sendtargets.reopen_max = 5; rec->u.sendtargets.auth.authmethod = 0; rec->u.sendtargets.auth.password_length = 0; rec->u.sendtargets.auth.password_in_length = 0; rec->u.sendtargets.conn_timeo.login_timeout=15; rec->u.sendtargets.conn_timeo.auth_timeout = 45; rec->u.sendtargets.conn_timeo.active_timeout=30; idbm_setup_session_defaults(&rec->u.sendtargets.session_conf); idbm_setup_conn_defaults(&rec->u.sendtargets.conn_conf); /* override def setting */ rec->u.sendtargets.conn_conf.MaxRecvDataSegmentLength = DEF_INI_DISC_MAX_RECV_SEG_LEN; break; case DISCOVERY_TYPE_SLP: rec->u.slp.interfaces = NULL; rec->u.slp.scopes = NULL; rec->u.slp.poll_interval = 5 * 60; /* 5 minutes */ rec->u.slp.auth.authmethod = 0; rec->u.slp.auth.password_length = 0; rec->u.slp.auth.password_in_length = 0; rec->u.slp.auth.password_in_length = 0; break; case DISCOVERY_TYPE_ISNS: rec->u.isns.use_discoveryd = 0; rec->u.isns.discoveryd_poll_inval = -1; break; default: break; } } int idbm_rec_update_param(recinfo_t *info, char *name, char *value, int line_number) { int i; int passwd_done = 0; char passwd_len[8]; setup_passwd_len: for (i=0; i '%s'", name, info[i].value, value); /* parse recinfo by type */ if (info[i].type == TYPE_INT) { if (!info[i].data) continue; *(int*)info[i].data = strtoul(value, NULL, 10); goto updated; } else if (info[i].type == TYPE_UINT8) { if (!info[i].data) continue; *(uint8_t *)info[i].data = strtoul(value, NULL, 10); goto updated; } else if (info[i].type == TYPE_UINT16) { if (!info[i].data) continue; *(uint16_t *)info[i].data = strtoul(value, NULL, 10); goto updated; } else if (info[i].type == TYPE_STR) { if (!info[i].data) continue; strlcpy((char*)info[i].data, value, info[i].data_len); goto updated; } for (j=0; jnrec); idbm_discovery_setup_defaults(&db->drec_st, DISCOVERY_TYPE_SENDTARGETS); idbm_discovery_setup_defaults(&db->drec_slp, DISCOVERY_TYPE_SLP); idbm_discovery_setup_defaults(&db->drec_isns, DISCOVERY_TYPE_ISNS); idbm_recinfo_discovery(&db->drec_st, db->dinfo_st); idbm_recinfo_discovery(&db->drec_slp, db->dinfo_slp); idbm_recinfo_discovery(&db->drec_isns, db->dinfo_isns); idbm_recinfo_node(&db->nrec, db->ninfo); if (!db->get_config_file) { log_debug(1, "Could not get config file. No config file fn\n"); return; } config_file = db->get_config_file(); if (!config_file) { log_debug(1, "Could not get config file for sync config\n"); return; } f = fopen(config_file, "r"); if (!f) { log_debug(1, "cannot open configuration file %s. " "Default location is %s.\n", config_file, CONFIG_FILE); return; } log_debug(5, "updating defaults from '%s'", config_file); idbm_recinfo_config(db->dinfo_st, f); idbm_recinfo_config(db->dinfo_slp, f); idbm_recinfo_config(db->dinfo_isns, f); idbm_recinfo_config(db->ninfo, f); fclose(f); /* update password lengths */ if (*db->drec_st.u.sendtargets.auth.password) db->drec_st.u.sendtargets.auth.password_length = strlen((char*)db->drec_st.u.sendtargets.auth.password); if (*db->drec_st.u.sendtargets.auth.password_in) db->drec_st.u.sendtargets.auth.password_in_length = strlen((char*)db->drec_st.u.sendtargets.auth.password_in); if (*db->drec_slp.u.slp.auth.password) db->drec_slp.u.slp.auth.password_length = strlen((char*)db->drec_slp.u.slp.auth.password); if (*db->drec_slp.u.slp.auth.password_in) db->drec_slp.u.slp.auth.password_in_length = strlen((char*)db->drec_slp.u.slp.auth.password_in); if (*db->nrec.session.auth.password) db->nrec.session.auth.password_length = strlen((char*)db->nrec.session.auth.password); if (*db->nrec.session.auth.password_in) db->nrec.session.auth.password_in_length = strlen((char*)db->nrec.session.auth.password_in); } void idbm_node_setup_from_conf(node_rec_t *rec) { memset(rec, 0, sizeof(*rec)); idbm_node_setup_defaults(rec); idbm_sync_config(); memcpy(rec, &db->nrec, sizeof(*rec)); } int idbm_print_discovery_info(discovery_rec_t *rec, int show) { idbm_print(IDBM_PRINT_TYPE_DISCOVERY, rec, show, stdout); return 1; } int idbm_print_node_info(void *data, node_rec_t *rec) { int show = *((int *)data); idbm_print(IDBM_PRINT_TYPE_NODE, rec, show, stdout); return 0; } int idbm_print_iface_info(void *data, struct iface_rec *iface) { int show = *((int *)data); idbm_print(IDBM_PRINT_TYPE_IFACE, iface, show, stdout); return 0; } int idbm_print_host_chap_info(struct iscsi_chap_rec *chap) { /* User only calls this to print chap so always print */ idbm_print(IDBM_PRINT_TYPE_HOST_CHAP, chap, 1, stdout); return 0; } int idbm_print_node_flat(void *data, node_rec_t *rec) { if (strchr(rec->conn[0].address, '.')) printf("%s:%d,%d %s\n", rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->name); else printf("[%s]:%d,%d %s\n", rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->name); return 0; } int idbm_print_node_tree(struct node_rec *last_rec, struct node_rec *rec, char *prefix) { if (!last_rec || strcmp(last_rec->name, rec->name)) { printf("%sTarget: %s\n", prefix, rec->name); if (last_rec) memset(last_rec, 0, sizeof(node_rec_t)); } if (!last_rec || ((strcmp(last_rec->conn[0].address, rec->conn[0].address) || last_rec->conn[0].port != rec->conn[0].port))) { if (strchr(rec->conn[0].address, '.')) printf("%s\tPortal: %s:%d,%d\n", prefix, rec->conn[0].address, rec->conn[0].port, rec->tpgt); else printf("%s\tPortal: [%s]:%d,%d\n", prefix, rec->conn[0].address, rec->conn[0].port, rec->tpgt); } if (last_rec) memcpy(last_rec, rec, sizeof(node_rec_t)); return 0; } int idbm_print_node_and_iface_tree(void *data, node_rec_t *rec) { idbm_print_node_tree(data, rec, ""); printf("\t\tIface Name: %s\n", rec->iface.name); return 0; } static int get_params_from_disc_link(char *link, char **target, char **tpgt, char **address, char **port, char **ifaceid) { (*target) = link; *address = strchr(*target, ','); if (!(*address)) return ISCSI_ERR_INVAL; *(*address)++ = '\0'; *port = strchr(*address, ','); if (!(*port)) return ISCSI_ERR_INVAL; *(*port)++ = '\0'; *tpgt = strchr(*port, ','); if (!(*tpgt)) return ISCSI_ERR_INVAL; *(*tpgt)++ = '\0'; *ifaceid = strchr(*tpgt, ','); if (!(*ifaceid)) return ISCSI_ERR_INVAL; *(*ifaceid)++ = '\0'; return 0; } int idbm_lock(void) { int fd, i, ret; if (db->refs > 0) { db->refs++; return 0; } if (access(LOCK_DIR, F_OK) != 0) { if (mkdir(LOCK_DIR, 0660) != 0) { log_error("Could not open %s: %s\n", LOCK_DIR, strerror(errno)); return ISCSI_ERR_IDBM; } } fd = open(LOCK_FILE, O_RDWR | O_CREAT, 0666); if (fd >= 0) close(fd); for (i = 0; i < 3000; i++) { ret = link(LOCK_FILE, LOCK_WRITE_FILE); if (ret == 0) break; if (errno != EEXIST) { log_error("Maybe you are not root?"); log_error("Could not lock discovery DB: %s: %s", LOCK_WRITE_FILE, strerror(errno)); return ISCSI_ERR_IDBM; } else if (i == 0) log_debug(2, "Waiting for discovery DB lock"); usleep(10000); } db->refs = 1; return 0; } void idbm_unlock(void) { if (db->refs > 1) { db->refs--; return; } db->refs = 0; unlink(LOCK_WRITE_FILE); } /* * Backwards Compat: * If the portal is a file then we are doing the old style default * session behavior (svn pre 780). */ static FILE *idbm_open_rec_r(char *portal, char *config) { struct stat statb; log_debug(5, "Looking for config file %s config %s.", portal, config); if (stat(portal, &statb)) { log_debug(5, "Could not stat %s err %d.", portal, errno); return NULL; } if (S_ISDIR(statb.st_mode)) { strlcat(portal, "/", PATH_MAX); strlcat(portal, config, PATH_MAX); } return fopen(portal, "r"); } static int __idbm_rec_read(node_rec_t *out_rec, char *conf) { recinfo_t *info; FILE *f; int rc = 0; info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return ISCSI_ERR_NOMEM; rc = idbm_lock(); if (rc) goto free_info; f = fopen(conf, "r"); if (!f) { log_debug(5, "Could not open %s err %s\n", conf, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } memset(out_rec, 0, sizeof(*out_rec)); idbm_node_setup_defaults(out_rec); idbm_recinfo_node(out_rec, info); idbm_recinfo_config(info, f); fclose(f); unlock: idbm_unlock(); free_info: free(info); return rc; } int idbm_rec_read(node_rec_t *out_rec, char *targetname, int tpgt, char *ip, int port, struct iface_rec *iface) { struct stat statb; char *portal; int rc; portal = calloc(1, PATH_MAX); if (!portal) return ISCSI_ERR_IDBM; /* try old style portal as config */ snprintf(portal, PATH_MAX, "%s/%s/%s,%d", NODE_CONFIG_DIR, targetname, ip, port); log_debug(5, "rec read looking for config file %s.", portal); if (!stat(portal, &statb)) goto read; snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d/%s", NODE_CONFIG_DIR, targetname, ip, port, tpgt, iface->name); log_debug(5, "rec read looking for config file %s.", portal); if (!strlen(iface->name)) { rc = ISCSI_ERR_INVAL; goto free_portal; } if (stat(portal, &statb)) { log_debug(5, "Could not stat %s: %s.", portal, strerror(errno)); free(portal); return ISCSI_ERR_IDBM; } read: rc = __idbm_rec_read(out_rec, portal); free_portal: free(portal); return rc; } static int print_discovered_flat(void *data, node_rec_t *rec) { struct discovery_rec *drec = data; if (rec->disc_type != drec->type) goto no_match; if (drec->type == DISCOVERY_TYPE_SENDTARGETS || drec->type == DISCOVERY_TYPE_ISNS) { if (rec->disc_port != drec->port || strcmp(rec->disc_address, drec->address)) goto no_match; } idbm_print_node_flat(NULL, rec); return 0; no_match: return -1; } struct discovered_tree_info { struct discovery_rec *drec; struct node_rec *last_rec; }; static int print_discovered_tree(void *data, node_rec_t *rec) { struct discovered_tree_info *tree_info = data; struct discovery_rec *drec = tree_info->drec; if (rec->disc_type != drec->type) goto no_match; if (strlen(drec->address)) { if (rec->disc_port != drec->port || strcmp(rec->disc_address, drec->address)) goto no_match; } idbm_print_node_and_iface_tree(tree_info->last_rec, rec); return 0; no_match: return -1; } static int idbm_print_discovered(discovery_rec_t *drec, int info_level) { int num_found = 0; if (info_level < 1) idbm_for_each_rec(&num_found, drec, print_discovered_flat); else { struct discovered_tree_info tree_info; struct node_rec last_rec; memset(&last_rec, 0, sizeof(struct node_rec)); tree_info.drec = drec; tree_info.last_rec = &last_rec; idbm_for_each_rec(&num_found, &tree_info, print_discovered_tree); } return num_found; } static int idbm_for_each_drec(int type, char *config_root, void *data, idbm_drec_op_fn *fn) { DIR *entity_dirfd; struct dirent *entity_dent; int found = 0; discovery_rec_t drec; char *tmp_port; entity_dirfd = opendir(config_root); if (!entity_dirfd) return found; while ((entity_dent = readdir(entity_dirfd))) { if (!strcmp(entity_dent->d_name, ".") || !strcmp(entity_dent->d_name, "..")) continue; log_debug(5, "found %s\n", entity_dent->d_name); tmp_port = strchr(entity_dent->d_name, ','); if (!tmp_port) continue; /* * pre 872 tools dumped the target portal symlinks in the isns * dir instead of the server. If we find one of those links * (by checking if there is a valid port) we skip it. */ if (strchr(tmp_port, ':') || strchr(tmp_port, '.')) continue; *tmp_port++ = '\0'; memset(&drec, 0, sizeof(drec)); if (idbm_discovery_read(&drec, type, entity_dent->d_name, atoi(tmp_port))) { log_error("Could not read discovery record for " "%s:%s.", entity_dent->d_name, tmp_port); continue; } if (!fn(data, &drec)) found++; } closedir(entity_dirfd); return found; } int idbm_for_each_st_drec(void *data, idbm_drec_op_fn *fn) { return idbm_for_each_drec(DISCOVERY_TYPE_SENDTARGETS, ST_CONFIG_DIR, data, fn); } int idbm_for_each_isns_drec(void *data, idbm_drec_op_fn *fn) { return idbm_for_each_drec(DISCOVERY_TYPE_ISNS, ISNS_CONFIG_DIR, data, fn); } static int __idbm_print_all_by_drec(void *data, struct discovery_rec *drec) { int info_level = *(int *)data; if (info_level >= 1) { printf("DiscoveryAddress: %s,%d\n", drec->address, drec->port); idbm_print_discovered(drec, info_level); } else printf("%s:%d via %s\n", drec->address, drec->port, drec->type == DISCOVERY_TYPE_ISNS ? "isns" : "sendtargets"); return 0; } static int idbm_print_all_st(int info_level) { int rc; rc = idbm_for_each_st_drec(&info_level, __idbm_print_all_by_drec); if (rc < 0) return 0; return rc; } static int idbm_print_all_isns(int info_level) { int rc; rc = idbm_for_each_isns_drec(&info_level, __idbm_print_all_by_drec); if (rc < 0) return 0; return rc; } int idbm_print_all_discovery(int info_level) { discovery_rec_t *drec; int found = 0, tmp; if (info_level < 1) { found = idbm_print_all_st(info_level); found += idbm_print_all_isns(info_level); return found; } drec = calloc(1, sizeof(*drec)); if (!drec) return 0; tmp = 0; printf("SENDTARGETS:\n"); tmp = idbm_print_all_st(info_level); if (!tmp) printf("No targets found.\n"); found += tmp; tmp = 0; printf("iSNS:\n"); tmp = idbm_print_all_isns(info_level); if (!tmp) { /* * pre 872 tools did not store the server ip,port so * we drop down here, to just look for target portals. */ drec->type = DISCOVERY_TYPE_ISNS; tmp = idbm_print_discovered(drec, info_level); if (!tmp) printf("No targets found.\n"); } found += tmp; tmp = 0; printf("STATIC:\n"); drec->type = DISCOVERY_TYPE_STATIC; tmp = idbm_print_discovered(drec, info_level); if (!tmp) printf("No targets found.\n"); found += tmp; tmp = 0; printf("FIRMWARE:\n"); drec->type = DISCOVERY_TYPE_FW; tmp = idbm_print_discovered(drec, info_level); if (!tmp) printf("No targets found.\n"); found += tmp; free(drec); return found; } /** * idbm_for_each_iface - iterate over bound iface recs * @found: nr of recs found so far * @data: data pointer passed to fn * @fn: iterator function ran over each bound iface rec * @targetname: rec's target name * @tpgt: rec's portal group tag * @ip: rec's ip address * @port: rec's port * * This will run fn over all recs with the {targetname,tpgt,ip,port} * id. It does not iterate over the ifaces setup in /etc/iscsi/ifaces. * * fn should return -1 if it skipped the rec, a ISCSI_ERR error code if * the operation failed or 0 if fn was run successfully. */ static int idbm_for_each_iface(int *found, void *data, idbm_iface_op_fn *fn, char *targetname, int tpgt, char *ip, int port) { DIR *iface_dirfd; struct dirent *iface_dent; struct stat statb; node_rec_t rec; int rc = 0; char *portal; portal = calloc(1, PATH_MAX); if (!portal) return ISCSI_ERR_NOMEM; if (tpgt >= 0) goto read_iface; /* old style portal as a config */ snprintf(portal, PATH_MAX, "%s/%s/%s,%d", NODE_CONFIG_DIR, targetname, ip, port); if (stat(portal, &statb)) { log_error("iface iter could not stat %s.", portal); rc = ISCSI_ERR_IDBM; goto free_portal; } rc = __idbm_rec_read(&rec, portal); if (rc) goto free_portal; rc = fn(data, &rec); if (!rc) (*found)++; else if (rc == -1) rc = 0; goto free_portal; read_iface: snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d", NODE_CONFIG_DIR, targetname, ip, port, tpgt); iface_dirfd = opendir(portal); if (!iface_dirfd) { log_error("iface iter could not read dir %s.", portal); rc = ISCSI_ERR_IDBM; goto free_portal; } while ((iface_dent = readdir(iface_dirfd))) { int curr_rc; if (!strcmp(iface_dent->d_name, ".") || !strcmp(iface_dent->d_name, "..")) continue; log_debug(5, "iface iter found %s.", iface_dent->d_name); memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d/%s", NODE_CONFIG_DIR, targetname, ip, port, tpgt, iface_dent->d_name); if (__idbm_rec_read(&rec, portal)) continue; curr_rc = fn(data, &rec); /* less than zero means it was not a match */ if (curr_rc > 0 && !rc) rc = curr_rc; else if (curr_rc == 0) (*found)++; } closedir(iface_dirfd); free_portal: free(portal); return rc; } /* * backwards compat * The portal could be a file or dir with interfaces */ int idbm_for_each_portal(int *found, void *data, idbm_portal_op_fn *fn, char *targetname) { DIR *portal_dirfd; struct dirent *portal_dent; int rc = 0; char *portal; portal = calloc(1, PATH_MAX); if (!portal) return ISCSI_ERR_NOMEM; snprintf(portal, PATH_MAX, "%s/%s", NODE_CONFIG_DIR, targetname); portal_dirfd = opendir(portal); if (!portal_dirfd) { rc = ISCSI_ERR_IDBM; goto done; } while ((portal_dent = readdir(portal_dirfd))) { char *tmp_port, *tmp_tpgt; int curr_rc; if (!strcmp(portal_dent->d_name, ".") || !strcmp(portal_dent->d_name, "..")) continue; log_debug(5, "found %s\n", portal_dent->d_name); tmp_port = strchr(portal_dent->d_name, ','); if (!tmp_port) continue; *tmp_port++ = '\0'; tmp_tpgt = strchr(tmp_port, ','); if (tmp_tpgt) *tmp_tpgt++ = '\0'; curr_rc = fn(found, data, targetname, tmp_tpgt ? atoi(tmp_tpgt) : -1, portal_dent->d_name, atoi(tmp_port)); /* less than zero means it was not a match */ if (curr_rc > 0 && !rc) rc = curr_rc; } closedir(portal_dirfd); done: free(portal); return rc; } int idbm_for_each_node(int *found, void *data, idbm_node_op_fn *fn) { DIR *node_dirfd; struct dirent *node_dent; int rc = 0; *found = 0; node_dirfd = opendir(NODE_CONFIG_DIR); if (!node_dirfd) /* on start up node dir may not be created */ return 0; while ((node_dent = readdir(node_dirfd))) { int curr_rc; if (!strcmp(node_dent->d_name, ".") || !strcmp(node_dent->d_name, "..")) continue; log_debug(5, "searching %s\n", node_dent->d_name); curr_rc = fn(found, data, node_dent->d_name); /* less than zero means it was not a match */ if (curr_rc > 0 && !rc) rc = curr_rc; } closedir(node_dirfd); return rc; } static int iface_fn(void *data, node_rec_t *rec) { struct rec_op_data *op_data = data; return op_data->fn(op_data->data, rec); } static int portal_fn(int *found, void *data, char *targetname, int tpgt, char *ip, int port) { return idbm_for_each_iface(found, data, iface_fn, targetname, tpgt, ip, port); } static int node_fn(int *found, void *data, char *targetname) { return idbm_for_each_portal(found, data, portal_fn, targetname); } int idbm_for_each_rec(int *found, void *data, idbm_iface_op_fn *fn) { struct rec_op_data op_data; memset(&op_data, 0, sizeof(struct rec_op_data)); op_data.data = data; op_data.fn = fn; return idbm_for_each_node(found, &op_data, node_fn); } static struct { char *config_root; char *config_name; } disc_type_to_config_vals[] = { { ST_CONFIG_DIR, ST_CONFIG_NAME }, { ISNS_CONFIG_DIR, ISNS_CONFIG_NAME }, }; int idbm_discovery_read(discovery_rec_t *out_rec, int drec_type, char *addr, int port) { recinfo_t *info; char *portal; int rc = 0; FILE *f; if (drec_type > 1) return ISCSI_ERR_INVAL; memset(out_rec, 0, sizeof(discovery_rec_t)); info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return ISCSI_ERR_NOMEM; portal = malloc(PATH_MAX); if (!portal) { rc = ISCSI_ERR_NOMEM; goto free_info; } snprintf(portal, PATH_MAX, "%s/%s,%d", disc_type_to_config_vals[drec_type].config_root, addr, port); log_debug(5, "Looking for config file %s\n", portal); rc = idbm_lock(); if (rc) goto free_info; f = idbm_open_rec_r(portal, disc_type_to_config_vals[drec_type].config_name); if (!f) { log_debug(1, "Could not open %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } idbm_discovery_setup_defaults(out_rec, drec_type); idbm_recinfo_discovery(out_rec, info); idbm_recinfo_config(info, f); fclose(f); unlock: idbm_unlock(); free_info: free(portal); free(info); return rc; } /* * Backwards Compat: * If the portal is a file then we are doing the old style default * session behavior (svn pre 780). */ static FILE *idbm_open_rec_w(char *portal, char *config) { struct stat statb; FILE *f; int err; log_debug(5, "Looking for config file %s\n", portal); err = stat(portal, &statb); if (err) goto mkdir_portal; if (!S_ISDIR(statb.st_mode)) { /* * Old style portal as a file. Let's update it. */ if (unlink(portal)) { log_error("Could not convert %s to %s/%s. " "err %d\n", portal, portal, config, errno); return NULL; } mkdir_portal: if (mkdir(portal, 0660) != 0) { log_error("Could not make dir %s err %d\n", portal, errno); return NULL; } } strlcat(portal, "/", PATH_MAX); strlcat(portal, config, PATH_MAX); f = fopen(portal, "w"); if (!f) log_error("Could not open %s err %d\n", portal, errno); return f; } static int idbm_rec_write(node_rec_t *rec) { struct stat statb; FILE *f; char *portal; int rc = 0; portal = malloc(PATH_MAX); if (!portal) { log_error("Could not alloc portal\n"); return ISCSI_ERR_NOMEM; } snprintf(portal, PATH_MAX, "%s", NODE_CONFIG_DIR); if (access(portal, F_OK) != 0) { if (mkdir(portal, 0660) != 0) { log_error("Could not make %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto free_portal; } } snprintf(portal, PATH_MAX, "%s/%s", NODE_CONFIG_DIR, rec->name); if (access(portal, F_OK) != 0) { if (mkdir(portal, 0660) != 0) { log_error("Could not make %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto free_portal; } } snprintf(portal, PATH_MAX, "%s/%s/%s,%d", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port); log_debug(5, "Looking for config file %s", portal); rc = idbm_lock(); if (rc) goto free_portal; rc = stat(portal, &statb); if (rc) { rc = 0; /* * older iscsiadm versions had you create the config then set * set the tgpt. In new versions you must pass all the info in * from the start */ if (rec->tpgt == PORTAL_GROUP_TAG_UNKNOWN) /* drop down to old style portal as config */ goto open_conf; else goto mkdir_portal; } if (!S_ISDIR(statb.st_mode)) { /* * older iscsiadm versions had you create the config then set * set the tgpt. In new versions you must pass all the info in * from the start */ if (rec->tpgt == PORTAL_GROUP_TAG_UNKNOWN) /* drop down to old style portal as config */ goto open_conf; /* * Old style portal as a file, but with tpgt. Let's update it. */ if (unlink(portal)) { log_error("Could not convert %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } } else { rc = ISCSI_ERR_INVAL; goto unlock; } mkdir_portal: snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt); if (stat(portal, &statb)) { if (mkdir(portal, 0660) != 0) { log_error("Could not make dir %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } } snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d/%s", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); open_conf: f = fopen(portal, "w"); if (!f) { log_error("Could not open %s: %sd\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } idbm_print(IDBM_PRINT_TYPE_NODE, rec, 1, f); fclose(f); unlock: idbm_unlock(); free_portal: free(portal); return rc; } static int idbm_discovery_write(discovery_rec_t *rec) { FILE *f; char *portal; int rc = 0; if (rec->type > 1) return ISCSI_ERR_INVAL; portal = malloc(PATH_MAX); if (!portal) { log_error("Could not alloc portal\n"); return ISCSI_ERR_NOMEM; } rc = idbm_lock(); if (rc) goto free_portal; snprintf(portal, PATH_MAX, "%s", disc_type_to_config_vals[rec->type].config_root); if (access(portal, F_OK) != 0) { if (mkdir(portal, 0660) != 0) { log_error("Could not make %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } } snprintf(portal, PATH_MAX, "%s/%s,%d", disc_type_to_config_vals[rec->type].config_root, rec->address, rec->port); f = idbm_open_rec_w(portal, disc_type_to_config_vals[rec->type].config_name); if (!f) { log_error("Could not open %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } idbm_print(IDBM_PRINT_TYPE_DISCOVERY, rec, 1, f); fclose(f); unlock: idbm_unlock(); free_portal: free(portal); return rc; } int idbm_add_discovery(discovery_rec_t *newrec) { discovery_rec_t rec; if (!idbm_discovery_read(&rec, newrec->type, newrec->address, newrec->port)) { log_debug(7, "disc rec already exists"); /* fall through */ } else log_debug(7, "adding new DB record"); return idbm_discovery_write(newrec); } static int setup_disc_to_node_link(char *disc_portal, node_rec_t *rec) { struct stat statb; int rc = 0; switch (rec->disc_type) { case DISCOVERY_TYPE_SENDTARGETS: /* st dir setup when we create its discovery node */ snprintf(disc_portal, PATH_MAX, "%s/%s,%d/%s,%s,%d,%d,%s", ST_CONFIG_DIR, rec->disc_address, rec->disc_port, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); break; case DISCOVERY_TYPE_FW: if (access(FW_CONFIG_DIR, F_OK) != 0) { if (mkdir(FW_CONFIG_DIR, 0660) != 0) { log_error("Could not make %s: %s", FW_CONFIG_DIR, strerror(errno)); rc = ISCSI_ERR_IDBM; } } snprintf(disc_portal, PATH_MAX, "%s/%s,%s,%d,%d,%s", FW_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); break; case DISCOVERY_TYPE_STATIC: if (access(STATIC_CONFIG_DIR, F_OK) != 0) { if (mkdir(STATIC_CONFIG_DIR, 0660) != 0) { log_error("Could not make %s; %s", STATIC_CONFIG_DIR, strerror(errno)); rc = ISCSI_ERR_IDBM; } } snprintf(disc_portal, PATH_MAX, "%s/%s,%s,%d,%d,%s", STATIC_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); break; case DISCOVERY_TYPE_ISNS: if (access(ISNS_CONFIG_DIR, F_OK) != 0) { if (mkdir(ISNS_CONFIG_DIR, 0660) != 0) { log_error("Could not make %s: %s", ISNS_CONFIG_DIR, strerror(errno)); rc = ISCSI_ERR_IDBM; } } /* * Older tools lumped all portals together in the * isns config dir. In 2.0-872, the isns dir added * a isns server (ddress and port) dir like sendtargets. * * If we found a older style link we return that so it * can be removed. If this function is called for * addition of a rec then the older link should have been * removed and we break down below. */ snprintf(disc_portal, PATH_MAX, "%s/%s,%s,%d,%d,%s", ISNS_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); if (!stat(disc_portal, &statb)) { log_debug(7, "using old style isns dir %s.", disc_portal); break; } snprintf(disc_portal, PATH_MAX, "%s/%s,%d", ISNS_CONFIG_DIR, rec->disc_address, rec->disc_port); if (!stat(disc_portal, &statb) && S_ISDIR(statb.st_mode)) { /* * if there is a dir for this isns server then * assume we are using the new style links */ snprintf(disc_portal, PATH_MAX, "%s/%s,%d/%s,%s,%d,%d,%s", ISNS_CONFIG_DIR, rec->disc_address, rec->disc_port, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); break; } /* adding a older link */ snprintf(disc_portal, PATH_MAX, "%s/%s,%s,%d,%d,%s", ISNS_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); break; case DISCOVERY_TYPE_SLP: default: rc = ISCSI_ERR_INVAL; } return rc; } int idbm_add_node(node_rec_t *newrec, discovery_rec_t *drec, int overwrite) { node_rec_t rec; char *node_portal, *disc_portal; int rc; if (!idbm_rec_read(&rec, newrec->name, newrec->tpgt, newrec->conn[0].address, newrec->conn[0].port, &newrec->iface)) { if (!overwrite) return 0; rc = idbm_delete_node(&rec); if (rc) return rc; log_debug(7, "overwriting existing record"); } else log_debug(7, "adding new DB record"); if (drec) { newrec->disc_type = drec->type; newrec->disc_port = drec->port; strcpy(newrec->disc_address, drec->address); } rc = idbm_rec_write(newrec); /* * if a old app passed in a bogus tpgt then we do not create links * since it will set a different tpgt in another iscsiadm call */ if (rc || !drec || newrec->tpgt == PORTAL_GROUP_TAG_UNKNOWN) return rc; node_portal = calloc(2, PATH_MAX); if (!node_portal) return ISCSI_ERR_NOMEM; disc_portal = node_portal + PATH_MAX; snprintf(node_portal, PATH_MAX, "%s/%s/%s,%d,%d", NODE_CONFIG_DIR, newrec->name, newrec->conn[0].address, newrec->conn[0].port, newrec->tpgt); rc = setup_disc_to_node_link(disc_portal, newrec); if (rc) goto free_portal; log_debug(7, "node addition making link from %s to %s", node_portal, disc_portal); rc = idbm_lock(); if (rc) goto free_portal; if (symlink(node_portal, disc_portal)) { if (errno == EEXIST) log_debug(7, "link from %s to %s exists", node_portal, disc_portal); else { rc = ISCSI_ERR_IDBM; log_error("Could not make link from disc source %s to " "node %s: %s", disc_portal, node_portal, strerror(errno)); } } idbm_unlock(); free_portal: free(node_portal); return rc; } static int idbm_bind_iface_to_nodes(idbm_disc_nodes_fn *disc_node_fn, void *data, struct iface_rec *iface, struct list_head *bound_recs) { struct node_rec *rec, *tmp; struct list_head new_recs; int rc; INIT_LIST_HEAD(&new_recs); rc = disc_node_fn(data, iface, &new_recs); if (rc) return rc; list_for_each_entry_safe(rec, tmp, &new_recs, list) { list_del_init(&rec->list); list_add_tail(&rec->list, bound_recs); iface_copy(&rec->iface, iface); } return 0; } static int discovery_error_fatal(int err) { switch (err) { /* No error */ case ISCSI_SUCCESS: /* Transport errors or timeouts are not fatal */ case ISCSI_ERR_TRANS: case ISCSI_ERR_TRANS_TIMEOUT: return 0; } return 1; } int idbm_bind_ifaces_to_nodes(idbm_disc_nodes_fn *disc_node_fn, void *data, struct list_head *ifaces, struct list_head *bound_recs) { struct list_head def_ifaces; struct node_rec *rec, *tmp_rec; struct iface_rec *iface, *tmp_iface; struct iscsi_transport *t; int rc = 0, found = 0; INIT_LIST_HEAD(&def_ifaces); if (!ifaces || list_empty(ifaces)) { iface_link_ifaces(&def_ifaces); list_for_each_entry_safe(iface, tmp_iface, &def_ifaces, list) { list_del(&iface->list); t = iscsi_sysfs_get_transport_by_name(iface->transport_name); /* * only auto bind to software iscsi if it is * not the default iface (that is handled below) */ if (!t || strcmp(t->name, DEFAULT_TRANSPORT) || !strcmp(iface->name, DEFAULT_IFACENAME)) { free(iface); continue; } rc = idbm_bind_iface_to_nodes(disc_node_fn, data, iface, bound_recs); free(iface); if (discovery_error_fatal(rc)) goto fail; found = 1; } /* create default iface with old/default behavior */ if (!found) { struct iface_rec def_iface; memset(&def_iface, 0, sizeof(struct iface_rec)); iface_setup_defaults(&def_iface); return idbm_bind_iface_to_nodes(disc_node_fn, data, &def_iface, bound_recs); } } else { list_for_each_entry(iface, ifaces, list) { if (strcmp(iface->name, DEFAULT_IFACENAME) && !iface_is_valid(iface)) { log_error("iface %s is not valid. Will not " "bind node to it. Iface settings " iface_fmt, iface->name, iface_str(iface)); continue; } rc = idbm_bind_iface_to_nodes(disc_node_fn, data, iface, bound_recs); if (discovery_error_fatal(rc)) goto fail; } } return 0; fail: list_for_each_entry_safe(iface, tmp_iface, &def_ifaces, list) { list_del(&iface->list); free(iface); } list_for_each_entry_safe(rec, tmp_rec, bound_recs, list) { list_del(&rec->list); free(rec); } return rc; } static void idbm_rm_disc_node_links(char *disc_dir) { char *target = NULL, *tpgt = NULL, *port = NULL; char *address = NULL, *iface_id = NULL; DIR *disc_dirfd; struct dirent *disc_dent; node_rec_t *rec; rec = calloc(1, sizeof(*rec)); if (!rec) return; disc_dirfd = opendir(disc_dir); if (!disc_dirfd) goto free_rec; /* rm links to nodes */ while ((disc_dent = readdir(disc_dirfd))) { if (!strcmp(disc_dent->d_name, ".") || !strcmp(disc_dent->d_name, "..")) continue; if (get_params_from_disc_link(disc_dent->d_name, &target, &tpgt, &address, &port, &iface_id)) { log_error("Improperly formed disc to node link"); continue; } log_debug(5, "disc removal removing link %s %s %s %s", target, address, port, iface_id); memset(rec, 0, sizeof(*rec)); strlcpy(rec->name, target, TARGET_NAME_MAXLEN); rec->tpgt = atoi(tpgt); rec->conn[0].port = atoi(port); strlcpy(rec->conn[0].address, address, NI_MAXHOST); strlcpy(rec->iface.name, iface_id, ISCSI_MAX_IFACE_LEN); if (idbm_delete_node(rec)) log_error("Could not delete node %s/%s/%s,%s/%s", NODE_CONFIG_DIR, target, address, port, iface_id); } closedir(disc_dirfd); free_rec: free(rec); } int idbm_delete_discovery(discovery_rec_t *drec) { char *portal; struct stat statb; int rc = 0; portal = calloc(1, PATH_MAX); if (!portal) return ISCSI_ERR_NOMEM; snprintf(portal, PATH_MAX, "%s/%s,%d", disc_type_to_config_vals[drec->type].config_root, drec->address, drec->port); log_debug(5, "Removing config file %s\n", portal); if (stat(portal, &statb)) { log_debug(5, "Could not stat %s to delete disc err %d\n", portal, errno); goto free_portal; } if (S_ISDIR(statb.st_mode)) { strlcat(portal, "/", PATH_MAX); strlcat(portal, disc_type_to_config_vals[drec->type].config_name, PATH_MAX); } if (unlink(portal)) log_debug(5, "Could not remove %s err %d\n", portal, errno); memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s,%d", disc_type_to_config_vals[drec->type].config_root, drec->address, drec->port); idbm_rm_disc_node_links(portal); /* rm portal dir */ if (S_ISDIR(statb.st_mode)) { memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s,%d", disc_type_to_config_vals[drec->type].config_root, drec->address, drec->port); rmdir(portal); } free_portal: free(portal); return rc; } /* * Backwards Compat or SLP: * if there is no link then this is pre svn 780 version where * we did not link the disc source and node */ static int idbm_remove_disc_to_node_link(node_rec_t *rec, char *portal) { int rc = 0; struct stat statb; node_rec_t *tmprec; tmprec = malloc(sizeof(*tmprec)); if (!tmprec) return ISCSI_ERR_NOMEM; memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d/%s", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); rc = __idbm_rec_read(tmprec, portal); if (rc) { /* old style recs will not have tpgt or a link so skip */ rc = 0; goto done; } log_debug(7, "found drec %s %d\n", tmprec->disc_address, tmprec->disc_port); /* rm link from discovery source to node */ memset(portal, 0, PATH_MAX); rc = setup_disc_to_node_link(portal, tmprec); if (rc) goto done; rc = idbm_lock(); if (rc) goto done; if (!stat(portal, &statb)) { if (unlink(portal)) { log_error("Could not remove link %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; } else log_debug(7, "rmd %s", portal); } else log_debug(7, "Could not stat %s", portal); idbm_unlock(); done: free(tmprec); return rc; } static int st_disc_filter(const struct dirent *dir) { return strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..") && strcmp(dir->d_name, ST_CONFIG_NAME); } int idbm_delete_node(node_rec_t *rec) { struct stat statb; char *portal; int rc = 0, dir_rm_rc = 0; portal = calloc(1, PATH_MAX); if (!portal) return ISCSI_ERR_NOMEM; rc = idbm_remove_disc_to_node_link(rec, portal); if (rc) goto free_portal; memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s/%s,%d", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port); log_debug(5, "Removing config file %s iface id %s\n", portal, rec->iface.name); rc = idbm_lock(); if (rc) goto free_portal; if (!stat(portal, &statb)) goto rm_conf; snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d/%s", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt, rec->iface.name); log_debug(5, "Removing config file %s", portal); if (!stat(portal, &statb)) goto rm_conf; log_error("Could not stat %s to delete node: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; rm_conf: if (unlink(portal)) { log_error("Could not remove %s: %s\n", portal, strerror(errno)); rc = ISCSI_ERR_IDBM; goto unlock; } memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt); if (!stat(portal, &statb)) { struct dirent **namelist; int n, i; memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s/%s,%d,%d", NODE_CONFIG_DIR, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt); n = scandir(portal, &namelist, st_disc_filter, alphasort); if (n < 0) goto free_portal; if (n == 0) dir_rm_rc = rmdir(portal); for (i = 0; i < n; i++) free(namelist[i]); free(namelist); } /* rm target dir */ if (!dir_rm_rc) { memset(portal, 0, PATH_MAX); snprintf(portal, PATH_MAX, "%s/%s", NODE_CONFIG_DIR, rec->name); rmdir(portal); } unlock: idbm_unlock(); free_portal: free(portal); return rc; } void idbm_sendtargets_defaults(struct iscsi_sendtargets_config *cfg) { idbm_sync_config(); memcpy(cfg, &db->drec_st.u.sendtargets, sizeof(struct iscsi_sendtargets_config)); } void idbm_isns_defaults(struct iscsi_isns_config *cfg) { idbm_sync_config(); memcpy(cfg, &db->drec_isns.u.isns, sizeof(struct iscsi_isns_config)); } void idbm_slp_defaults(struct iscsi_slp_config *cfg) { memcpy(cfg, &db->drec_slp.u.slp, sizeof(struct iscsi_slp_config)); } struct user_param *idbm_alloc_user_param(char *name, char *value) { struct user_param *param; param = calloc(1, sizeof(*param)); if (!param) return NULL; INIT_LIST_HEAD(¶m->list); param->name = strdup(name); if (!param->name) goto free_param; param->value = strdup(value); if (!param->value) goto free_name; return param; free_name: free(param->name); free_param: free(param); return NULL; } int idbm_node_set_rec_from_param(struct list_head *params, node_rec_t *rec, int verify) { struct user_param *param; recinfo_t *info; int rc = 0; if (list_empty(params)) return 0; info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return ISCSI_ERR_NOMEM; idbm_recinfo_node(rec, info); if (verify) { list_for_each_entry(param, params, list) { rc = idbm_verify_param(info, param->name); if (rc) goto free_info; } } list_for_each_entry(param, params, list) { rc = idbm_rec_update_param(info, param->name, param->value, 0); if (rc) { if (rc == ISCSI_ERR_INVAL) log_error("Unknown parameter %s.", param->name); goto free_info; } } free_info: free(info); return rc; } int idbm_node_set_param(void *data, node_rec_t *rec) { int rc; rc = idbm_node_set_rec_from_param(data, rec, 1); if (rc) return rc; return idbm_rec_write(rec); } int idbm_discovery_set_param(void *data, discovery_rec_t *rec) { struct list_head *params = data; struct user_param *param; recinfo_t *info; int rc = 0; info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return ISCSI_ERR_NOMEM; idbm_recinfo_discovery((discovery_rec_t *)rec, info); list_for_each_entry(param, params, list) { rc = idbm_verify_param(info, param->name); if (rc) goto free_info; } list_for_each_entry(param, params, list) { rc = idbm_rec_update_param(info, param->name, param->value, 0); if (rc) goto free_info; } rc = idbm_discovery_write((discovery_rec_t *)rec); if (rc) goto free_info; free_info: free(info); return rc; } int idbm_init(idbm_get_config_file_fn *fn) { /* make sure root db dir is there */ if (access(ISCSI_CONFIG_ROOT, F_OK) != 0) { if (mkdir(ISCSI_CONFIG_ROOT, 0660) != 0) { log_error("Could not make %s %d\n", ISCSI_CONFIG_ROOT, errno); return errno; } } db = malloc(sizeof(idbm_t)); if (!db) { log_error("out of memory on idbm allocation"); return ISCSI_ERR_NOMEM; } memset(db, 0, sizeof(idbm_t)); db->get_config_file = fn; return 0; } void idbm_terminate(void) { if (db) free(db); } /** * idbm_create_rec - allocate and setup a node record * @targetname: target name * @tgpt: target portal group * @ip: ip address of portal * @port: port of portal * @iface: iscsi iface info * @verbose: flag indicating whether to log ifaces setup errors * * The iface only needs to have the name set. This function will * read in the other values. */ struct node_rec *idbm_create_rec(char *targetname, int tpgt, char *ip, int port, struct iface_rec *iface, int verbose) { struct node_rec *rec; rec = calloc(1, sizeof(*rec)); if (!rec) { log_error("Could not not allocate memory to create node " "record."); return NULL; } idbm_node_setup_defaults(rec); if (targetname) strlcpy(rec->name, targetname, TARGET_NAME_MAXLEN); rec->tpgt = tpgt; rec->conn[0].port = port; if (ip) strlcpy(rec->conn[0].address, ip, NI_MAXHOST); memset(&rec->iface, 0, sizeof(struct iface_rec)); if (iface) { iface_copy(&rec->iface, iface); if (strlen(iface->name)) { if (iface_conf_read(&rec->iface)) { if (verbose) log_error("Could not read iface info " "for %s.", iface->name); goto free_rec; } } } return rec; free_rec: free(rec); return NULL; } struct node_rec *idbm_create_rec_from_boot_context(struct boot_context *context) { struct node_rec *rec; /* tpgt hard coded to 1 ??? */ rec = idbm_create_rec(context->targetname, 1, context->target_ipaddr, context->target_port, NULL, 1); if (!rec) { log_error("Could not setup rec for fw discovery login."); return NULL; } iface_setup_defaults(&rec->iface); strlcpy(rec->session.auth.username, context->chap_name, sizeof(context->chap_name)); strlcpy((char *)rec->session.auth.password, context->chap_password, sizeof(context->chap_password)); strlcpy(rec->session.auth.username_in, context->chap_name_in, sizeof(context->chap_name_in)); strlcpy((char *)rec->session.auth.password_in, context->chap_password_in, sizeof(context->chap_password_in)); rec->session.auth.password_length = strlen((char *)context->chap_password); rec->session.auth.password_in_length = strlen((char *)context->chap_password_in); iface_setup_from_boot_context(&rec->iface, context); return rec; } void idbm_node_setup_defaults(node_rec_t *rec) { int i; memset(rec, 0, sizeof(node_rec_t)); INIT_LIST_HEAD(&rec->list); rec->tpgt = PORTAL_GROUP_TAG_UNKNOWN; rec->disc_type = DISCOVERY_TYPE_STATIC; rec->leading_login = 0; rec->session.cmds_max = CMDS_MAX; rec->session.xmit_thread_priority = XMIT_THREAD_PRIORITY; rec->session.initial_cmdsn = 0; rec->session.queue_depth = QUEUE_DEPTH; rec->session.nr_sessions = 1; rec->session.initial_login_retry_max = DEF_INITIAL_LOGIN_RETRIES_MAX; rec->session.reopen_max = 32; rec->session.auth.authmethod = 0; rec->session.auth.password_length = 0; rec->session.auth.password_in_length = 0; rec->session.err_timeo.abort_timeout = DEF_ABORT_TIMEO; rec->session.err_timeo.lu_reset_timeout = DEF_LU_RESET_TIMEO; rec->session.err_timeo.tgt_reset_timeout = DEF_TGT_RESET_TIMEO; rec->session.err_timeo.host_reset_timeout = DEF_HOST_RESET_TIMEO; rec->session.timeo.replacement_timeout = DEF_REPLACEMENT_TIMEO; rec->session.info = NULL; rec->session.sid = 0; rec->session.multiple = 0; idbm_setup_session_defaults(&rec->session.iscsi); for (i=0; iconn[i].startup = ISCSI_STARTUP_MANUAL; rec->conn[i].port = ISCSI_LISTEN_PORT; rec->conn[i].tcp.window_size = TCP_WINDOW_SIZE; rec->conn[i].tcp.type_of_service = 0; rec->conn[i].timeo.login_timeout= DEF_LOGIN_TIMEO; rec->conn[i].timeo.logout_timeout= DEF_LOGOUT_TIMEO; rec->conn[i].timeo.auth_timeout = 45; rec->conn[i].timeo.noop_out_interval = DEF_NOOP_OUT_INTERVAL; rec->conn[i].timeo.noop_out_timeout = DEF_NOOP_OUT_TIMEO; idbm_setup_conn_defaults(&rec->conn[i].iscsi); } iface_setup_defaults(&rec->iface); } struct node_rec * idbm_find_rec_in_list(struct list_head *rec_list, char *targetname, char *addr, int port, struct iface_rec *iface) { struct node_rec *rec; list_for_each_entry(rec, rec_list, list) { if (__iscsi_match_session(rec, targetname, addr, port, iface, MATCH_ANY_SID)) return rec; } return NULL; } open-iscsi-2.0.873/usr/idbm.h000066400000000000000000000146041175631155400156560ustar00rootroot00000000000000/* * iSCSI Discovery Database Library * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef IDBM_H #define IDBM_H #include #include #include "initiator.h" #include "config.h" #include "list.h" #define NODE_CONFIG_DIR ISCSI_CONFIG_ROOT"nodes" #define SLP_CONFIG_DIR ISCSI_CONFIG_ROOT"slp" #define ISNS_CONFIG_DIR ISCSI_CONFIG_ROOT"isns" #define STATIC_CONFIG_DIR ISCSI_CONFIG_ROOT"static" #define FW_CONFIG_DIR ISCSI_CONFIG_ROOT"fw" #define ST_CONFIG_DIR ISCSI_CONFIG_ROOT"send_targets" #define ST_CONFIG_NAME "st_config" #define ISNS_CONFIG_NAME "isns_config" #define TYPE_INT 0 #define TYPE_INT_O 1 #define TYPE_STR 2 #define TYPE_UINT8 3 #define TYPE_UINT16 4 #define MAX_KEYS 256 /* number of keys total(including CNX_MAX) */ #define NAME_MAXVAL 128 /* the maximum length of key name */ #define VALUE_MAXVAL 256 /* the maximum length of 223 bytes in the RFC. */ #define OPTS_MAXVAL 8 typedef struct recinfo { int type; char name[NAME_MAXVAL]; char value[VALUE_MAXVAL]; void *data; int data_len; int visible; char* opts[OPTS_MAXVAL]; int numopts; /* * bool indicating if we can change it or not. * TODO: make it a enum that can indicate wheter it also requires * a relogin to pick up if a session is running. */ int can_modify; } recinfo_t; typedef char *(idbm_get_config_file_fn)(void); typedef struct idbm { void *discdb; void *nodedb; char *configfile; int refs; idbm_get_config_file_fn *get_config_file; node_rec_t nrec; recinfo_t ninfo[MAX_KEYS]; discovery_rec_t drec_st; recinfo_t dinfo_st[MAX_KEYS]; discovery_rec_t drec_slp; recinfo_t dinfo_slp[MAX_KEYS]; discovery_rec_t drec_isns; recinfo_t dinfo_isns[MAX_KEYS]; } idbm_t; struct user_param { struct list_head list; char *name; char *value; }; typedef int (idbm_iface_op_fn)(void *data, node_rec_t *rec); typedef int (idbm_portal_op_fn)(int *found, void *data, char *targetname, int tpgt, char *ip, int port); typedef int (idbm_node_op_fn)(int *found, void *data, char *targetname); struct rec_op_data { void *data; node_rec_t *match_rec; idbm_iface_op_fn *fn; }; extern int idbm_for_each_portal(int *found, void *data, idbm_portal_op_fn *fn, char *targetname); extern int idbm_for_each_node(int *found, void *data, idbm_node_op_fn *fn); extern int idbm_for_each_rec(int *found, void *data, idbm_iface_op_fn *fn); typedef int (idbm_drec_op_fn)(void *data, discovery_rec_t *drec); extern int idbm_for_each_st_drec(void *data, idbm_drec_op_fn *fn); extern int idbm_for_each_isns_drec(void *data, idbm_drec_op_fn *fn); extern int idbm_init(idbm_get_config_file_fn *fn); extern void idbm_node_setup_from_conf(node_rec_t *rec); extern void idbm_terminate(void); extern int idbm_print_iface_info(void *data, struct iface_rec *iface); extern int idbm_print_node_info(void *data, node_rec_t *rec); extern int idbm_print_node_flat(void *data, node_rec_t *rec); extern int idbm_print_node_tree(struct node_rec *last_rec, struct node_rec *rec, char *prefix); extern int idbm_print_node_and_iface_tree(void *data, node_rec_t *rec); extern int idbm_print_discovery_info(discovery_rec_t *rec, int show); extern int idbm_print_all_discovery(int info_level); extern int idbm_delete_discovery(discovery_rec_t *rec); extern void idbm_node_setup_defaults(node_rec_t *rec); extern int idbm_delete_node(node_rec_t *rec); extern int idbm_add_node(node_rec_t *newrec, discovery_rec_t *drec, int overwrite); struct list_head; typedef int (idbm_disc_nodes_fn)(void *data, struct iface_rec *iface, struct list_head *recs); extern int idbm_bind_ifaces_to_nodes(idbm_disc_nodes_fn *disc_node_fn, void *data, struct list_head *ifaces, struct list_head *bound_recs); extern int idbm_add_discovery(discovery_rec_t *newrec); extern void idbm_sendtargets_defaults(struct iscsi_sendtargets_config *cfg); extern void idbm_isns_defaults(struct iscsi_isns_config *cfg); extern void idbm_slp_defaults(struct iscsi_slp_config *cfg); extern int idbm_discovery_read(discovery_rec_t *rec, int type, char *addr, int port); extern int idbm_rec_read(node_rec_t *out_rec, char *target_name, int tpgt, char *addr, int port, struct iface_rec *iface); extern int idbm_node_set_rec_from_param(struct list_head *params, node_rec_t *rec, int verify); extern int idbm_node_set_param(void *data, node_rec_t *rec); extern int idbm_discovery_set_param(void *data, discovery_rec_t *rec); struct user_param *idbm_alloc_user_param(char *name, char *value); extern void idbm_node_setup_defaults(node_rec_t *rec); extern struct node_rec *idbm_find_rec_in_list(struct list_head *rec_list, char *targetname, char *addr, int port, struct iface_rec *iface); /* lower level idbm functions for use by iface.c */ extern void idbm_recinfo_config(recinfo_t *info, FILE *f); extern void idbm_recinfo_iface(struct iface_rec *r, recinfo_t *ri); extern int idbm_lock(void); extern void idbm_unlock(void); extern recinfo_t *idbm_recinfo_alloc(int max_keys); extern int idbm_verify_param(recinfo_t *info, char *name); extern int idbm_rec_update_param(recinfo_t *info, char *name, char *value, int line_number); extern void idbm_recinfo_node(node_rec_t *r, recinfo_t *ri); enum { IDBM_PRINT_TYPE_DISCOVERY, IDBM_PRINT_TYPE_NODE, IDBM_PRINT_TYPE_IFACE, IDBM_PRINT_TYPE_HOST_CHAP, }; extern void idbm_print(int type, void *rec, int show, FILE *f); struct boot_context; extern struct node_rec *idbm_create_rec(char *targetname, int tpgt, char *ip, int port, struct iface_rec *iface, int verbose); extern struct node_rec * idbm_create_rec_from_boot_context(struct boot_context *context); extern int idbm_print_host_chap_info(struct iscsi_chap_rec *chap); #endif /* IDBM_H */ open-iscsi-2.0.873/usr/idbm_fields.h000066400000000000000000000141211175631155400171760ustar00rootroot00000000000000#ifndef IDBM_FIELDS_H #define IDBM_FIELDS_H #include "version.h" #define ISCSI_BEGIN_REC "# BEGIN RECORD "ISCSI_VERSION_STR #define ISCSI_END_REC "# END RECORD" /* node fields */ #define NODE_NAME "node.name" #define NODE_TPGT "node.tpgt" #define NODE_STARTUP "node.startup" #define NODE_LEADING_LOGIN "node.leading_login" #define NODE_DISC_ADDR "node.discovery_address" #define NODE_DISC_PORT "node.discovery_port" #define NODE_DISC_TYPE "node.discovery_type" #define NODE_BOOT_LUN "node.boot_lun" /* session fields */ #define SESSION_INIT_CMDSN "node.session.initial_cmdsn" #define SESSION_INIT_LOGIN_RETRY "node.session.initial_login_retry_max" #define SESSION_CMDS_MAX "node.session.cmds_max" #define SESSION_XMIT_THREAD_PRIORITY "node.session.xmit_thread_priority" #define SESSION_QDEPTH "node.session.queue_depth" #define SESSION_NR_SESSIONS "node.session.nr_sessions" #define SESSION_AUTH_METHOD "node.session.auth.authmethod" #define SESSION_USERNAME "node.session.auth.username" #define SESSION_PASSWORD "node.session.auth.password" #define SESSION_PASSWORD_LEN "node.session.auth.password_length" #define SESSION_USERNAME_IN "node.session.auth.username_in" #define SESSION_PASSWORD_IN "node.session.auth.password_in" #define SESSION_PASSWORD_IN_LEN "node.session.auth.password_in_length" #define SESSION_REPLACEMENT_TMO "node.session.timeo.replacement_timeout" #define SESSION_ABORT_TMO "node.session.err_timeo.abort_timeout" #define SESSION_LU_RESET_TMO "node.session.err_timeo.lu_reset_timeout" #define SESSION_TGT_RESET_TMO "node.session.err_timeo.tgt_reset_timeout" #define SESSION_HOST_RESET_TMO "node.session.err_timeo.host_reset_timeout" #define SESSION_FAST_ABORT "node.session.iscsi.FastAbort" #define SESSION_INITIAL_R2T "node.session.iscsi.InitialR2T" #define SESSION_IMM_DATA "node.session.iscsi.ImmediateData" #define SESSION_FIRST_BURST "node.session.iscsi.FirstBurstLength" #define SESSION_MAX_BURST "node.session.iscsi.MaxBurstLength" #define SESSION_DEF_TIME2RETAIN "node.session.iscsi.DefaultTime2Retain" #define SESSION_DEF_TIME2WAIT "node.session.iscsi.DefaultTime2Wait" #define SESSION_MAX_CONNS "node.session.iscsi.MaxConnections" #define SESSION_MAX_R2T "node.session.iscsi.MaxOutstandingR2T" #define SESSION_ERL "node.session.iscsi.ERL" /* connections fields */ #define CONN_ADDR "node.conn[%d].address" #define CONN_PORT "node.conn[%d].port" #define CONN_STARTUP "node.conn[%d].startup" #define CONN_WINDOW_SIZE "node.conn[%d].tcp.window_size" #define CONN_SERVICE_TYPE "node.conn[%d].tcp.type_of_service" #define CONN_LOGOUT_TMO "node.conn[%d].timeo.logout_timeout" #define CONN_LOGIN_TMO "node.conn[%d].timeo.login_timeout" #define CONN_AUTH_TMO "node.conn[%d].timeo.auth_timeout" #define CONN_NOP_INT "node.conn[%d].timeo.noop_out_interval" #define CONN_NOP_TMO "node.conn[%d].timeo.noop_out_timeout" #define CONN_MAX_XMIT_DLEN "node.conn[%d].iscsi.MaxXmitDataSegmentLength" #define CONN_MAX_RECV_DLEN "node.conn[%d].iscsi.MaxRecvDataSegmentLength" #define CONN_HDR_DIGEST "node.conn[%d].iscsi.HeaderDigest" #define CONN_DATA_DIGEST "node.conn[%d].iscsi.DataDigest" #define CONN_IFMARKER "node.conn[%d].iscsi.IFMarker" #define CONN_OFMARKER "node.conn[%d].iscsi.OFMarker" /* iface fields */ #define IFACE_HWADDR "iface.hwaddress" #define IFACE_ISCSINAME "iface.iscsi_ifacename" #define IFACE_NETNAME "iface.net_ifacename" #define IFACE_TRANSPORTNAME "iface.transport_name" #define IFACE_INAME "iface.initiatorname" #define IFACE_ISID "iface.isid" #define IFACE_BOOT_PROTO "iface.bootproto" #define IFACE_IPADDR "iface.ipaddress" #define IFACE_SUBNET_MASK "iface.subnet_mask" #define IFACE_GATEWAY "iface.gateway" #define IFACE_PRIMARY_DNS "iface.primary_dns" #define IFACE_SEC_DNS "iface.secondary_dns" #define IFACE_VLAN_ID "iface.vlan_id" #define IFACE_VLAN_PRIORITY "iface.vlan_priority" #define IFACE_VLAN_STATE "iface.vlan_state" #define IFACE_LINKLOCAL "iface.ipv6_linklocal" #define IFACE_ROUTER "iface.ipv6_router" #define IFACE_IPV6_AUTOCFG "iface.ipv6_autocfg" #define IFACE_LINKLOCAL_AUTOCFG "iface.linklocal_autocfg" #define IFACE_ROUTER_AUTOCFG "iface.router_autocfg" #define IFACE_STATE "iface.state" #define IFACE_NUM "iface.iface_num" #define IFACE_MTU "iface.mtu" #define IFACE_PORT "iface.port" /* discovery fields */ #define DISC_STARTUP "discovery.startup" #define DISC_TYPE "discovery.type" /* sendtargets */ #define DISC_ST_ADDR "discovery.sendtargets.address" #define DISC_ST_PORT "discovery.sendtargets.port" #define DISC_ST_AUTH_METHOD "discovery.sendtargets.auth.authmethod" #define DISC_ST_USERNAME "discovery.sendtargets.auth.username" #define DISC_ST_PASSWORD "discovery.sendtargets.auth.password" #define DISC_ST_PASSWORD_LEN "discovery.sendtargets.auth.password_length" #define DISC_ST_USERNAME_IN "discovery.sendtargets.auth.username_in" #define DISC_ST_PASSWORD_IN "discovery.sendtargets.auth.password_in" #define DISC_ST_PASSWORD_IN_LEN "discovery.sendtargets.auth.password_in_length" #define DISC_ST_LOGIN_TMO "discovery.sendtargets.timeo.login_timeout" #define DISC_ST_REOPEN_MAX "discovery.sendtargets.reopen_max" #define DISC_ST_DISC_DAEMON_POLL_INVAL "discovery.sendtargets.discoveryd_poll_inval" #define DISC_ST_USE_DISC_DAEMON "discovery.sendtargets.use_discoveryd" #define DISC_ST_AUTH_TMO "discovery.sendtargets.timeo.auth_timeout" #define DISC_ST_ACTIVE_TMO "discovery.sendtargets.timeo.active_timeout" #define DISC_ST_MAX_RECV_DLEN "discovery.sendtargets.iscsi.MaxRecvDataSegmentLength" #define DISC_ISNS_DISC_DAEMON_POLL_INVAL "discovery.isns.discoveryd_poll_inval" #define DISC_ISNS_USE_DISC_DAEMON "discovery.isns.use_discoveryd" #define DISC_ISNS_ADDR "discovery.sendtargets.address" #define DISC_ISNS_PORT "discovery.sendtargets.port" /* host auth fields */ #define HOST_AUTH_INDEX "host.auth.tbl_idx" #define HOST_AUTH_METHOD "host.auth.authmethod" #define HOST_AUTH_USERNAME "host.auth.username" #define HOST_AUTH_PASSWORD "host.auth.password" #define HOST_AUTH_PASSWORD_LEN "host.auth.password_length" #define HOST_AUTH_USERNAME_IN "host.auth.username_in" #define HOST_AUTH_PASSWORD_IN "host.auth.password_in" #define HOST_AUTH_PASSWORD_IN_LEN "host.auth.password_in_length" #endif open-iscsi-2.0.873/usr/iface.c000066400000000000000000001304571175631155400160120ustar00rootroot00000000000000/* * iSCSI iface helpers * * Copyright (C) 2008 Mike Christie * Copyright (C) 2008 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "list.h" #include "iscsi_sysfs.h" #include "iscsi_settings.h" #include "config.h" #include "transport.h" #include "idbm.h" #include "iface.h" #include "session_info.h" #include "host.h" #include "fw_context.h" #include "sysdeps.h" #include "iscsi_err.h" #include "iscsi_netlink.h" /* * Default ifaces for use with transports that do not bind to hardware * by defaults (transports that let the interconnect layer to the routing * by defaults). */ /* * iSCSI over TCP/IP */ static struct iface_rec iface_default = { .name = "default", .transport_name = "tcp", }; /* * iSER */ static struct iface_rec iface_iser = { .name = "iser", .transport_name = "iser", }; static struct iface_rec *default_ifaces[] = { &iface_default, &iface_iser, NULL, }; static struct iface_rec *iface_match_default(struct iface_rec *iface) { struct iface_rec *def_iface; int i = 0; while ((def_iface = default_ifaces[i++])) { if (!strcmp(iface->name, def_iface->name)) return def_iface; } return NULL; } static void iface_init(struct iface_rec *iface) { if (!strlen(iface->name)) sprintf(iface->name, DEFAULT_IFACENAME); } /* * default is to use tcp through whatever the network layer * selects for us with the /etc/iscsi/initiatorname.iscsi iname. */ void iface_setup_defaults(struct iface_rec *iface) { sprintf(iface->transport_name, DEFAULT_TRANSPORT); iface_init(iface); } struct iface_rec *iface_alloc(char *ifname, int *err) { struct iface_rec *iface; if (!strlen(ifname) || strlen(ifname) + 1 > ISCSI_MAX_IFACE_LEN) { *err = ISCSI_ERR_INVAL; return NULL; } iface = calloc(1, sizeof(*iface)); if (!iface) { *err = ISCSI_ERR_NOMEM; return NULL; } strlcpy(iface->name, ifname, ISCSI_MAX_IFACE_LEN); INIT_LIST_HEAD(&iface->list); return iface; } static int __iface_conf_read(struct iface_rec *iface) { char *iface_conf; recinfo_t *info; FILE *f; int rc = 0; iface_conf = calloc(1, PATH_MAX); if (!iface_conf) return ISCSI_ERR_NOMEM; info = idbm_recinfo_alloc(MAX_KEYS); if (!info) { rc = ISCSI_ERR_NOMEM; goto free_conf; } snprintf(iface_conf, PATH_MAX, "%s/%s", IFACE_CONFIG_DIR, iface->name); log_debug(5, "looking for iface conf %s", iface_conf); f = fopen(iface_conf, "r"); if (!f) { /* * if someone passes in default but has not defined * a iface with default then we do it for them */ if (!strcmp(iface->name, DEFAULT_IFACENAME)) { iface_setup_defaults(iface); rc = 0; } else rc = ISCSI_ERR_IDBM; goto free_info; } iface_init(iface); idbm_recinfo_iface(iface, info); idbm_recinfo_config(info, f); fclose(f); free_info: free(info); free_conf: free(iface_conf); return rc; } int iface_conf_read(struct iface_rec *iface) { struct iface_rec *def_iface; int rc, retry = 0; def_iface = iface_match_default(iface); if (def_iface) { /* * older tools allowed default to have different * transport_names so we do not want to overwrite * it. */ if (!strcmp(def_iface->name, DEFAULT_IFACENAME)) { if (!strlen(iface->name)) strcpy(iface->name, def_iface->name); if (!strlen(iface->netdev)) strcpy(iface->netdev, def_iface->netdev); if (!strlen(iface->hwaddress)) strcpy(iface->hwaddress, def_iface->hwaddress); if (!strlen(iface->transport_name)) strcpy(iface->transport_name, def_iface->transport_name); if (!strlen(iface->iname)) strcpy(iface->iname, def_iface->iname); } else { iface_init(iface); iface_copy(iface, def_iface); } return 0; } retry_read: rc = idbm_lock(); if (rc) return rc; rc = __iface_conf_read(iface); idbm_unlock(); /* * cmd was run before running -m iface, so force def bindings * creation to see if that was the one requested */ if (retry < 1 && rc == ISCSI_ERR_IDBM) { iface_setup_host_bindings(); retry++; goto retry_read; } return rc; } int iface_conf_delete(struct iface_rec *iface) { struct iface_rec *def_iface; char *iface_conf; int rc = 0; def_iface = iface_match_default(iface); if (def_iface) { log_error("iface %s is a special interface and " "cannot be deleted.\n", iface->name); return ISCSI_ERR_INVAL; } iface_conf = calloc(1, PATH_MAX); if (!iface_conf) return ISCSI_ERR_NOMEM; sprintf(iface_conf, "%s/%s", IFACE_CONFIG_DIR, iface->name); rc = idbm_lock(); if (rc) goto free_conf; if (unlink(iface_conf)) rc = ISCSI_ERR_IDBM; idbm_unlock(); free_conf: free(iface_conf); return rc; } int iface_conf_write(struct iface_rec *iface) { struct iface_rec *def_iface; char *iface_conf; FILE *f; int rc = 0; def_iface = iface_match_default(iface); if (def_iface) { log_error("iface %s is a special interface and " "is not stored in %s.\n", iface->name, IFACE_CONFIG_DIR); return ISCSI_ERR_INVAL; } iface_conf = calloc(1, PATH_MAX); if (!iface_conf) return ISCSI_ERR_NOMEM; sprintf(iface_conf, "%s/%s", IFACE_CONFIG_DIR, iface->name); f = fopen(iface_conf, "w"); if (!f) { rc = ISCSI_ERR_IDBM; goto free_conf; } rc = idbm_lock(); if (rc) goto close_f; idbm_print(IDBM_PRINT_TYPE_IFACE, iface, 1, f); idbm_unlock(); close_f: fclose(f); free_conf: free(iface_conf); return rc; } int iface_conf_update(struct list_head *params, struct iface_rec *iface) { struct iface_rec *def_iface; recinfo_t *info; struct user_param *param; int rc = 0; def_iface = iface_match_default(iface); if (def_iface) { log_error("iface %s is a special interface and " "cannot be modified.\n", iface->name); return ISCSI_ERR_INVAL; } info = idbm_recinfo_alloc(MAX_KEYS); if (!info) return ISCSI_ERR_NOMEM; idbm_recinfo_iface(iface, info); list_for_each_entry(param, params, list) { rc = idbm_verify_param(info, param->name); if (rc) goto free_info; } list_for_each_entry(param, params, list) { rc = idbm_rec_update_param(info, param->name, param->value, 0); if (rc) goto free_info; } rc = iface_conf_write(iface); free_info: free(info); return rc; } #if 0 /* Unused */ static int iface_get_next_id(void) { struct stat statb; char *iface_conf; int i, rc = ENOSPC; iface_conf = calloc(1, PATH_MAX); if (!iface_conf) return ENOMEM; for (i = 0; i < INT_MAX; i++) { memset(iface_conf, 0, PATH_MAX); /* check len */ snprintf(iface_conf, PATH_MAX, "iface%d", i); if (strlen(iface_conf) > ISCSI_MAX_IFACE_LEN - 1) { log_error("iface namespace is full. Remove unused " "iface definitions from %s or send mail " "to open-iscsi@googlegroups.com to report " "the problem", IFACE_CONFIG_DIR); rc = ENOSPC; break; } memset(iface_conf, 0, PATH_MAX); snprintf(iface_conf, PATH_MAX, "%s/iface%d", IFACE_CONFIG_DIR, i); if (!stat(iface_conf, &statb)) continue; if (errno == ENOENT) { rc = i; break; } } free(iface_conf); return rc; } #endif /* Unused */ struct iface_search { struct iface_rec *pattern; struct iface_rec *found; }; static int __iface_get_by_net_binding(void *data, struct iface_rec *iface) { struct iface_search *search = data; if (!strcmp(search->pattern->name, iface->name)) { iface_copy(search->found, iface); return 1; } if (iface_is_bound_by_hwaddr(search->pattern)) { if (!strcasecmp(iface->hwaddress, search->pattern->hwaddress)) { iface_copy(search->found, iface); return 1; } else return 0; } if (iface_is_bound_by_netdev(search->pattern)) { if (!strcmp(iface->netdev, search->pattern->netdev)) { iface_copy(search->found, iface); return 1; } else return 0; } /* if (iface_is_bound_by_ipaddr(search->pattern)) { if (!strcmp(iface->ipaddress, search->pattern->ipaddress)) { iface_copy(search->found, iface); return 1; } else return 0; } */ return 0; } /* * Before 2.0.870, we only could bind by netdeivce or hwaddress, * so we did a simple reverse lookup to go from sysfs info to * the iface name. After 2.0.870 we added a lot of options to the * iface binding so we added the ifacename to the kernel. * * This function is for older kernels that do not export the ifacename. * If the user was doing iscsi_tcp session binding we will find * the iface by matching net info. */ int iface_get_by_net_binding(struct iface_rec *pattern, struct iface_rec *out_rec) { int num_found = 0, rc; struct iface_search search; if (!iface_is_bound_by_hwaddr(pattern) && !iface_is_bound_by_netdev(pattern)) { sprintf(out_rec->name, DEFAULT_IFACENAME); return 0; } search.pattern = pattern; search.found = out_rec; rc = iface_for_each_iface(&search, 0, &num_found, __iface_get_by_net_binding); if (rc == 1) return 0; return ISCSI_ERR_NO_OBJS_FOUND; } int iface_get_iptype(struct iface_rec *iface) { /* address might not be set if user config with another tool */ if (!strlen(iface->ipaddress) || !strcmp(UNKNOWN_VALUE, iface->ipaddress)) { /* try to figure out by name */ if (strstr(iface->name, "ipv4")) return ISCSI_IFACE_TYPE_IPV4; else return ISCSI_IFACE_TYPE_IPV6; } else { if (strcmp(iface->bootproto, "dhcp") && !strstr(iface->ipaddress, ".")) return ISCSI_IFACE_TYPE_IPV6; else return ISCSI_IFACE_TYPE_IPV4; } } static int iface_setup_binding_from_kern_iface(void *data, struct iface_rec *kern_iface) { struct host_info *hinfo = data; struct iface_rec iface; char iface_path[PATH_MAX]; if (!strlen(hinfo->iface.hwaddress)) { log_error("Invalid offload iSCSI host %u. Missing " "hwaddress. Try upgrading %s driver.\n", hinfo->host_no, hinfo->iface.transport_name); return 0; } memset(&iface, 0, sizeof(struct iface_rec)); strcpy(iface.hwaddress, hinfo->iface.hwaddress); strcpy(iface.transport_name, hinfo->iface.transport_name); if (kern_iface) { iface.iface_num = kern_iface->iface_num; snprintf(iface.name, sizeof(iface.name), "%s.%s.%s.%u", kern_iface->transport_name, kern_iface->hwaddress, iface_get_iptype(kern_iface) == ISCSI_IFACE_TYPE_IPV4 ? "ipv4" : "ipv6", kern_iface->iface_num); } else { snprintf(iface.name, sizeof(iface.name), "%s.%s", hinfo->iface.transport_name, hinfo->iface.hwaddress); } memset(iface_path, 0, sizeof(iface_path)); snprintf(iface_path, PATH_MAX, "%s/%s", IFACE_CONFIG_DIR, iface.name); if (access(iface_path, F_OK) != 0) { /* not found so create it */ if (iface_conf_write(&iface)) { log_error("Could not create default iface conf %s.", iface.name); /* fall through - will not be persistent */ } } return 0; } static int __iface_setup_host_bindings(void *data, struct host_info *hinfo) { struct iface_rec *def_iface; struct iscsi_transport *t; int i = 0, nr_found; t = iscsi_sysfs_get_transport_by_hba(hinfo->host_no); if (!t) return 0; /* do not setup binding for hosts using non offload drivers */ while ((def_iface = default_ifaces[i++])) { if (!strcmp(t->name, def_iface->transport_name)) return 0; } nr_found = 0; iscsi_sysfs_for_each_iface_on_host(hinfo, hinfo->host_no, &nr_found, iface_setup_binding_from_kern_iface); if (!nr_found) iface_setup_binding_from_kern_iface(hinfo, NULL); return 0; } /* * Create a default iface for offload cards. We assume that we will * be able identify each host by MAC. */ void iface_setup_host_bindings(void) { int nr_found = 0; if (idbm_lock()) return; if (access(IFACE_CONFIG_DIR, F_OK) != 0) { if (mkdir(IFACE_CONFIG_DIR, 0660) != 0) { log_error("Could not make %s. HW/OFFLOAD iscsi " "may not be supported", IFACE_CONFIG_DIR); idbm_unlock(); return; } } idbm_unlock(); transport_probe_for_offload(); if (iscsi_sysfs_for_each_host(NULL, &nr_found, __iface_setup_host_bindings)) log_error("Could not scan scsi hosts. HW/OFFLOAD iscsi " "operations may not be supported, or please " "see README for instructions on setting up ifaces."); } void iface_copy(struct iface_rec *dst, struct iface_rec *src) { if (strlen(src->name)) strcpy(dst->name, src->name); if (src->iface_num) dst->iface_num = src->iface_num; if (strlen(src->netdev)) strcpy(dst->netdev, src->netdev); if (strlen(src->ipaddress)) strcpy(dst->ipaddress, src->ipaddress); if (strlen(src->subnet_mask)) strcpy(dst->subnet_mask, src->subnet_mask); if (strlen(src->gateway)) strcpy(dst->gateway, src->gateway); if (strlen(src->bootproto)) strcpy(dst->bootproto, src->bootproto); if (strlen(src->ipv6_linklocal)) strcpy(dst->ipv6_linklocal, src->ipv6_linklocal); if (strlen(src->ipv6_router)) strcpy(dst->ipv6_router, src->ipv6_router); if (strlen(src->ipv6_autocfg)) strcpy(dst->ipv6_autocfg, src->ipv6_autocfg); if (strlen(src->linklocal_autocfg)) strcpy(dst->linklocal_autocfg, src->linklocal_autocfg); if (strlen(src->router_autocfg)) strcpy(dst->router_autocfg, src->router_autocfg); if (src->vlan_id) dst->vlan_id = src->vlan_id; if (src->vlan_priority) dst->vlan_priority = src->vlan_priority; if (strlen(src->vlan_state)) strcpy(dst->vlan_state, src->vlan_state); if (strlen(src->state)) strcpy(dst->state, src->state); if (src->mtu) dst->mtu = src->mtu; if (src->port) dst->port = src->port; if (strlen(src->hwaddress)) strcpy(dst->hwaddress, src->hwaddress); if (strlen(src->transport_name)) strcpy(dst->transport_name, src->transport_name); if (strlen(src->iname)) strcpy(dst->iname, src->iname); } int iface_is_valid(struct iface_rec *iface) { if (!iface) return 0; if (!strlen(iface->name)) return 0; if (!strlen(iface->transport_name)) return 0; if (iface_is_bound_by_hwaddr(iface)) return 1; if (iface_is_bound_by_netdev(iface)) return 1; // if (iface_is_bound_by_ipaddr(iface)) // return 1; /* bound by transport name */ return 1; } int iface_match(struct iface_rec *pattern, struct iface_rec *iface) { if (!pattern || !iface) return 1; if (!strlen(pattern->name)) return 1; if (!strcmp(pattern->name, iface->name)) { if (!strcmp(pattern->name, DEFAULT_IFACENAME)) return 1; /* * For default we allow the same name, but different * transports. */ if (!strlen(pattern->transport_name)) return 1; if (!strcmp(pattern->transport_name, iface->transport_name)) return 1; /* fall through */ } return 0; } int iface_is_bound_by_hwaddr(struct iface_rec *iface) { if (iface && strlen(iface->hwaddress) && strcmp(iface->hwaddress, DEFAULT_HWADDRESS)) return 1; return 0; } int iface_is_bound_by_netdev(struct iface_rec *iface) { if (iface && strlen(iface->netdev) && strcmp(iface->netdev, DEFAULT_NETDEV)) return 1; return 0; } int iface_is_bound_by_ipaddr(struct iface_rec *iface) { if (iface && strlen(iface->ipaddress) && strcmp(iface->ipaddress, DEFAULT_IPADDRESS)) return 1; return 0; } void iface_print(struct iface_rec *iface, char *prefix) { if (strlen(iface->name)) printf("%sIface Name: %s\n", prefix, iface->name); else printf("%sIface Name: %s\n", prefix, UNKNOWN_VALUE); if (strlen(iface->transport_name)) printf("%sIface Transport: %s\n", prefix, iface->transport_name); else printf("%sIface Transport: %s\n", prefix, UNKNOWN_VALUE); if (strlen(iface->iname)) printf("%sIface Initiatorname: %s\n", prefix, iface->iname); else printf("%sIface Initiatorname: %s\n", prefix, UNKNOWN_VALUE); if (!strlen(iface->ipaddress)) printf("%sIface IPaddress: %s\n", prefix, UNKNOWN_VALUE); else if (strchr(iface->ipaddress, '.')) printf("%sIface IPaddress: %s\n", prefix, iface->ipaddress); else printf("%sIface IPaddress: [%s]\n", prefix, iface->ipaddress); if (strlen(iface->hwaddress)) printf("%sIface HWaddress: %s\n", prefix, iface->hwaddress); else printf("%sIface HWaddress: %s\n", prefix, UNKNOWN_VALUE); if (strlen(iface->netdev)) printf("%sIface Netdev: %s\n", prefix, iface->netdev); else printf("%sIface Netdev: %s\n", prefix, UNKNOWN_VALUE); } struct iface_print_node_data { struct node_rec *last_rec; struct iface_rec *match_iface; }; static int iface_print_nodes(void *data, node_rec_t *rec) { struct iface_print_node_data *print_data = data; if (!iface_match(print_data->match_iface, &rec->iface)) return -1; idbm_print_node_tree(print_data->last_rec, rec, "\t"); return 0; } /** * iface_print_tree - print out binding info * @iface: iface to print out * * Currently this looks like the iface conf print, because we only * have the binding info. When we store the iface specific node settings * in the iface record then it will look different. */ int iface_print_tree(void *data, struct iface_rec *iface) { struct node_rec last_rec; struct iface_print_node_data print_data; int num_found = 0; printf("Iface: %s\n", iface->name); memset(&last_rec, 0, sizeof(struct node_rec )); print_data.match_iface = iface; print_data.last_rec = &last_rec; idbm_for_each_rec(&num_found, &print_data, iface_print_nodes); return 0; } int iface_print_flat(void *data, struct iface_rec *iface) { printf("%s %s,%s,%s,%s,%s\n", strlen(iface->name) ? iface->name : UNKNOWN_VALUE, strlen(iface->transport_name) ? iface->transport_name : UNKNOWN_VALUE, strlen(iface->hwaddress) ? iface->hwaddress : UNKNOWN_VALUE, strlen(iface->ipaddress) ? iface->ipaddress : UNKNOWN_VALUE, strlen(iface->netdev) ? iface->netdev : UNKNOWN_VALUE, strlen(iface->iname) ? iface->iname : UNKNOWN_VALUE); return 0; } int iface_for_each_iface(void *data, int skip_def, int *nr_found, iface_op_fn *fn) { DIR *iface_dirfd; struct dirent *iface_dent; struct iface_rec *iface, *def_iface; int err = 0, i = 0; if (!skip_def) { while ((def_iface = default_ifaces[i++])) { iface = iface_alloc(def_iface->name, &err); if (!iface) { log_error("Could not add iface %s.", def_iface->name); continue; } iface_copy(iface, def_iface); err = fn(data, iface); free(iface); if (err) return err; (*nr_found)++; } } iface_dirfd = opendir(IFACE_CONFIG_DIR); if (!iface_dirfd) return errno; while ((iface_dent = readdir(iface_dirfd))) { if (!strcmp(iface_dent->d_name, ".") || !strcmp(iface_dent->d_name, "..")) continue; log_debug(5, "iface_for_each_iface found %s", iface_dent->d_name); iface = iface_alloc(iface_dent->d_name, &err); if (!iface || err) { if (err == ISCSI_ERR_INVAL) log_error("Invalid iface name %s. Must be " "from 1 to %d characters.", iface_dent->d_name, ISCSI_MAX_IFACE_LEN - 1); else log_error("Could not add iface %s.", iface_dent->d_name); continue; } err = idbm_lock(); if (err) { free(iface); continue; } err = __iface_conf_read(iface); idbm_unlock(); if (err) { log_error("Could not read def iface %s (err %d)", iface->name, err); free(iface); continue; } if (!iface_is_valid(iface)) { log_debug(5, "iface is not valid " "Iface settings " iface_fmt, iface_str(iface)); free(iface); continue; } err = fn(data, iface); free(iface); if (err) break; (*nr_found)++; } closedir(iface_dirfd); return err; } static int iface_link(void *data, struct iface_rec *iface) { struct list_head *ifaces = data; struct iface_rec *iface_copy; iface_copy = calloc(1, sizeof(*iface_copy)); if (!iface_copy) return ISCSI_ERR_NOMEM; memcpy(iface_copy, iface, sizeof(*iface_copy)); INIT_LIST_HEAD(&iface_copy->list); list_add_tail(&iface_copy->list, ifaces); return 0; } /** * iface_link_ifaces - link non default ifaces * @ifaces: list to add ifaces to * * This will return a list of the ifaces created by iscsiadm * or the user. It does not return the static default ones. */ void iface_link_ifaces(struct list_head *ifaces) { int nr_found = 0; iface_for_each_iface(ifaces, 1, &nr_found, iface_link); } /** * iface_setup_from_boot_context - setup iface from boot context info * @iface: iface t setup * @context: boot context info * * Returns 1 if setup for offload. */ int iface_setup_from_boot_context(struct iface_rec *iface, struct boot_context *context) { struct iscsi_transport *t = NULL; char transport_name[ISCSI_TRANSPORT_NAME_MAXLEN]; uint32_t hostno; if (strlen(context->initiatorname)) strlcpy(iface->iname, context->initiatorname, sizeof(iface->iname)); if (strlen(context->scsi_host_name)) { if (sscanf(context->scsi_host_name, "iscsi_boot%u", &hostno) != 1) { log_error("Could not parse %s's host no.", context->scsi_host_name); return 0; } } else if (strlen(context->iface)) { /* this ifdef is only temp until distros and firmwares are updated */ #ifdef OFFLOAD_BOOT_SUPPORTED memset(transport_name, 0, ISCSI_TRANSPORT_NAME_MAXLEN); /* make sure offload driver is loaded */ if (!net_get_transport_name_from_netdev(context->iface, transport_name)) t = iscsi_sysfs_get_transport_by_name(transport_name); hostno = iscsi_sysfs_get_host_no_from_hwaddress(context->mac, &rc); if (rc) { /* * If the MAC in the boot info does not match a iscsi * host then the MAC must be for network card, so boot * is not going to be offloaded. */ log_debug(3, "Could not match %s to host\n", context->mac); return 0; } strlcpy(iface->netdev, context->iface, sizeof(iface->netdev)); #else return 0; #endif } else return 0; /* * set up for access through a offload card. */ if (!t) t = iscsi_sysfs_get_transport_by_hba(hostno); if (!t) { log_error("Could not get transport for host%u. " "Make sure the iSCSI driver is loaded.", hostno); return 0; } strcpy(iface->transport_name, t->name); memset(iface->name, 0, sizeof(iface->name)); snprintf(iface->name, sizeof(iface->name), "%s.%s", iface->transport_name, context->mac); strlcpy(iface->hwaddress, context->mac, sizeof(iface->hwaddress)); strlcpy(iface->ipaddress, context->ipaddr, sizeof(iface->ipaddress)); log_debug(1, "iface " iface_fmt "\n", iface_str(iface)); return 1; } /** * iface_create_ifaces_from_boot_contexts - create ifaces based on boot info * @ifaces: list to store ifaces in * @targets: list of targets to create ifaces from * * This function will create a iface struct based on the boot info * and it will create (or update if existing already) a iface rec in * the ifaces dir based on the info. */ int iface_create_ifaces_from_boot_contexts(struct list_head *ifaces, struct list_head *targets) { struct boot_context *context; struct iface_rec *iface, *tmp_iface; int rc = 0; list_for_each_entry(context, targets, list) { rc = 0; /* use dummy name. If valid it will get overwritten below */ iface = iface_alloc(DEFAULT_IFACENAME, &rc); if (!iface) { log_error("Could not setup iface %s for boot\n", context->iface); goto fail; } if (!iface_setup_from_boot_context(iface, context)) { /* no offload so forget it */ free(iface); continue; } rc = iface_conf_write(iface); if (rc) { log_error("Could not setup default iface conf " "for %s.", iface->name); free(iface); goto fail; } list_add_tail(&iface->list, ifaces); } return 0; fail: list_for_each_entry_safe(iface, tmp_iface, ifaces, list) { list_del(&iface->list); free(iface); } return rc; } struct iface_param_count { struct iface_rec *primary; int count; }; /** * __iface_get_param_count - Gets netconfig parameter count for given iface * @data: iface_param_count structure * @iface: iface to setup */ static int __iface_get_param_count(void *data, struct iface_rec *iface) { struct iface_param_count *iface_params = data; int iptype = ISCSI_IFACE_TYPE_IPV4; int count = 0; if (strcmp(iface_params->primary->hwaddress, iface->hwaddress)) return 0; iptype = iface_get_iptype(iface); if (iptype == ISCSI_IFACE_TYPE_IPV4) { if (strcmp(iface->state, "disable")) { if (strstr(iface->bootproto, "dhcp")) /* DHCP enabled */ count++; else { /* DHCP disabled */ count++; if (strstr(iface->ipaddress, ".")) { /* User configured IPv4 Address */ count++; if (strstr(iface->subnet_mask, ".")) /* User configured Subnet */ count++; if (strstr(iface->gateway, ".")) /* User configured Gateway */ count++; } else /* * IPv4 Address not valid, decrement * count of DHCP */ count--; } /* * If IPv4 configuration in iface file is valid, * enable state and other parameters (if any) */ if (count) { /* iface state */ count++; if (strcmp(iface->vlan_state, "disable")) { /* vlan_state enabled */ count++; if (iface->vlan_id) /* For vlan value */ count++; } else /* vlan_state disabled */ count++; if (iface->mtu) count++; if (iface->port) count++; } } else /* IPv4 is disabled, iface state */ count++; } else if (iptype == ISCSI_IFACE_TYPE_IPV6) { if (strcmp(iface->state, "disable")) { /* IPv6 Address */ if (strstr(iface->ipv6_autocfg, "nd") || strstr(iface->ipv6_autocfg, "dhcpv6")) /* Autocfg enabled */ count++; else { /* Autocfg disabled */ count++; if (strstr(iface->ipaddress, ":")) /* User configured IPv6 Address */ count++; else /* * IPv6 Address not valid, decrement * count of IPv6 Autocfg */ count--; } /* IPv6 LinkLocal Address */ if (strstr(iface->linklocal_autocfg, "auto")) /* Autocfg enabled */ count++; else { /* Autocfg disabled */ count++; if (strstr(iface->ipv6_linklocal, ":")) /* User configured LinkLocal Address */ count++; else /* * LinkLocal Address not valid, * decrement count of LinkLocal Autocfg */ count--; } /* IPv6 Router Address */ if (strstr(iface->router_autocfg, "auto")) /* Autocfg enabled */ count++; else { /* Autocfg disabled */ count++; if (strstr(iface->ipv6_router, ":")) /* User configured Router Address */ count++; else /* * Router Address not valid, * decrement count of Router Autocfg */ count--; } /* * If IPv6 configuration in iface file is valid, * enable state and other parameters (if any) */ if (count) { /* iface state */ count++; if (strcmp(iface->vlan_state, "disable")) { /* vlan_state enabled */ count++; if (iface->vlan_id) /* For vlan value */ count++; } else /* vlan_state disabled */ count++; if (iface->mtu) count++; if (iface->port) count++; } } else /* IPv6 is disabled, iface state */ count++; } iface_params->count += count; return 0; } /** * iface_get_param_count - Gets netconfig parameter count from iface * @iface: iface to setup * @iface_all: Flag for number of ifaces to traverse (1 for all) * * Returns netconfig parameter count. */ int iface_get_param_count(struct iface_rec *iface, int iface_all) { int num_found = 0, rc; struct iface_param_count iface_params; log_debug(8, "In iface_get_param_count\n"); iface_params.primary = iface; iface_params.count = 0; if (iface_all) rc = iface_for_each_iface(&iface_params, 0, &num_found, __iface_get_param_count); else rc = __iface_get_param_count(&iface_params, iface); log_debug(8, "iface_get_param_count: rc = %d, count = %d\n", rc, iface_params.count); return iface_params.count; } /* IPv4/IPv6 Port: 3260 or User defined */ static int iface_fill_port(struct iovec *iov, struct iface_rec *iface, uint32_t iface_type) { int len; struct iscsi_iface_param_info *net_param; uint16_t port = 3260; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + sizeof(port); iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_PORT, len); if (!iov->iov_base) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_PORT; net_param->iface_type = iface_type; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 2; if (iface->port) port = iface->port; memcpy(net_param->value, &port, net_param->len); return 0; } static int iface_fill_mtu(struct iovec *iov, struct iface_rec *iface, uint32_t iface_type) { int len; struct iscsi_iface_param_info *net_param; uint16_t mtu = 0; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 2; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_MTU, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_MTU; net_param->iface_type = iface_type; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 2; mtu = iface->mtu; memcpy(net_param->value, &mtu, net_param->len); return 0; } /* IPv4/IPv6 VLAN_ID: decimal value <= 4095 */ static int iface_fill_vlan_id(struct iovec *iov, struct iface_rec *iface, uint32_t iface_type) { int len; struct iscsi_iface_param_info *net_param; uint16_t vlan = 0; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 2; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_VLAN_TAG, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_VLAN_TAG; net_param->iface_type = iface_type; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 2; if (iface->vlan_id <= ISCSI_MAX_VLAN_ID && iface->vlan_priority <= ISCSI_MAX_VLAN_PRIORITY) /* * Bit 15-13: User Priority of VLAN * Bit 11-00: VLAN ID */ vlan = (iface->vlan_priority << 13) | (iface->vlan_id & ISCSI_MAX_VLAN_ID); memcpy(net_param->value, &vlan, net_param->len); return 0; } /* IPv4/IPv6 VLAN state: disable/enable */ static int iface_fill_vlan_state(struct iovec *iov, struct iface_rec *iface, uint32_t iface_type) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_VLAN_ENABLED, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_VLAN_ENABLED; net_param->iface_type = iface_type; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (strcmp(iface->vlan_state, "disable") && iface->vlan_id) net_param->value[0] = ISCSI_VLAN_ENABLE; else /* Assume disabled */ net_param->value[0] = ISCSI_VLAN_DISABLE; return 0; } /* IPv4/IPv6 Network state: disable/enable */ static int iface_fill_net_state(struct iovec *iov, struct iface_rec *iface, uint32_t iface_type) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_IFACE_ENABLE, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_IFACE_ENABLE; net_param->iface_type = iface_type; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (!strcmp(iface->state, "disable")) net_param->value[0] = ISCSI_IFACE_DISABLE; else /* Assume enabled */ net_param->value[0] = ISCSI_IFACE_ENABLE; return 0; } /* IPv4 Bootproto: DHCP/static */ static int iface_fill_net_bootproto(struct iovec *iov, struct iface_rec *iface) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_IPV4_BOOTPROTO, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_IPV4_BOOTPROTO; net_param->iface_type = ISCSI_IFACE_TYPE_IPV4; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (!strcmp(iface->bootproto, "dhcp")) net_param->value[0] = ISCSI_BOOTPROTO_DHCP; else net_param->value[0] = ISCSI_BOOTPROTO_STATIC; return 0; } /* IPv6 IPAddress Autocfg: nd/dhcpv6/disable */ static int iface_fill_net_autocfg(struct iovec *iov, struct iface_rec *iface) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_IPV6_ADDR_AUTOCFG; net_param->iface_type = ISCSI_IFACE_TYPE_IPV6; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (!strcmp(iface->ipv6_autocfg, "nd")) net_param->value[0] = ISCSI_IPV6_AUTOCFG_ND_ENABLE; else if (!strcmp(iface->ipv6_autocfg, "dhcpv6")) net_param->value[0] = ISCSI_IPV6_AUTOCFG_DHCPV6_ENABLE; else net_param->value[0] = ISCSI_IPV6_AUTOCFG_DISABLE; return 0; } /* IPv6 LinkLocal Autocfg: enable/disable */ static int iface_fill_linklocal_autocfg(struct iovec *iov, struct iface_rec *iface) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_IPV6_LINKLOCAL_AUTOCFG; net_param->iface_type = ISCSI_IFACE_TYPE_IPV6; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (strstr(iface->linklocal_autocfg, "auto")) net_param->value[0] = ISCSI_IPV6_LINKLOCAL_AUTOCFG_ENABLE; else net_param->value[0] = ISCSI_IPV6_LINKLOCAL_AUTOCFG_DISABLE; return 0; } /* IPv6 Router Autocfg: enable/disable */ static int iface_fill_router_autocfg(struct iovec *iov, struct iface_rec *iface) { int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 1; iov->iov_base = iscsi_nla_alloc(ISCSI_NET_PARAM_IPV6_ROUTER_AUTOCFG, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = ISCSI_NET_PARAM_IPV6_ROUTER_AUTOCFG; net_param->iface_type = ISCSI_IFACE_TYPE_IPV6; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 1; if (strstr(iface->router_autocfg, "auto")) net_param->value[0] = ISCSI_IPV6_ROUTER_AUTOCFG_ENABLE; else net_param->value[0] = ISCSI_IPV6_ROUTER_AUTOCFG_DISABLE; return 0; } /* IPv4 IPAddress/Subnet Mask/Gateway: 4 bytes */ static int iface_fill_net_ipv4_addr(struct iovec *iov, struct iface_rec *iface, uint32_t param) { int rc = 1; int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 4; iov->iov_base = iscsi_nla_alloc(param, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = param; net_param->iface_type = ISCSI_IFACE_TYPE_IPV4; net_param->iface_num = iface->iface_num; net_param->len = 4; net_param->param_type = ISCSI_NET_PARAM; switch (param) { case ISCSI_NET_PARAM_IPV4_ADDR: rc = inet_pton(AF_INET, iface->ipaddress, net_param->value); if (rc <= 0) goto free; break; case ISCSI_NET_PARAM_IPV4_SUBNET: rc = inet_pton(AF_INET, iface->subnet_mask, net_param->value); if (rc <= 0) goto free; break; case ISCSI_NET_PARAM_IPV4_GW: rc = inet_pton(AF_INET, iface->gateway, net_param->value); if (rc <= 0) goto free; break; default: goto free; } /* validate */ if (!net_param->value[0] && !net_param->value[1] && !net_param->value[2] && !net_param->value[3]) goto free; return 0; free: free(iov->iov_base); iov->iov_base = NULL; iov->iov_len = 0; return 1; } /* IPv6 IPAddress/LinkLocal/Router: 16 bytes */ static int iface_fill_net_ipv6_addr(struct iovec *iov, struct iface_rec *iface, uint32_t param) { int rc; int len; struct iscsi_iface_param_info *net_param; struct nlattr *attr; len = sizeof(struct iscsi_iface_param_info) + 16; iov->iov_base = iscsi_nla_alloc(param, len); if (!(iov->iov_base)) return 1; attr = iov->iov_base; iov->iov_len = NLA_ALIGN(attr->nla_len); net_param = (struct iscsi_iface_param_info *)ISCSI_NLA_DATA(attr); net_param->param = param; net_param->iface_type = ISCSI_IFACE_TYPE_IPV6; net_param->iface_num = iface->iface_num; net_param->param_type = ISCSI_NET_PARAM; net_param->len = 16; switch (param) { case ISCSI_NET_PARAM_IPV6_ADDR: rc = inet_pton(AF_INET6, iface->ipaddress, net_param->value); if (rc <= 0) goto free; break; case ISCSI_NET_PARAM_IPV6_LINKLOCAL: rc = inet_pton(AF_INET6, iface->ipv6_linklocal, net_param->value); if (rc <= 0) goto free; break; case ISCSI_NET_PARAM_IPV6_ROUTER: rc = inet_pton(AF_INET6, iface->ipv6_router, net_param->value); if (rc <= 0) goto free; break; default: goto free; } return 0; free: free(iov->iov_base); iov->iov_base = NULL; iov->iov_len = 0; return 1; } struct iface_net_config { struct iface_rec *primary; struct iovec *iovs; int count; }; static int __iface_build_net_config(void *data, struct iface_rec *iface) { struct iface_net_config *net_config = data; struct iovec *iov; int iptype = ISCSI_IFACE_TYPE_IPV4; int count = 0; if (strcmp(net_config->primary->hwaddress, iface->hwaddress)) return 0; /* start at 2, because 0 is for nlmsghdr and 1 for event */ iov = net_config->iovs + 2; iptype = iface_get_iptype(iface); if (iptype == ISCSI_IFACE_TYPE_IPV4) { if (!strcmp(iface->state, "disable")) { if (!iface_fill_net_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } return 0; } if (strstr(iface->bootproto, "dhcp")) { if (!iface_fill_net_bootproto(&iov[net_config->count], iface)) { net_config->count++; count++; } } else if (strstr(iface->ipaddress, ".")) { if (!iface_fill_net_bootproto(&iov[net_config->count], iface)) { net_config->count++; count++; } if (!iface_fill_net_ipv4_addr(&iov[net_config->count], iface, ISCSI_NET_PARAM_IPV4_ADDR)) { net_config->count++; count++; } if (strstr(iface->subnet_mask, ".")) { if (!iface_fill_net_ipv4_addr( &iov[net_config->count], iface, ISCSI_NET_PARAM_IPV4_SUBNET)) { net_config->count++; count++; } } if (strstr(iface->gateway, ".")) { if (!iface_fill_net_ipv4_addr( &iov[net_config->count], iface, ISCSI_NET_PARAM_IPV4_GW)) { net_config->count++; count++; } } } /* * If IPv4 configuration in iface file is valid, * fill state and other parameters (if any) */ if (count) { if (!iface_fill_net_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } if (!iface_fill_vlan_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } if (strcmp(iface->vlan_state, "disable") && iface->vlan_id) { if (!iface_fill_vlan_id(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } } if (iface->mtu) { if (!iface_fill_mtu(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } } if (iface->port) { if (!iface_fill_port(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV4)) { net_config->count++; count++; } } } } else if (iptype == ISCSI_IFACE_TYPE_IPV6) { if (!strcmp(iface->state, "disable")) { if (!iface_fill_net_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } return 0; } /* For IPv6 Address */ if (strstr(iface->ipv6_autocfg, "nd") || strstr(iface->ipv6_autocfg, "dhcpv6")) { if (!iface_fill_net_autocfg(&iov[net_config->count], iface)) { net_config->count++; count++; } } else if (strstr(iface->ipaddress, ":")) { if (!iface_fill_net_autocfg(&iov[net_config->count], iface)) { net_config->count++; count++; } /* User provided IPv6 Address */ if (!iface_fill_net_ipv6_addr(&iov[net_config->count], iface, ISCSI_NET_PARAM_IPV6_ADDR)) { net_config->count++; count++; } } /* For LinkLocal Address */ if (strstr(iface->linklocal_autocfg, "auto")) { if (!iface_fill_linklocal_autocfg( &iov[net_config->count], iface)) { net_config->count++; count++; } } else if (strstr(iface->ipv6_linklocal, ":")) { if (!iface_fill_linklocal_autocfg( &iov[net_config->count], iface)) { net_config->count++; count++; } /* User provided Link Local Address */ if (!iface_fill_net_ipv6_addr(&iov[net_config->count], iface, ISCSI_NET_PARAM_IPV6_LINKLOCAL)) { net_config->count++; count++; } } /* For Router Address */ if (strstr(iface->router_autocfg, "auto")) { if (!iface_fill_router_autocfg(&iov[net_config->count], iface)) { net_config->count++; count++; } } else if (strstr(iface->ipv6_router, ":")) { if (!iface_fill_router_autocfg(&iov[net_config->count], iface)) { net_config->count++; count++; } /* User provided Router Address */ if (!iface_fill_net_ipv6_addr(&iov[net_config->count], iface, ISCSI_NET_PARAM_IPV6_ROUTER)) { net_config->count++; count++; } } /* * If IPv6 configuration in iface file is valid, * fill state and other parameters */ if (count) { if (!iface_fill_net_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } if (!iface_fill_vlan_state(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } if (strcmp(iface->vlan_state, "disable") && iface->vlan_id) { if (!iface_fill_vlan_id(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } } if (iface->mtu) { if (!iface_fill_mtu(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } } if (iface->port) { if (!iface_fill_port(&iov[net_config->count], iface, ISCSI_IFACE_TYPE_IPV6)) { net_config->count++; count++; } } } } return 0; } /** * iface_build_net_config - Setup neconfig parameter buffers * @iface: iface to setup * @iface_all: Flag for number of ifaces to traverse (1 for all) * @iovs: iovec buffer for netconfig parameters * * Returns total number of netconfig parameter buffers used. */ int iface_build_net_config(struct iface_rec *iface, int iface_all, struct iovec *iovs) { int num_found = 0, rc; struct iface_net_config net_config; log_debug(8, "In iface_build_net_config\n"); net_config.primary = iface; net_config.iovs = iovs; net_config.count = 0; if (iface_all) rc = iface_for_each_iface(&net_config, 0, &num_found, __iface_build_net_config); else rc = __iface_build_net_config(&net_config, iface); log_debug(8, "iface_build_net_config: rc = %d, count = %d\n", rc, net_config.count); return net_config.count; } open-iscsi-2.0.873/usr/iface.h000066400000000000000000000055061175631155400160130ustar00rootroot00000000000000/* * iSCSI iface helpers * * Copyright (C) 2008 Mike Christie * Copyright (C) 2008 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_IFACE_H #define ISCSI_IFACE_H #define IFACE_CONFIG_DIR ISCSI_CONFIG_ROOT"ifaces" struct iface_rec; struct list_head; struct boot_context; extern void iface_copy(struct iface_rec *dst, struct iface_rec *src); extern int iface_match(struct iface_rec *pattern, struct iface_rec *iface); extern struct iface_rec *iface_alloc(char *ifname, int *err); extern int iface_conf_read(struct iface_rec *iface); extern void iface_setup_defaults(struct iface_rec *iface); extern int iface_is_bound_by_hwaddr(struct iface_rec *iface); extern int iface_is_bound_by_netdev(struct iface_rec *iface); extern int iface_is_bound_by_ipaddr(struct iface_rec *iface); typedef int (iface_op_fn)(void *data, struct iface_rec *iface); extern int iface_for_each_iface(void *data, int skip_def, int *nr_found, iface_op_fn *fn); extern void iface_print(struct iface_rec *iface, char *prefix); extern int iface_print_flat(void *data, struct iface_rec *iface); extern int iface_print_tree(void *data, struct iface_rec *iface); extern void iface_setup_host_bindings(void); extern int iface_get_by_net_binding(struct iface_rec *pattern, struct iface_rec *out_rec); extern int iface_conf_update(struct list_head *params, struct iface_rec *iface); extern int iface_conf_write(struct iface_rec *iface); extern int iface_conf_delete(struct iface_rec *iface); extern int iface_is_valid(struct iface_rec *iface); extern void iface_link_ifaces(struct list_head *ifaces); extern int iface_setup_from_boot_context(struct iface_rec *iface, struct boot_context *context); extern int iface_create_ifaces_from_boot_contexts(struct list_head *ifaces, struct list_head *targets); extern int iface_get_param_count(struct iface_rec *iface_primary, int iface_all); extern int iface_build_net_config(struct iface_rec *iface_primary, int iface_all, struct iovec *iovs); extern int iface_get_iptype(struct iface_rec *iface); #define iface_fmt "[hw=%s,ip=%s,net_if=%s,iscsi_if=%s]" #define iface_str(_iface) \ (_iface)->hwaddress, (_iface)->ipaddress, (_iface)->netdev, \ (_iface)->name #endif open-iscsi-2.0.873/usr/initiator.c000066400000000000000000001543511175631155400167440ustar00rootroot00000000000000/* * iSCSI Session Management and Slow-path Control * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include "initiator.h" #include "transport.h" #include "iscsid.h" #include "iscsi_if.h" #include "mgmt_ipc.h" #include "event_poll.h" #include "iscsi_ipc.h" #include "idbm.h" #include "log.h" #include "iscsi_util.h" #include "scsi.h" #include "iscsi_sysfs.h" #include "iscsi_settings.h" #include "iface.h" #include "sysdeps.h" #include "iscsi_err.h" #include "kern_err_table.h" #define ISCSI_CONN_ERR_REOPEN_DELAY 3 #define ISCSI_INTERNAL_ERR_REOPEN_DELAY 5 #define PROC_DIR "/proc" static void iscsi_login_timedout(void *data); static int iscsi_sched_ev_context(struct iscsi_ev_context *ev_context, struct iscsi_conn *conn, unsigned long tmo, int event); static int iscsi_ev_context_alloc(iscsi_conn_t *conn) { int i; for (i = 0; i < CONTEXT_POOL_MAX; i++) { conn->context_pool[i] = calloc(1, sizeof(struct iscsi_ev_context) + ipc->ctldev_bufmax); if (!conn->context_pool[i]) { int j; for (j = 0; j < i; j++) free(conn->context_pool[j]); return ENOMEM; } conn->context_pool[i]->conn = conn; } return 0; } static void iscsi_ev_context_free(iscsi_conn_t *conn) { int i; for (i = 0; i < CONTEXT_POOL_MAX; i++) { if (!conn->context_pool[i]) continue; if (conn->context_pool[i]->allocated) /* missing flush on shutdown */ log_error("BUG: context_pool leak %p", conn->context_pool[i]); free(conn->context_pool[i]); } } static struct iscsi_ev_context * iscsi_ev_context_get(iscsi_conn_t *conn, int ev_size) { struct iscsi_ev_context *ev_context; int i; if (ev_size > ipc->ctldev_bufmax) return NULL; for (i = 0; i < CONTEXT_POOL_MAX; i++) { if (!conn->context_pool[i]) continue; if (!conn->context_pool[i]->allocated) { ev_context = conn->context_pool[i]; memset(&ev_context->actor, 0, sizeof(struct actor)); ev_context->allocated = 1; /* some callers abuse this pointer */ ev_context->data = (void *)ev_context + sizeof(struct iscsi_ev_context); log_debug(7, "get ev context %p", &ev_context->actor); return ev_context; } } return NULL; } static void iscsi_ev_context_put(struct iscsi_ev_context *ev_context) { log_debug(7, "put ev context %p", &ev_context->actor); ev_context->allocated = 0; } static void session_online_devs(int host_no, int sid) { iscsi_sysfs_for_each_device(NULL, host_no, sid, iscsi_sysfs_set_device_online); } static conn_login_status_e __login_response_status(iscsi_conn_t *conn, enum iscsi_login_status login_status) { switch (login_status) { case LOGIN_OK: /* check the status class and detail */ return CONN_LOGIN_SUCCESS; case LOGIN_REDIRECT: return CONN_LOGIN_IMM_REDIRECT_RETRY; case LOGIN_IO_ERROR: case LOGIN_REDIRECTION_FAILED: return CONN_LOGIN_RETRY; default: log_error("Login error (Login status %d) on conn %d", conn->id, login_status); break; } return CONN_LOGIN_FAILED; } static conn_login_status_e __check_iscsi_status_class(iscsi_session_t *session, int cid, uint8_t status_class, uint8_t status_detail) { iscsi_conn_t *conn = &session->conn[cid]; switch (status_class) { case ISCSI_STATUS_CLS_SUCCESS: return CONN_LOGIN_SUCCESS; case ISCSI_STATUS_CLS_REDIRECT: switch (status_detail) { case ISCSI_LOGIN_STATUS_TGT_MOVED_TEMP: return CONN_LOGIN_IMM_RETRY; case ISCSI_LOGIN_STATUS_TGT_MOVED_PERM: /* * for a permanent redirect, we need to update the * failback address */ memset(&conn->failback_saddr, 0, sizeof(struct sockaddr_storage)); conn->failback_saddr = conn->saddr; return CONN_LOGIN_IMM_REDIRECT_RETRY; default: log_error("conn %d login rejected: redirection " "type 0x%x not supported", conn->id, status_detail); return CONN_LOGIN_RETRY; } case ISCSI_STATUS_CLS_INITIATOR_ERR: switch (status_detail) { case ISCSI_LOGIN_STATUS_AUTH_FAILED: log_error("session %d login rejected: Initiator " "failed authentication with target", session->id); return CONN_LOGIN_AUTH_FAILED; case ISCSI_LOGIN_STATUS_TGT_FORBIDDEN: log_error("conn %d login rejected: initiator " "failed authorization with target", conn->id); return CONN_LOGIN_AUTH_FAILED; case ISCSI_LOGIN_STATUS_TGT_NOT_FOUND: log_error("conn %d login rejected: initiator " "error - target not found (%02x/%02x)", conn->id, status_class, status_detail); return CONN_LOGIN_FAILED; case ISCSI_LOGIN_STATUS_NO_VERSION: /* * FIXME: if we handle multiple protocol versions, * before we log an error, try the other supported * versions. */ log_error("conn %d login rejected: incompatible " "version (%02x/%02x), non-retryable, " "giving up", conn->id, status_class, status_detail); return CONN_LOGIN_FAILED; default: log_error("conn %d login rejected: initiator " "error (%02x/%02x)", conn->id, status_class, status_detail); return CONN_LOGIN_FAILED; } case ISCSI_STATUS_CLS_TARGET_ERR: log_error("conn %d login rejected: target error " "(%02x/%02x)\n", conn->id, status_class, status_detail); /* * We have no idea what the problem is. But spec says initiator * may retry later. */ return CONN_LOGIN_RETRY; default: log_error("conn %d login response with unknown status " "class 0x%x, detail 0x%x\n", conn->id, status_class, status_detail); break; } return CONN_LOGIN_FAILED; } static int __session_conn_create(iscsi_session_t *session, int cid) { iscsi_conn_t *conn = &session->conn[cid]; conn_rec_t *conn_rec = &session->nrec.conn[cid]; int err; if (iscsi_ev_context_alloc(conn)) { log_error("cannot allocate context_pool for conn cid %d", cid); return ISCSI_ERR_NOMEM; } conn->state = ISCSI_CONN_STATE_FREE; conn->session = session; /* * TODO: we must export the socket_fd/transport_eph from sysfs * so if iscsid is resyncing up we can pick that up and cleanup up * the old connection. Right now we leak a connection. * We can also probably merge these two fields. */ conn->socket_fd = -1; conn->transport_ep_handle = -1; /* connection's timeouts */ conn->id = cid; conn->logout_timeout = conn_rec->timeo.logout_timeout; if (!conn->logout_timeout) { log_error("Invalid timeo.logout_timeout. Must be greater " "than zero. Using default %d.\n", DEF_LOGOUT_TIMEO); conn->logout_timeout = DEF_LOGOUT_TIMEO; } conn->login_timeout = conn_rec->timeo.login_timeout; if (!conn->login_timeout) { log_error("Invalid timeo.login_timeout. Must be greater " "than zero. Using default %d.\n", DEF_LOGIN_TIMEO); conn->login_timeout = DEF_LOGIN_TIMEO; } conn->auth_timeout = conn_rec->timeo.auth_timeout; /* noop-out setting */ conn->noop_out_interval = conn_rec->timeo.noop_out_interval; conn->noop_out_timeout = conn_rec->timeo.noop_out_timeout; if (conn->noop_out_interval && !conn->noop_out_timeout) { log_error("Invalid timeo.noop_out_timeout. Must be greater " "than zero. Using default %d.\n", DEF_NOOP_OUT_TIMEO); conn->noop_out_timeout = DEF_NOOP_OUT_TIMEO; } if (conn->noop_out_timeout && !conn->noop_out_interval) { log_error("Invalid timeo.noop_out_interval. Must be greater " "than zero. Using default %d.\n", DEF_NOOP_OUT_INTERVAL); conn->noop_out_interval = DEF_NOOP_OUT_INTERVAL; } iscsi_copy_operational_params(conn, &session->nrec.session.iscsi, &conn_rec->iscsi); /* TCP options */ conn->tcp_window_size = conn_rec->tcp.window_size; /* FIXME: type_of_service */ /* resolve the string address to an IP address */ err = iscsi_setup_portal(conn, conn_rec->address, conn_rec->port); if (err) return err; return 0; } static void session_release(iscsi_session_t *session) { log_debug(2, "Releasing session %p", session); if (session->target_alias) free(session->target_alias); iscsi_ev_context_free(&session->conn[0]); free(session); } static iscsi_session_t* __session_create(node_rec_t *rec, struct iscsi_transport *t) { iscsi_session_t *session; int hostno, rc = 0; session = calloc(1, sizeof (*session)); if (session == NULL) { log_debug(1, "can not allocate memory for session"); return NULL; } log_debug(2, "Allocted session %p", session); INIT_LIST_HEAD(&session->list); session->t = t; session->reopen_qtask.mgmt_ipc_fd = -1; session->id = -1; session->use_ipc = 1; /* save node record. we might need it for redirection */ memcpy(&session->nrec, rec, sizeof(node_rec_t)); session->portal_group_tag = rec->tpgt; session->type = ISCSI_SESSION_TYPE_NORMAL; session->r_stage = R_STAGE_NO_CHANGE; strlcpy(session->target_name, rec->name, TARGET_NAME_MAXLEN); if (strlen(session->nrec.iface.iname)) session->initiator_name = session->nrec.iface.iname; else if (dconfig->initiator_name) session->initiator_name = dconfig->initiator_name; else { log_error("No initiator name set. Cannot create session."); free(session); return NULL; } if (strlen(session->nrec.iface.alias)) session->initiator_alias = session->nrec.iface.alias; else session->initiator_alias = dconfig->initiator_alias; /* session's eh parameters */ session->replacement_timeout = rec->session.timeo.replacement_timeout; session->fast_abort = rec->session.iscsi.FastAbort; session->abort_timeout = rec->session.err_timeo.abort_timeout; session->lu_reset_timeout = rec->session.err_timeo.lu_reset_timeout; session->tgt_reset_timeout = rec->session.err_timeo.tgt_reset_timeout; session->host_reset_timeout = rec->session.err_timeo.host_reset_timeout; /* OUI and uniqifying number */ session->isid[0] = DRIVER_ISID_0; session->isid[1] = DRIVER_ISID_1; session->isid[2] = DRIVER_ISID_2; session->isid[3] = 0; session->isid[4] = 0; session->isid[5] = 0; /* setup authentication variables for the session*/ iscsi_setup_authentication(session, &rec->session.auth); session->param_mask = ~0ULL; if (!(t->caps & CAP_MULTI_R2T)) session->param_mask &= ~ISCSI_MAX_R2T; if (!(t->caps & CAP_HDRDGST)) session->param_mask &= ~ISCSI_HDRDGST_EN; if (!(t->caps & CAP_DATADGST)) session->param_mask &= ~ISCSI_DATADGST_EN; if (!(t->caps & CAP_MARKERS)) { session->param_mask &= ~ISCSI_IFMARKER_EN; session->param_mask &= ~ISCSI_OFMARKER_EN; } hostno = iscsi_sysfs_get_host_no_from_hwinfo(&rec->iface, &rc); if (!rc) { /* * if the netdev or mac was set, then we are going to want * to want to bind the all the conns/eps to a specific host * if offload is used. */ session->conn[0].bind_ep = 1; session->hostno = hostno; } list_add_tail(&session->list, &t->sessions); return session; } static void iscsi_flush_context_pool(struct iscsi_session *session) { struct iscsi_ev_context *ev_context; struct iscsi_conn *conn = &session->conn[0]; int i; for (i = 0; i < CONTEXT_POOL_MAX; i++) { ev_context = conn->context_pool[i]; if (!ev_context) continue; if (ev_context->allocated) { actor_delete(&(conn->context_pool[i]->actor)); iscsi_ev_context_put(ev_context); } } } static void __session_destroy(iscsi_session_t *session) { log_debug(1, "destroying session\n"); list_del(&session->list); iscsi_flush_context_pool(session); session_release(session); } static void conn_delete_timers(iscsi_conn_t *conn) { actor_delete(&conn->login_timer); actor_delete(&conn->nop_out_timer); } static int session_conn_shutdown(iscsi_conn_t *conn, queue_task_t *qtask, int err) { iscsi_session_t *session = conn->session; log_debug(2, "disconnect conn"); /* this will check for a valid interconnect connection */ if (session->t->template->ep_disconnect) session->t->template->ep_disconnect(conn); if (session->id == -1) goto cleanup; if (!iscsi_sysfs_session_has_leadconn(session->id)) goto cleanup; if (conn->state == ISCSI_CONN_STATE_IN_LOGIN || conn->state == ISCSI_CONN_STATE_IN_LOGOUT || conn->state == ISCSI_CONN_STATE_LOGGED_IN) { log_debug(2, "stop conn (conn state %d)", conn->state); if (ipc->stop_conn(session->t->handle, session->id, conn->id, STOP_CONN_TERM)) { log_error("can't stop connection %d:%d (%d)", session->id, conn->id, errno); return ISCSI_ERR_INTERNAL; } } log_debug(2, "kdestroy conn"); if (ipc->destroy_conn(session->t->handle, session->id, conn->id)) { log_error("can not safely destroy connection %d", conn->id); return ISCSI_ERR_INTERNAL; } cleanup: if (session->id != -1) { log_debug(2, "kdestroy session %u", session->id); session->r_stage = R_STAGE_SESSION_DESTOYED; if (ipc->destroy_session(session->t->handle, session->id)) { log_error("can not safely destroy session %d", session->id); return ISCSI_ERR_INTERNAL; } } log_warning("Connection%d:%d to [target: %s, portal: %s,%d] " "through [iface: %s] is shutdown.", session->id, conn->id, session->nrec.name, session->nrec.conn[conn->id].address, session->nrec.conn[conn->id].port, session->nrec.iface.name); mgmt_ipc_write_rsp(qtask, err); conn_delete_timers(conn); __session_destroy(session); return ISCSI_SUCCESS; } static void queue_delayed_reopen(queue_task_t *qtask, int delay) { iscsi_conn_t *conn = qtask->conn; log_debug(4, "Requeue reopen attempt in %d secs\n", delay); /* * iscsi_login_eh can handle the login resched as * if it were login time out */ actor_delete(&conn->login_timer); actor_timer(&conn->login_timer, delay * 1000, iscsi_login_timedout, qtask); } static int iscsi_conn_connect(struct iscsi_conn *conn, queue_task_t *qtask) { struct iscsi_ev_context *ev_context; int rc; ev_context = iscsi_ev_context_get(conn, 0); if (!ev_context) { /* while reopening the recv pool should be full */ log_error("BUG: __session_conn_reopen could not get conn " "context for recv."); return ENOMEM; } ev_context->data = qtask; rc = conn->session->t->template->ep_connect(conn, 1); if (rc < 0 && errno != EINPROGRESS) { char serv[NI_MAXSERV]; getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); log_error("cannot make a connection to %s:%s (%d,%d)", conn->host, serv, rc, errno); iscsi_ev_context_put(ev_context); return ENOTCONN; } iscsi_sched_ev_context(ev_context, conn, 0, EV_CONN_POLL); log_debug(3, "Setting login timer %p timeout %d", &conn->login_timer, conn->login_timeout); actor_timer(&conn->login_timer, conn->login_timeout * 1000, iscsi_login_timedout, qtask); return 0; } static void __session_conn_reopen(iscsi_conn_t *conn, queue_task_t *qtask, int do_stop, int redirected) { iscsi_session_t *session = conn->session; uint32_t delay; log_debug(1, "re-opening session %d (reopen_cnt %d)", session->id, session->reopen_cnt); qtask->conn = conn; /* flush stale polls or errors queued */ iscsi_flush_context_pool(session); conn_delete_timers(conn); conn->state = ISCSI_CONN_STATE_XPT_WAIT; conn->session->t->template->ep_disconnect(conn); if (do_stop) { /* state: ISCSI_CONN_STATE_CLEANUP_WAIT */ if (ipc->stop_conn(session->t->handle, session->id, conn->id, do_stop)) { log_error("can't stop connection %d:%d (%d)", session->id, conn->id, errno); delay = ISCSI_INTERNAL_ERR_REOPEN_DELAY; goto queue_reopen; } log_debug(3, "connection %d:%d is stopped for recovery", session->id, conn->id); } if (!redirected) { delay = session->def_time2wait; session->def_time2wait = 0; if (delay) goto queue_reopen; } if (!redirected) session->reopen_cnt++; if (iscsi_conn_connect(conn, qtask)) { delay = ISCSI_CONN_ERR_REOPEN_DELAY; goto queue_reopen; } return; queue_reopen: log_debug(4, "Waiting %u seconds before trying to reconnect.\n", delay); queue_delayed_reopen(qtask, delay); } static void session_conn_reopen(iscsi_conn_t *conn, queue_task_t *qtask, int do_stop) { /* * If we were temporarily redirected, we need to fall back to * the original address to see where the target will send us * for the retry */ memset(&conn->saddr, 0, sizeof(struct sockaddr_storage)); conn->saddr = conn->failback_saddr; __session_conn_reopen(conn, qtask, do_stop, 0); } static int iscsi_retry_initial_login(struct iscsi_conn *conn) { int initial_login_retry_max; struct timeval now, timeout, fail_time; initial_login_retry_max = conn->session->nrec.session.initial_login_retry_max; memset(&now, 0, sizeof(now)); memset(&timeout, 0, sizeof(timeout)); memset(&fail_time, 0, sizeof(fail_time)); timeout.tv_sec = initial_login_retry_max * conn->login_timeout; if (gettimeofday(&now, NULL)) { log_error("Could not get time of day. Dropping down to " "max retry check.\n"); return initial_login_retry_max > conn->session->reopen_cnt; } timeradd(&conn->initial_connect_time, &timeout, &fail_time); /* * if we have been trying for login_retry_max * login_timeout * then it is time to give up */ if (timercmp(&now, &fail_time, >)) { log_debug(1, "Giving up on initial login attempt after " "%u seconds.\n", initial_login_retry_max * conn->login_timeout); return 0; } return 1; } static int iscsi_login_is_fatal_err(int err) { if (err == ISCSI_ERR_LOGIN_AUTH_FAILED || err == ISCSI_ERR_FATAL_LOGIN) return 1; return 0; } static void iscsi_login_eh(struct iscsi_conn *conn, struct queue_task *qtask, int err) { struct iscsi_session *session = conn->session; log_debug(3, "iscsi_login_eh"); /* * Flush polls and other events */ iscsi_flush_context_pool(conn->session); switch (conn->state) { case ISCSI_CONN_STATE_XPT_WAIT: switch (session->r_stage) { case R_STAGE_NO_CHANGE: log_debug(6, "login failed ISCSI_CONN_STATE_XPT_WAIT/" "R_STAGE_NO_CHANGE"); /* timeout during initial connect. * clean connection. write ipc rsp or retry */ if (iscsi_login_is_fatal_err(err) || !iscsi_retry_initial_login(conn)) session_conn_shutdown(conn, qtask, err); else { session->reopen_cnt++; session->t->template->ep_disconnect(conn); if (iscsi_conn_connect(conn, qtask)) queue_delayed_reopen(qtask, ISCSI_CONN_ERR_REOPEN_DELAY); } break; case R_STAGE_SESSION_REDIRECT: log_debug(6, "login failed ISCSI_CONN_STATE_XPT_WAIT/" "R_STAGE_SESSION_REDIRECT"); /* timeout during initial redirect connect * clean connection. write ipc rsp or retry */ if (iscsi_login_is_fatal_err(err) || !iscsi_retry_initial_login(conn)) session_conn_shutdown(conn, qtask, err); else session_conn_reopen(conn, qtask, 0); break; case R_STAGE_SESSION_REOPEN: log_debug(6, "login failed ISCSI_CONN_STATE_XPT_WAIT/" "R_STAGE_SESSION_REOPEN %d", session->reopen_cnt); /* timeout during reopen connect. try again */ session_conn_reopen(conn, qtask, 0); break; case R_STAGE_SESSION_CLEANUP: session_conn_shutdown(conn, qtask, err); break; default: break; } break; case ISCSI_CONN_STATE_IN_LOGIN: switch (session->r_stage) { case R_STAGE_NO_CHANGE: case R_STAGE_SESSION_REDIRECT: log_debug(6, "login failed ISCSI_CONN_STATE_IN_LOGIN/" "R_STAGE_NO_CHANGE %d", session->reopen_cnt); /* * send pdu timeout during initial connect or * initial redirected connect. Clean connection * and write rsp or retry. */ if (iscsi_login_is_fatal_err(err) || !iscsi_retry_initial_login(conn)) session_conn_shutdown(conn, qtask, err); else session_conn_reopen(conn, qtask, STOP_CONN_RECOVER); break; case R_STAGE_SESSION_REOPEN: log_debug(6, "login failed ISCSI_CONN_STATE_IN_LOGIN/" "R_STAGE_SESSION_REOPEN %d", session->reopen_cnt); session_conn_reopen(conn, qtask, STOP_CONN_RECOVER); break; case R_STAGE_SESSION_CLEANUP: session_conn_shutdown(conn, qtask, ISCSI_ERR_PDU_TIMEOUT); break; default: break; } break; default: log_error("Ignoring login error %d in conn state %d.\n", err, conn->state); break; } } static void __conn_error_handle(iscsi_session_t *session, iscsi_conn_t *conn) { int i; /* * if we got an error while trying to logout for the user then * just cleanup and return to the user. */ if (conn->logout_qtask) { session_conn_shutdown(conn, conn->logout_qtask, ISCSI_SUCCESS); return; } switch (conn->state) { case ISCSI_CONN_STATE_IN_LOGOUT: /* logout was from eh - fall down to cleanup */ case ISCSI_CONN_STATE_LOGGED_IN: /* mark failed connection */ conn->state = ISCSI_CONN_STATE_CLEANUP_WAIT; if (session->erl > 0) { /* check if we still have some logged in connections */ for (i=0; iconn[i].state == ISCSI_CONN_STATE_LOGGED_IN) break; } if (i != ISCSI_CONN_MAX) { /* FIXME: re-assign leading connection * for ERL>0 */ } break; } /* mark all connections as failed */ for (i=0; iconn[i].state == ISCSI_CONN_STATE_LOGGED_IN) session->conn[i].state = ISCSI_CONN_STATE_CLEANUP_WAIT; } session->r_stage = R_STAGE_SESSION_REOPEN; break; case ISCSI_CONN_STATE_IN_LOGIN: if (session->r_stage == R_STAGE_SESSION_REOPEN) { queue_task_t *qtask; if (session->notify_qtask) qtask = session->notify_qtask; else qtask = &session->reopen_qtask; iscsi_login_eh(conn, qtask, ISCSI_ERR_TRANS); return; } log_debug(1, "ignoring conn error in login. " "let it timeout"); return; case ISCSI_CONN_STATE_XPT_WAIT: log_debug(1, "ignoring conn error in XPT_WAIT. " "let connection fail on its own"); return; case ISCSI_CONN_STATE_CLEANUP_WAIT: log_debug(1, "ignoring conn error in CLEANUP_WAIT. " "let connection stop"); return; default: log_debug(8, "invalid state %d\n", conn->state); return; } if (session->r_stage == R_STAGE_SESSION_REOPEN) { session_conn_reopen(conn, &session->reopen_qtask, STOP_CONN_RECOVER); return; } } static void session_conn_error(void *data) { struct iscsi_ev_context *ev_context = data; enum iscsi_err error = *(enum iscsi_err *)ev_context->data; iscsi_conn_t *conn = ev_context->conn; iscsi_session_t *session = conn->session; log_warning("Kernel reported iSCSI connection %d:%d error (%d - %s) " "state (%d)", session->id, conn->id, error, kern_err_code_to_string(error), conn->state); iscsi_ev_context_put(ev_context); switch (error) { case ISCSI_ERR_INVALID_HOST: if (session_conn_shutdown(conn, NULL, ISCSI_SUCCESS)) log_error("BUG: Could not shutdown session."); break; default: __conn_error_handle(session, conn); } } static void iscsi_login_timedout(void *data) { struct queue_task *qtask = data; struct iscsi_conn *conn = qtask->conn; switch (conn->state) { case ISCSI_CONN_STATE_XPT_WAIT: iscsi_login_eh(conn, qtask, ISCSI_ERR_TRANS_TIMEOUT); break; case ISCSI_CONN_STATE_IN_LOGIN: iscsi_login_eh(conn, qtask, ISCSI_ERR_PDU_TIMEOUT); break; default: iscsi_login_eh(conn, qtask, ISCSI_ERR_INTERNAL); break; } } static void iscsi_login_redirect(iscsi_conn_t *conn) { iscsi_session_t *session = conn->session; iscsi_login_context_t *c = &conn->login_context; log_debug(3, "login redirect ...\n"); if (session->r_stage == R_STAGE_NO_CHANGE) session->r_stage = R_STAGE_SESSION_REDIRECT; __session_conn_reopen(conn, c->qtask, STOP_CONN_RECOVER, 1); } static int __send_nopin_rsp(iscsi_conn_t *conn, struct iscsi_nopin *rhdr, char *data) { struct iscsi_nopout hdr; memset(&hdr, 0, sizeof(struct iscsi_nopout)); hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE; hdr.flags = ISCSI_FLAG_CMD_FINAL; hdr.dlength[0] = rhdr->dlength[0]; hdr.dlength[1] = rhdr->dlength[1]; hdr.dlength[2] = rhdr->dlength[2]; memcpy(hdr.lun, rhdr->lun, 8); hdr.ttt = rhdr->ttt; hdr.itt = ISCSI_RESERVED_TAG; return iscsi_io_send_pdu(conn, (struct iscsi_hdr*)&hdr, ISCSI_DIGEST_NONE, data, ISCSI_DIGEST_NONE, 0); } static int __send_nopout(iscsi_conn_t *conn) { struct iscsi_nopout hdr; memset(&hdr, 0, sizeof(struct iscsi_nopout)); hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE; hdr.flags = ISCSI_FLAG_CMD_FINAL; hdr.itt = 0; /* XXX: let kernel send_pdu set for us*/ hdr.ttt = ISCSI_RESERVED_TAG; /* we have hdr.lun reserved, and no data */ return iscsi_io_send_pdu(conn, (struct iscsi_hdr*)&hdr, ISCSI_DIGEST_NONE, NULL, ISCSI_DIGEST_NONE, 0); } static void conn_nop_out_timeout(void *data) { iscsi_conn_t *conn = (iscsi_conn_t*)data; iscsi_session_t *session = conn->session; log_warning("Nop-out timedout after %d seconds on connection %d:%d " "state (%d). Dropping session.", conn->noop_out_timeout, session->id, conn->id, conn->state); /* XXX: error handle */ __conn_error_handle(session, conn); } static void conn_send_nop_out(void *data) { iscsi_conn_t *conn = data; /* * we cannot start new request during logout and the logout timer * will figure things out. */ if (conn->state == ISCSI_CONN_STATE_IN_LOGOUT) return; __send_nopout(conn); actor_timer(&conn->nop_out_timer, conn->noop_out_timeout*1000, conn_nop_out_timeout, conn); log_debug(3, "noop out timeout timer %p start, timeout %d\n", &conn->nop_out_timer, conn->noop_out_timeout); } void free_initiator(void) { struct iscsi_transport *t; iscsi_session_t *session, *tmp; list_for_each_entry(t, &transports, list) { list_for_each_entry_safe(session, tmp, &t->sessions, list) { list_del(&session->list); iscsi_flush_context_pool(session); session_release(session); } } free_transports(); } static void session_scan_host(struct iscsi_session *session, int hostno, queue_task_t *qtask) { pid_t pid; pid = iscsi_sysfs_scan_host(hostno, 1); if (pid == 0) { mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); if (session) iscsi_sysfs_for_each_device( &session->nrec.session.queue_depth, hostno, session->id, iscsi_sysfs_set_queue_depth); exit(0); } else if (pid > 0) { reap_inc(); if (qtask) { close(qtask->mgmt_ipc_fd); free(qtask); } } else mgmt_ipc_write_rsp(qtask, ISCSI_ERR_INTERNAL); } static void setup_full_feature_phase(iscsi_conn_t *conn) { iscsi_session_t *session = conn->session; iscsi_login_context_t *c = &conn->login_context; int rc; actor_delete(&conn->login_timer); if (iscsi_session_set_params(conn)) { iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; } if (iscsi_host_set_params(session)) { iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; } if (ipc->start_conn(session->t->handle, session->id, conn->id, &rc) || rc) { log_error("can't start connection %d:%d retcode %d (%d)", session->id, conn->id, rc, errno); iscsi_login_eh(conn, c->qtask, ISCSI_ERR_INTERNAL); return; } conn->state = ISCSI_CONN_STATE_LOGGED_IN; if (session->r_stage == R_STAGE_NO_CHANGE || session->r_stage == R_STAGE_SESSION_REDIRECT) { /* * scan host is one-time deal. We * don't want to re-scan it on recovery. */ if (conn->id == 0) session_scan_host(session, session->hostno, c->qtask); log_warning("Connection%d:%d to [target: %s, portal: %s,%d] " "through [iface: %s] is operational now", session->id, conn->id, session->nrec.name, session->nrec.conn[conn->id].address, session->nrec.conn[conn->id].port, session->nrec.iface.name); } else { session->notify_qtask = NULL; session_online_devs(session->hostno, session->id); mgmt_ipc_write_rsp(c->qtask, ISCSI_SUCCESS); log_warning("connection%d:%d is operational after recovery " "(%d attempts)", session->id, conn->id, session->reopen_cnt); } /* * reset ERL=0 reopen counter */ session->reopen_cnt = 0; session->r_stage = R_STAGE_NO_CHANGE; /* noop_out */ if (conn->userspace_nop && conn->noop_out_interval) { actor_timer(&conn->nop_out_timer, conn->noop_out_interval*1000, conn_send_nop_out, conn); log_debug(3, "noop out timer %p start\n", &conn->nop_out_timer); } } static void iscsi_logout_timedout(void *data) { struct iscsi_ev_context *ev_context = data; struct iscsi_conn *conn = ev_context->conn; iscsi_ev_context_put(ev_context); /* * assume we were in ISCSI_CONN_STATE_IN_LOGOUT or there * was some nasty error */ log_debug(3, "logout timeout, dropping conn...\n"); __conn_error_handle(conn->session, conn); } static int iscsi_send_logout(iscsi_conn_t *conn) { struct iscsi_logout hdr; struct iscsi_ev_context *ev_context; if (conn->state != ISCSI_CONN_STATE_LOGGED_IN) return EINVAL; memset(&hdr, 0, sizeof(struct iscsi_logout)); hdr.opcode = ISCSI_OP_LOGOUT | ISCSI_OP_IMMEDIATE; hdr.flags = ISCSI_FLAG_CMD_FINAL | (ISCSI_LOGOUT_REASON_CLOSE_SESSION & ISCSI_FLAG_LOGOUT_REASON_MASK); /* kernel will set the rest */ if (!iscsi_io_send_pdu(conn, (struct iscsi_hdr*)&hdr, ISCSI_DIGEST_NONE, NULL, ISCSI_DIGEST_NONE, 0)) return EIO; conn->state = ISCSI_CONN_STATE_IN_LOGOUT; ev_context = iscsi_ev_context_get(conn, 0); if (!ev_context) /* unbounded logout */ log_warning("Could not allocate conn context for logout."); else { iscsi_sched_ev_context(ev_context, conn, conn->logout_timeout, EV_CONN_LOGOUT_TIMER); log_debug(3, "logout timeout timer %u\n", conn->logout_timeout * 1000); } return 0; } static void iscsi_stop(void *data) { struct iscsi_ev_context *ev_context = data; struct iscsi_conn *conn = ev_context->conn; int rc = 0; iscsi_ev_context_put(ev_context); if (!(conn->session->t->caps & CAP_LOGIN_OFFLOAD)) { if (!iscsi_send_logout(conn)) return; } rc = session_conn_shutdown(conn, conn->logout_qtask, ISCSI_SUCCESS); if (rc) log_error("BUG: Could not shutdown session."); } static void iscsi_recv_nop_in(iscsi_conn_t *conn, struct iscsi_hdr *hdr) { if (!conn->userspace_nop) { log_error("Got nop in, but kernel supports nop handling."); return; } if (hdr->ttt == ISCSI_RESERVED_TAG) { /* noop out rsp */ actor_delete(&conn->nop_out_timer); /* schedule a new ping */ actor_timer(&conn->nop_out_timer, conn->noop_out_interval*1000, conn_send_nop_out, conn); } else /* noop in req */ if (!__send_nopin_rsp(conn, (struct iscsi_nopin*)hdr, conn->data)) { log_error("can not send nopin response"); } } static void iscsi_recv_logout_rsp(iscsi_conn_t *conn, struct iscsi_hdr *hdr) { struct iscsi_logout_rsp *logout_rsp = (struct iscsi_logout_rsp *)hdr; log_debug(3, "Recv: logout response %d\n", logout_rsp->response); if (logout_rsp->response == 2 || logout_rsp->response == 3) { conn->session->def_time2wait = ntohs(logout_rsp->t2wait); log_debug(4, "logout rsp returned time2wait %u", conn->session->def_time2wait); } /* TODO process the hdr */ __conn_error_handle(conn->session, conn); } static void iscsi_recv_async_msg(iscsi_conn_t *conn, struct iscsi_hdr *hdr) { iscsi_session_t *session = conn->session; struct iscsi_async *async_hdr = (struct iscsi_async *)hdr; char *buf = conn->data; unsigned int senselen; struct scsi_sense_hdr sshdr; log_debug(3, "Read AEN %d\n", async_hdr->async_event); switch (async_hdr->async_event) { case ISCSI_ASYNC_MSG_SCSI_EVENT: senselen = (buf[0] << 8) | buf[1]; buf += 2; if (!scsi_normalize_sense((uint8_t *)buf, senselen, &sshdr)) { log_error("Could not handle AEN %d. Invalid sense.", async_hdr->async_event); break; } if (sshdr.asc == 0x3f && sshdr.ascq == 0x0e) session_scan_host(session, session->hostno, NULL); break; case ISCSI_ASYNC_MSG_REQUEST_LOGOUT: log_warning("Target requests logout within %u seconds for " "connection\n", ntohs(async_hdr->param3)); if (iscsi_send_logout(conn)) log_error("Could not send logout in response to" "logout request aen\n"); break; case ISCSI_ASYNC_MSG_DROPPING_CONNECTION: log_warning("Target dropping connection %u, reconnect min %u " "max %u\n", ntohs(async_hdr->param1), ntohs(async_hdr->param2), ntohs(async_hdr->param3)); session->def_time2wait = (uint32_t)ntohs(async_hdr->param2) & 0x0000FFFFFL; break; case ISCSI_ASYNC_MSG_DROPPING_ALL_CONNECTIONS: log_warning("Target dropping all connections, reconnect min %u " "max %u\n", ntohs(async_hdr->param2), ntohs(async_hdr->param3)); session->def_time2wait = (uint32_t)ntohs(async_hdr->param2) & 0x0000FFFFFL; break; case ISCSI_ASYNC_MSG_PARAM_NEGOTIATION: log_warning("Received async event param negotiation, " "dropping session\n"); __conn_error_handle(session, conn); break; case ISCSI_ASYNC_MSG_VENDOR_SPECIFIC: default: log_warning("AEN not supported\n"); } } static void iscsi_recv_login_rsp(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; iscsi_login_context_t *c = &conn->login_context; int err = ISCSI_ERR_FATAL_LOGIN; if (iscsi_login_rsp(session, c)) { log_debug(1, "login_rsp ret (%d)", c->ret); switch (__login_response_status(conn, c->ret)) { case CONN_LOGIN_FAILED: goto failed; case CONN_LOGIN_RETRY: goto retry; case CONN_LOGIN_IMM_REDIRECT_RETRY: iscsi_login_redirect(conn); return; default: ; /* success - fall through */ } /* check the login status */ switch (__check_iscsi_status_class(session, conn->id, c->status_class, c->status_detail)) { case CONN_LOGIN_AUTH_FAILED: err = ISCSI_ERR_LOGIN_AUTH_FAILED; goto failed; case CONN_LOGIN_FAILED: goto failed; case CONN_LOGIN_IMM_REDIRECT_RETRY: iscsi_login_redirect(conn); return; case CONN_LOGIN_IMM_RETRY: case CONN_LOGIN_RETRY: goto retry; default: ; /* success - fall through */ } } if (conn->current_stage != ISCSI_FULL_FEATURE_PHASE) { /* more nego. needed! */ conn->state = ISCSI_CONN_STATE_IN_LOGIN; if (iscsi_login_req(session, c)) { iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; } } else setup_full_feature_phase(conn); return; retry: /* retry if not initial login or initial login has not timed out */ iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; failed: /* force failure if initial login */ session->reopen_cnt = session->nrec.session.initial_login_retry_max; iscsi_login_eh(conn, c->qtask, err); return; } static void session_conn_recv_pdu(void *data) { struct iscsi_ev_context *ev_context = data; iscsi_conn_t *conn = ev_context->conn; struct iscsi_hdr hdr; conn->recv_context = ev_context; switch (conn->state) { case ISCSI_CONN_STATE_IN_LOGIN: iscsi_recv_login_rsp(conn); break; case ISCSI_CONN_STATE_LOGGED_IN: case ISCSI_CONN_STATE_IN_LOGOUT: case ISCSI_CONN_STATE_LOGOUT_REQUESTED: /* read incoming PDU */ if (iscsi_io_recv_pdu(conn, &hdr, ISCSI_DIGEST_NONE, conn->data, ISCSI_DEF_MAX_RECV_SEG_LEN, ISCSI_DIGEST_NONE, 0) < 0) return; switch (hdr.opcode & ISCSI_OPCODE_MASK) { case ISCSI_OP_NOOP_IN: iscsi_recv_nop_in(conn, &hdr); break; case ISCSI_OP_LOGOUT_RSP: iscsi_recv_logout_rsp(conn, &hdr); break; case ISCSI_OP_ASYNC_EVENT: iscsi_recv_async_msg(conn, &hdr); break; default: log_error("unsupported opcode 0x%x", hdr.opcode); break; } break; case ISCSI_CONN_STATE_XPT_WAIT: iscsi_ev_context_put(ev_context); log_debug(1, "ignoring incoming PDU in XPT_WAIT. " "let connection re-establish or fail"); break; case ISCSI_CONN_STATE_CLEANUP_WAIT: iscsi_ev_context_put(ev_context); log_debug(1, "ignoring incoming PDU in XPT_WAIT. " "let connection cleanup"); break; default: iscsi_ev_context_put(ev_context); log_error("Invalid state. Dropping PDU.\n"); } } static void session_increase_wq_priority(struct iscsi_session *session) { DIR *proc_dir; struct dirent *proc_dent; struct stat statb; char stat_file[PATH_SIZE]; char sbuf[1024]; /* got this from ps */ int pid, stat_fd, num_read; char *proc_name, *proc_name_end; uint32_t host_no; /* drivers like bnx2i and qla4xxx do not have a write wq */ if (session->t->caps & CAP_DATA_PATH_OFFLOAD) return; proc_dir = opendir(PROC_DIR); if (!proc_dir) goto fail; while ((proc_dent = readdir(proc_dir))) { if (!strcmp(proc_dent->d_name, ".") || !strcmp(proc_dent->d_name, "..")) continue; if (sscanf(proc_dent->d_name, "%d", &pid) != 1) continue; memset(stat_file, 0, sizeof(stat_file)); sprintf(stat_file, PROC_DIR"/%d/stat", pid); if (stat(stat_file, &statb)) continue; if (!S_ISREG( statb.st_mode)) continue; stat_fd = open(stat_file, O_RDONLY); if (stat_fd == -1) continue; memset(sbuf, 0, sizeof(sbuf)); num_read = read(stat_fd, sbuf, sizeof(sbuf)); close(stat_fd); if (num_read == -1) continue; if (num_read == sizeof(sbuf)) sbuf[num_read - 1] = '\0'; else sbuf[num_read] = '\0'; /* * Finally match proc name to iscsi thread name. * In newer kernels the name is iscsi_wq_%HOST_NO. * In older kernels before 2.6.30, it was scsi_wq_%HOST_NO. * * We only support newer kernels. */ proc_name = strchr(sbuf, '(') + 1; if (!proc_name) continue; proc_name_end = strchr(proc_name, ')'); if (!proc_name_end) continue; *proc_name_end = '\0'; if (sscanf(proc_name, "iscsi_q_%u\n", &host_no) == 1) { if (host_no == session->hostno) { if (!setpriority(PRIO_PROCESS, pid, session->nrec.session.xmit_thread_priority)) { closedir(proc_dir); return; } else break; } } } closedir(proc_dir); fail: log_error("Could not set session%d priority. " "READ/WRITE throughout and latency could be " "affected.\n", session->id); } static int session_ipc_create(struct iscsi_session *session) { struct iscsi_conn *conn = &session->conn[0]; int err = 0, pass_ep = 1; uint32_t host_no = -1; if (session->t->template->ep_connect != ktransport_ep_connect) pass_ep = 0; retry_create: err = ipc->create_session(session->t->handle, pass_ep ? conn->transport_ep_handle : 0, session->nrec.session.initial_cmdsn, session->nrec.session.cmds_max, session->nrec.session.queue_depth, &session->id, &host_no); /* * Older kernels were not passed the sessions's leading conn ep, * so we will get -EINVAL || -ENOSYS for iser. * * 2.6.22 and earlier would send -EINVAL instead of -ENOSYS. */ if (pass_ep && (err == -ENOSYS || err == -EINVAL)) { pass_ep = 0; goto retry_create; } if (!err) { session->hostno = host_no; session_increase_wq_priority(session); } return err; } static void setup_offload_login_phase(iscsi_conn_t *conn) { iscsi_session_t *session = conn->session; iscsi_login_context_t *c = &conn->login_context; int rc; actor_delete(&conn->login_timer); if (iscsi_session_set_params(conn)) { iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; } if (iscsi_host_set_params(session)) { iscsi_login_eh(conn, c->qtask, ISCSI_ERR_LOGIN); return; } conn->state = ISCSI_CONN_STATE_IN_LOGIN; if (ipc->start_conn(session->t->handle, session->id, conn->id, &rc) || rc) { if (rc == -EEXIST) { log_error("Session already exists."); session_conn_shutdown(conn, c->qtask, ISCSI_ERR_SESS_EXISTS); } else { log_error("can't start connection %d:%d retcode (%d)", session->id, conn->id, rc); iscsi_login_eh(conn, c->qtask, ISCSI_ERR_INTERNAL); } return; } session->notify_qtask = c->qtask; } static void session_conn_poll(void *data) { struct iscsi_ev_context *ev_context = data; iscsi_conn_t *conn = ev_context->conn; struct iscsi_session *session = conn->session; int err = ISCSI_SUCCESS; queue_task_t *qtask = ev_context->data; iscsi_login_context_t *c = &conn->login_context; int rc; iscsi_ev_context_put(ev_context); if (conn->state != ISCSI_CONN_STATE_XPT_WAIT) return; rc = session->t->template->ep_poll(conn, 1); if (rc == 0) { log_debug(4, "poll not connected %d", rc); /* timedout: Poll again. */ ev_context = iscsi_ev_context_get(conn, 0); if (!ev_context) { /* while polling the recv pool should be full */ log_error("BUG: session_conn_poll could not get conn " "context."); iscsi_login_eh(conn, qtask, ISCSI_ERR_INTERNAL); return; } ev_context->data = qtask; iscsi_sched_ev_context(ev_context, conn, 0, EV_CONN_POLL); } else if (rc > 0) { /* connected! */ memset(c, 0, sizeof(iscsi_login_context_t)); /* do not allocate new connection in case of reopen */ if (session->id == -1) { if (conn->id == 0 && session_ipc_create(session)) { log_error("Can't create session."); err = ISCSI_ERR_INTERNAL; goto cleanup; } log_debug(3, "created new iSCSI session sid %d host " "no %u", session->id, session->hostno); err = ipc->create_conn(session->t->handle, session->id, conn->id, &conn->id); if (err) { log_error("Can't create connection."); err = ISCSI_ERR_INTERNAL; goto cleanup; } log_debug(3, "created new iSCSI connection " "%d:%d", session->id, conn->id); } iscsi_copy_operational_params(conn, &session->nrec.session.iscsi, &session->nrec.conn[conn->id].iscsi); /* * TODO: use the iface number or some other value * so this will be persistent */ session->isid[3] = session->id; if (ipc->bind_conn(session->t->handle, session->id, conn->id, conn->transport_ep_handle, (conn->id == 0), &rc) || rc) { log_error("can't bind conn %d:%d to session %d, " "retcode %d (%d)", session->id, conn->id, session->id, rc, errno); iscsi_login_eh(conn, qtask, ISCSI_ERR_LOGIN); return; } log_debug(3, "bound iSCSI connection %d:%d to session %d", session->id, conn->id, session->id); c->qtask = qtask; c->cid = conn->id; c->buffer = conn->data; c->bufsize = sizeof(conn->data); conn->exp_statsn = iscsi_sysfs_get_exp_statsn(session->id); if (session->t->caps & CAP_LOGIN_OFFLOAD) { setup_offload_login_phase(conn); return; } if (iscsi_login_begin(session, c)) { iscsi_login_eh(conn, qtask, ISCSI_ERR_LOGIN); return; } conn->state = ISCSI_CONN_STATE_IN_LOGIN; if (iscsi_login_req(session, c)) { iscsi_login_eh(conn, qtask, ISCSI_ERR_LOGIN); return; } } else { log_debug(4, "poll error %d", rc); queue_delayed_reopen(qtask, ISCSI_CONN_ERR_REOPEN_DELAY); } return; cleanup: session_conn_shutdown(conn, qtask, err); } static void session_conn_process_login(void *data) { struct iscsi_ev_context *ev_context = data; enum iscsi_conn_state state = *(enum iscsi_conn_state *) ev_context->data; struct iscsi_conn *conn = ev_context->conn; struct iscsi_session *session = conn->session; iscsi_login_context_t *c = &conn->login_context; queue_task_t *qtask; iscsi_ev_context_put(ev_context); if (!(session->t->caps & CAP_LOGIN_OFFLOAD)) return; if (state == ISCSI_CONN_STATE_FREE) goto failed_login; conn->state = ISCSI_CONN_STATE_LOGGED_IN; /* * ok we were in_login and now we got the notification that we are * logged in */ log_debug(3, "session created sid %u host no %d", session->id, session->hostno); if (session->r_stage == R_STAGE_NO_CHANGE || session->r_stage == R_STAGE_SESSION_REDIRECT) { /* * scan host is one-time deal. We * don't want to re-scan it on recovery. */ session_scan_host(session, session->hostno, c->qtask); session->notify_qtask = NULL; log_warning("Connection%d:%d to [target: %s, portal: %s,%d] " "through [iface: %s] is operational now", session->id, conn->id, session->nrec.name, session->nrec.conn[conn->id].address, session->nrec.conn[conn->id].port, session->nrec.iface.name); } else { session->notify_qtask = NULL; mgmt_ipc_write_rsp(c->qtask, ISCSI_SUCCESS); } /* * reset ERL=0 reopen counter */ session->reopen_cnt = 0; session->r_stage = R_STAGE_NO_CHANGE; return; failed_login: qtask = session->notify_qtask; session->notify_qtask = NULL; mgmt_ipc_write_rsp(qtask, ISCSI_ERR_LOGIN); if (ipc->destroy_conn(session->t->handle, session->id, conn->id)) log_error("can not safely destroy connection %d", conn->id); if (ipc->destroy_session(session->t->handle, session->id)) log_error("can not safely destroy session %d", session->id); __session_destroy(session); } static int iscsi_sched_ev_context(struct iscsi_ev_context *ev_context, struct iscsi_conn *conn, unsigned long tmo, int event) { enum iscsi_err error; log_debug(7, "sched conn context %p event %d, tmo %lu", &ev_context->actor, event, tmo); ev_context->conn = conn; switch (event) { case EV_CONN_RECV_PDU: actor_new(&ev_context->actor, session_conn_recv_pdu, ev_context); actor_schedule(&ev_context->actor); break; case EV_CONN_ERROR: error = *(enum iscsi_err *)ev_context->data; actor_new(&ev_context->actor, session_conn_error, ev_context); /* * We handle invalid host, by killing the session. * It must go at the head of the queue, so we do not * initiate error handling or logout or some other op. */ if (error == ISCSI_ERR_INVALID_HOST) actor_schedule_head(&ev_context->actor); else actor_schedule(&ev_context->actor); break; case EV_CONN_LOGIN: actor_new(&ev_context->actor, session_conn_process_login, ev_context); actor_schedule(&ev_context->actor); break; case EV_CONN_POLL: actor_new(&ev_context->actor, session_conn_poll, ev_context); actor_schedule(&ev_context->actor); break; case EV_CONN_LOGOUT_TIMER: actor_timer(&ev_context->actor, tmo * 1000, iscsi_logout_timedout, ev_context); break; case EV_CONN_STOP: actor_new(&ev_context->actor, iscsi_stop, ev_context); actor_schedule(&ev_context->actor); break; default: log_error("Invalid event type %d.", event); } return 0; } static iscsi_session_t* session_find_by_rec(node_rec_t *rec) { struct iscsi_transport *t; iscsi_session_t *session; list_for_each_entry(t, &transports, list) { list_for_each_entry(session, &t->sessions, list) { if (__iscsi_match_session(rec, session->nrec.name, session->nrec.conn[0].address, session->nrec.conn[0].port, &session->nrec.iface, MATCH_ANY_SID)) return session; } } return NULL; } /* * a session could be running in the kernel but not in iscsid * due to a resync or becuase some other app started the session */ static int session_is_running(node_rec_t *rec) { int nr_found = 0; if (session_find_by_rec(rec)) return 1; if (iscsi_sysfs_for_each_session(rec, &nr_found, iscsi_match_session)) return 1; return 0; } int session_login_task(node_rec_t *rec, queue_task_t *qtask) { iscsi_session_t *session; iscsi_conn_t *conn; struct iscsi_transport *t; int rc; if (session_is_running(rec)) { if (rec->session.multiple) log_debug(2, "Adding a copy of an existing session"); else return ISCSI_ERR_SESS_EXISTS; } t = iscsi_sysfs_get_transport_by_name(rec->iface.transport_name); if (!t) return ISCSI_ERR_TRANS_NOT_FOUND; if ((!(t->caps & CAP_RECOVERY_L0) && rec->session.iscsi.ERL != 0) || (!(t->caps & CAP_RECOVERY_L1) && rec->session.iscsi.ERL > 1)) { log_error("Transport '%s' does not support ERL %d." "Setting ERL to ERL0.\n", t->name, rec->session.iscsi.ERL); rec->session.iscsi.ERL = 0; } if (!(t->caps & CAP_MULTI_R2T) && rec->session.iscsi.MaxOutstandingR2T) { log_error("Transport '%s' does not support " "MaxOutstandingR2T %d. Setting " "MaxOutstandingR2T to 1.", t->name, rec->session.iscsi.MaxOutstandingR2T); rec->session.iscsi.MaxOutstandingR2T = 1; } if (!(t->caps & CAP_HDRDGST) && rec->conn[0].iscsi.HeaderDigest) { log_error("Transport '%s' does not support " "HeaderDigest != None. Setting HeaderDigest " "to None.", t->name); rec->conn[0].iscsi.HeaderDigest = CONFIG_DIGEST_NEVER; } if (!(t->caps & CAP_DATADGST) && rec->conn[0].iscsi.DataDigest) { log_error("Transport '%s' does not support " "DataDigest != None. Setting DataDigest " "to None", t->name); rec->conn[0].iscsi.DataDigest = CONFIG_DIGEST_NEVER; } if (!(t->caps & CAP_MARKERS) && rec->conn[0].iscsi.IFMarker) { log_error("Transport '%s' does not support IFMarker. " "Disabling IFMarkers.\n", t->name); rec->conn[0].iscsi.IFMarker = 0; } if (!(t->caps & CAP_MARKERS) && rec->conn[0].iscsi.OFMarker) { log_error("Transport '%s' does not support OFMarker." "Disabling OFMarkers.\n", t->name); rec->conn[0].iscsi.OFMarker = 0; } session = __session_create(rec, t); if (!session) return ISCSI_ERR_LOGIN; /* FIXME: login all connections! marked as "automatic" */ /* create leading connection */ rc = __session_conn_create(session, 0); if (rc) { __session_destroy(session); return rc; } conn = &session->conn[0]; qtask->conn = conn; if (iscsi_host_set_net_params(&rec->iface, session)) { __session_destroy(session); return ISCSI_ERR_LOGIN; } if (gettimeofday(&conn->initial_connect_time, NULL)) log_error("Could not get initial connect time. If " "login errors iscsid may give up the initial " "login early. You should manually login."); conn->state = ISCSI_CONN_STATE_XPT_WAIT; qtask->rsp.command = MGMT_IPC_SESSION_LOGIN; qtask->rsp.err = ISCSI_SUCCESS; if (iscsi_conn_connect(conn, qtask)) { log_debug(4, "Initial connect failed. Waiting %u seconds " "before trying to reconnect.\n", ISCSI_CONN_ERR_REOPEN_DELAY); queue_delayed_reopen(qtask, ISCSI_CONN_ERR_REOPEN_DELAY); } return ISCSI_SUCCESS; } static int sync_conn(iscsi_session_t *session, uint32_t cid) { iscsi_conn_t *conn; int rc; rc = __session_conn_create(session, cid); if (rc) return rc; conn = &session->conn[cid]; /* TODO: must export via sysfs so we can pick this up */ conn->state = ISCSI_CONN_STATE_CLEANUP_WAIT; return 0; } int iscsi_sync_session(node_rec_t *rec, queue_task_t *qtask, uint32_t sid) { iscsi_session_t *session; struct iscsi_transport *t; int err; t = iscsi_sysfs_get_transport_by_name(rec->iface.transport_name); if (!t) return ISCSI_ERR_TRANS_NOT_FOUND; session = __session_create(rec, t); if (!session) return ISCSI_ERR_LOGIN; session->id = sid; session->hostno = iscsi_sysfs_get_host_no_from_sid(sid, &err); if (err) { log_error("Could not get hostno for session %d\n", sid); goto destroy_session; } session->r_stage = R_STAGE_SESSION_REOPEN; err = sync_conn(session, 0); if (err) goto destroy_session; qtask->rsp.command = MGMT_IPC_SESSION_SYNC; log_debug(3, "Started sync iSCSI session %d", session->id); session->notify_qtask = qtask; session_conn_reopen(&session->conn[0], qtask, STOP_CONN_RECOVER); return 0; destroy_session: __session_destroy(session); log_error("Could not sync session%d err %d\n", sid, err); return err; } static int session_unbind(struct iscsi_session *session) { int err; err = ipc->unbind_session(session->t->handle, session->id); if (err) /* older kernels did not support unbind */ log_debug(2, "Could not unbind session %d.\n", err); return err; } int session_logout_task(int sid, queue_task_t *qtask) { iscsi_session_t *session; iscsi_conn_t *conn; int rc = ISCSI_SUCCESS; session = session_find_by_sid(sid); if (!session) { log_debug(1, "session sid %d not found.\n", sid); return ISCSI_ERR_SESS_NOT_FOUND; } conn = &session->conn[0]; /* * If syncing up or if this is the initial login and mgmt_ipc * has not been notified of that result fail the logout request */ if (session->notify_qtask || ((conn->state == ISCSI_CONN_STATE_XPT_WAIT || conn->state == ISCSI_CONN_STATE_IN_LOGIN) && (session->r_stage == R_STAGE_NO_CHANGE || session->r_stage == R_STAGE_SESSION_REDIRECT))) { invalid_state: log_error("session in invalid state for logout. " "Try again later\n"); return ISCSI_ERR_INTERNAL; } /* FIXME: logout all active connections */ conn = &session->conn[0]; if (conn->logout_qtask) goto invalid_state; qtask->conn = conn; qtask->rsp.command = MGMT_IPC_SESSION_LOGOUT; conn->logout_qtask = qtask; switch (conn->state) { case ISCSI_CONN_STATE_LOGGED_IN: if (!session_unbind(session)) return ISCSI_SUCCESS; /* LLDs that offload login also offload logout */ if (!(session->t->caps & CAP_LOGIN_OFFLOAD)) { /* unbind is not supported so just do old logout */ if (!iscsi_send_logout(conn)) return ISCSI_SUCCESS; } log_error("Could not send logout pdu. Dropping session\n"); /* fallthrough */ default: rc = session_conn_shutdown(conn, qtask, ISCSI_SUCCESS); break; } return rc; } int iscsi_host_send_targets(queue_task_t *qtask, int host_no, int do_login, struct sockaddr_storage *ss) { struct iscsi_transport *t; t = iscsi_sysfs_get_transport_by_hba(host_no); if (!t) { log_error("Invalid host no %d for sendtargets\n", host_no); return ISCSI_ERR_TRANS_NOT_FOUND; } if (!(t->caps & CAP_SENDTARGETS_OFFLOAD)) return ISCSI_ERR_TRANS_CAPS; if (ipc->sendtargets(t->handle, host_no, (struct sockaddr *)ss)) return ISCSI_ERR; return ISCSI_SUCCESS; } /* * HW drivers like qla4xxx present a interface that hides most of the iscsi * details. Userspace sends down a discovery event then it gets notified * if the sessions that were logged in as a result asynchronously, or * the card will have sessions preset in the FLASH and will log into them * automaotically then send us notification that a session is setup. */ static void iscsi_async_session_creation(uint32_t host_no, uint32_t sid) { struct iscsi_transport *transport; transport = iscsi_sysfs_get_transport_by_hba(host_no); if (!transport) return; if (!(transport->caps & CAP_FW_DB)) return; log_debug(3, "session created sid %u host no %d", sid, host_no); session_online_devs(host_no, sid); session_scan_host(NULL, host_no, NULL); } static void iscsi_async_session_destruction(uint32_t host_no, uint32_t sid) { log_debug(3, "session destroyed sid %u host no %d", sid, host_no); } static struct iscsi_ipc_ev_clbk ipc_clbk = { .create_session = iscsi_async_session_creation, .destroy_session = iscsi_async_session_destruction, .get_ev_context = iscsi_ev_context_get, .put_ev_context = iscsi_ev_context_put, .sched_ev_context = iscsi_sched_ev_context, }; void iscsi_initiator_init(void) { ipc_register_ev_callback(&ipc_clbk); } open-iscsi-2.0.873/usr/initiator.h000066400000000000000000000243471175631155400167520ustar00rootroot00000000000000/* * iSCSI Initiator * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef INITIATOR_H #define INITIATOR_H #include #include #include #include "types.h" #include "iscsi_proto.h" #include "iscsi_if.h" #include "auth.h" #include "mgmt_ipc.h" #include "config.h" #include "actor.h" #include "list.h" #define ISCSI_CONFIG_ROOT "/etc/iscsi/" #define CONFIG_FILE ISCSI_CONFIG_ROOT"iscsid.conf" #define INITIATOR_NAME_FILE ISCSI_CONFIG_ROOT"initiatorname.iscsi" #define PID_FILE "/var/run/iscsid.pid" #ifndef LOCK_DIR #define LOCK_DIR "/var/lock/iscsi" #endif #define LOCK_FILE LOCK_DIR"/lock" #define LOCK_WRITE_FILE LOCK_DIR"/lock.write" typedef enum iscsi_session_r_stage_e { R_STAGE_NO_CHANGE, R_STAGE_SESSION_CLEANUP, R_STAGE_SESSION_REOPEN, R_STAGE_SESSION_REDIRECT, R_STAGE_SESSION_DESTOYED, } iscsi_session_r_stage_e; typedef enum conn_login_status_e { CONN_LOGIN_SUCCESS = 0, CONN_LOGIN_FAILED = 1, CONN_LOGIN_IO_ERR = 2, CONN_LOGIN_RETRY = 3, CONN_LOGIN_IMM_RETRY = 4, CONN_LOGIN_IMM_REDIRECT_RETRY = 5, CONN_LOGIN_AUTH_FAILED = 6, } conn_login_status_e; enum iscsi_login_status { LOGIN_OK = 0, LOGIN_IO_ERROR = 1, LOGIN_FAILED = 2, LOGIN_VERSION_MISMATCH = 3, LOGIN_NEGOTIATION_FAILED = 4, LOGIN_AUTHENTICATION_FAILED = 5, LOGIN_REDIRECTION_FAILED = 6, LOGIN_INVALID_PDU = 7, LOGIN_REDIRECT = 8, }; typedef enum iscsi_event_e { EV_UNKNOWN, EV_CONN_RECV_PDU, EV_CONN_POLL, EV_CONN_ERROR, EV_CONN_LOGOUT_TIMER, EV_CONN_STOP, EV_CONN_LOGIN, } iscsi_event_e; struct queue_task; typedef struct iscsi_login_context { int cid; char *buffer; size_t bufsize; uint8_t status_class; uint8_t status_detail; struct iscsi_acl *auth_client; struct iscsi_hdr pdu; struct iscsi_login_rsp *login_rsp; char *data; int received_pdu; int max_data_length; int timeout; int final; enum iscsi_login_status ret; struct queue_task *qtask; } iscsi_login_context_t; struct iscsi_session; struct iscsi_conn; struct iscsi_ev_context; /* daemon's connection structure */ typedef struct iscsi_conn { uint32_t id; struct iscsi_session *session; iscsi_login_context_t login_context; struct iscsi_ev_context *recv_context; struct queue_task *logout_qtask; char data[ISCSI_DEF_MAX_RECV_SEG_LEN]; char host[NI_MAXHOST]; /* scratch */ enum iscsi_conn_state state; int userspace_nop; struct timeval initial_connect_time; actor_t login_timer; actor_t nop_out_timer; #define CONTEXT_POOL_MAX 32 struct iscsi_ev_context *context_pool[CONTEXT_POOL_MAX]; /* login state machine */ int current_stage; int next_stage; int partial_response; conn_login_status_e status; /* tcp/socket settings */ /* * Either a tcp/ip or a netlink socket to do * IO through. */ int socket_fd; /* address being used for normal session connection */ struct sockaddr_storage saddr; /* address received during login */ struct sockaddr_storage failback_saddr; int tcp_window_size; int type_of_service; /* used for the IPC of bind and for connect/poll/disconnect by * transports (eg iser) which does these ops from the kernel. * In the case of TCP, it is just the transport_fd casted to u64. */ uint64_t transport_ep_handle; int bind_ep; /* timeouts */ int login_timeout; int logout_timeout; int auth_timeout; int active_timeout; int noop_out_interval; int noop_out_timeout; /* sequencing */ uint32_t exp_statsn; /* negotiated parameters */ uint32_t hdrdgst_en; uint32_t datadgst_en; uint32_t max_recv_dlength; /* the value we declare */ uint32_t max_xmit_dlength; /* the value declared by the target */ } iscsi_conn_t; struct iscsi_ev_context { struct actor actor; struct iscsi_conn *conn; int allocated; void *data; }; typedef struct queue_task { iscsi_conn_t *conn; iscsiadm_req_t req; iscsiadm_rsp_t rsp; int mgmt_ipc_fd; int allocated : 1; /* Newer request types include a * variable-length payload */ void *payload; } queue_task_t; struct iscsi_transport_template; struct iscsi_transport; /* daemon's session structure */ typedef struct iscsi_session { struct list_head list; uint32_t id; uint32_t hostno; char netdev[IFNAMSIZ]; struct iscsi_transport *t; uint8_t use_ipc; node_rec_t nrec; /* copy of original Node record in database */ unsigned int irrelevant_keys_bitmap; int send_async_text; uint32_t itt; uint32_t cmdsn; uint32_t exp_cmdsn; uint32_t max_cmdsn; int erl; uint32_t imm_data_en; uint32_t initial_r2t_en; uint32_t fast_abort; uint32_t first_burst; uint32_t max_burst; uint32_t pdu_inorder_en; uint32_t dataseq_inorder_en; uint32_t def_time2wait; uint32_t def_time2retain; int type; int portal_group_tag; uint8_t isid[6]; uint16_t tsih; char target_name[TARGET_NAME_MAXLEN + 1]; char *target_alias; char *initiator_name; char *initiator_alias; struct auth_str_block auth_recv_string_block; struct auth_str_block auth_send_string_block; struct auth_large_binary auth_recv_binary_block; struct auth_large_binary auth_send_binary_block; struct iscsi_acl auth_client_block; struct iscsi_acl *auth_client; int num_auth_buffers; struct auth_buffer_desc auth_buffers[5]; int bidirectional_auth; char username[AUTH_STR_MAX_LEN]; uint8_t password[AUTH_STR_MAX_LEN]; int password_length; char username_in[AUTH_STR_MAX_LEN]; uint8_t password_in[AUTH_STR_MAX_LEN]; int password_in_length; iscsi_conn_t conn[ISCSI_CONN_MAX]; uint64_t param_mask; /* connection reopens during recovery */ int reopen_cnt; queue_task_t reopen_qtask; iscsi_session_r_stage_e r_stage; uint32_t replacement_timeout; int host_reset_timeout; int tgt_reset_timeout; int lu_reset_timeout; int abort_timeout; /* * used for hw and sync up to notify caller that the operation * is complete */ queue_task_t *notify_qtask; } iscsi_session_t; /* login.c */ #define ISCSI_SESSION_TYPE_NORMAL 0 #define ISCSI_SESSION_TYPE_DISCOVERY 1 /* not defined by iSCSI, but used in the login code to determine * when to send the initial Login PDU */ #define ISCSI_INITIAL_LOGIN_STAGE -1 #define ISCSI_TEXT_SEPARATOR '=' /* implemented in iscsi-login.c for use on all platforms */ extern int iscsi_add_text(struct iscsi_hdr *hdr, char *data, int max_data_length, char *param, char *value); extern enum iscsi_login_status iscsi_login(iscsi_session_t *session, int cid, char *buffer, size_t bufsize, uint8_t * status_class, uint8_t * status_detail); extern int iscsi_update_address(iscsi_conn_t *conn, char *address); extern int iscsi_login_begin(iscsi_session_t *session, iscsi_login_context_t *c); extern int iscsi_login_req(iscsi_session_t *session, iscsi_login_context_t *c); extern int iscsi_login_rsp(iscsi_session_t *session, iscsi_login_context_t *c); extern int resolve_address(char *host, char *port, struct sockaddr_storage *ss); /* Digest types */ #define ISCSI_DIGEST_NONE 0 #define ISCSI_DIGEST_CRC32C 1 #define ISCSI_DIGEST_CRC32C_NONE 2 /* offer both, prefer CRC32C */ #define ISCSI_DIGEST_NONE_CRC32C 3 /* offer both, prefer None */ #define IRRELEVANT_MAXCONNECTIONS 0x01 #define IRRELEVANT_INITIALR2T 0x02 #define IRRELEVANT_IMMEDIATEDATA 0x04 #define IRRELEVANT_MAXBURSTLENGTH 0x08 #define IRRELEVANT_FIRSTBURSTLENGTH 0x10 #define IRRELEVANT_MAXOUTSTANDINGR2T 0x20 #define IRRELEVANT_DATAPDUINORDER 0x40 #define IRRELEVANT_DATASEQUENCEINORDER 0x80 /* * These user/kernel IPC calls are used by transports (eg iSER) that have their * native connection managed from the kernel. The IPC for having the user space * code being able to do it, is implemented as an enhancement of the open iscsi * netlink IPC scheme, currently with the ability to connect/poll-for-establish * ment/disconnect an opaque transport dependent 64 bit ep (endpoint) handle. * The exact IPC ABI for that matter is defined in iscsi_if.h */ /* netlink.c */ extern int ktransport_ep_connect(iscsi_conn_t *conn, int non_blocking); extern int ktransport_ep_poll(iscsi_conn_t *conn, int timeout_ms); extern void ktransport_ep_disconnect(iscsi_conn_t *conn); /* io.c */ extern int iscsi_io_tcp_poll(iscsi_conn_t *conn, int timeout_ms); extern int iscsi_io_tcp_connect(iscsi_conn_t *conn, int non_blocking); extern void iscsi_io_tcp_disconnect(iscsi_conn_t *conn); extern int iscsi_io_connect(iscsi_conn_t *conn); extern void iscsi_io_disconnect(iscsi_conn_t *conn); extern int iscsi_io_send_pdu(iscsi_conn_t *conn, struct iscsi_hdr *hdr, int hdr_digest, char *data, int data_digest, int timeout); extern int iscsi_io_recv_pdu(iscsi_conn_t *conn, struct iscsi_hdr *hdr, int hdr_digest, char *data, int max_data_length, int data_digest, int timeout); /* initiator.c */ extern int session_login_task(node_rec_t *rec, queue_task_t *qtask); extern int session_logout_task(int sid, queue_task_t *qtask); extern iscsi_session_t *session_find_by_sid(uint32_t sid); extern int iscsi_sync_session(node_rec_t *rec, queue_task_t *tsk, uint32_t sid); extern int iscsi_host_send_targets(queue_task_t *qtask, int host_no, int do_login, struct sockaddr_storage *ss); extern void free_initiator(void); extern void iscsi_initiator_init(void); /* initiator code common to discovery and normal sessions */ extern int iscsi_session_set_params(struct iscsi_conn *conn); extern int iscsi_host_set_params(struct iscsi_session *session); extern int iscsi_host_set_net_params(struct iface_rec *iface, struct iscsi_session *session); extern void iscsi_copy_operational_params(struct iscsi_conn *conn, struct iscsi_session_operational_config *session_conf, struct iscsi_conn_operational_config *conn_conf); extern int iscsi_setup_authentication(struct iscsi_session *session, struct iscsi_auth_config *auth_cfg); extern int iscsi_setup_portal(struct iscsi_conn *conn, char *address, int port); #endif /* INITIATOR_H */ open-iscsi-2.0.873/usr/initiator_common.c000066400000000000000000000421201175631155400203020ustar00rootroot00000000000000/* * Common code for setting up discovery and normal sessions. * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 - 2009 Mike Christie * Copyright (C) 2006 - 2009 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include "initiator.h" #include "transport.h" #include "iscsid.h" #include "iscsi_ipc.h" #include "log.h" #include "iscsi_sysfs.h" #include "iscsi_settings.h" #include "iface.h" #include "host.h" #include "sysdeps.h" #include "iscsi_err.h" #include "iscsi_net_util.h" struct iscsi_session *session_find_by_sid(uint32_t sid) { struct iscsi_transport *t; struct iscsi_session *session; list_for_each_entry(t, &transports, list) { list_for_each_entry(session, &t->sessions, list) { if (session->id == sid) return session; } } return NULL; } /* * calculate parameter's padding */ static unsigned int __padding(unsigned int param) { int pad; pad = param & 3; if (pad) { pad = 4 - pad; log_debug(1, "parameter's value %d padded to %d bytes\n", param, param + pad); } return param + pad; } int iscsi_setup_authentication(struct iscsi_session *session, struct iscsi_auth_config *auth_cfg) { /* if we have any incoming credentials, we insist on authenticating * the target or not logging in at all */ if (auth_cfg->username_in[0] || auth_cfg->password_in_length) { /* sanity check the config */ if (auth_cfg->password_length == 0) { log_warning("CHAP configuratoin has incoming " "authentication credentials but has no " "outgoing credentials configured."); return EINVAL; } session->bidirectional_auth = 1; } else { /* no or 1-way authentication */ session->bidirectional_auth = 0; } /* copy in whatever credentials we have */ strlcpy(session->username, auth_cfg->username, sizeof (session->username)); session->username[sizeof (session->username) - 1] = '\0'; if ((session->password_length = auth_cfg->password_length)) memcpy(session->password, auth_cfg->password, session->password_length); strlcpy(session->username_in, auth_cfg->username_in, sizeof (session->username_in)); session->username_in[sizeof (session->username_in) - 1] = '\0'; if ((session->password_in_length = auth_cfg->password_in_length)) memcpy(session->password_in, auth_cfg->password_in, session->password_in_length); if (session->password_length || session->password_in_length) { /* setup the auth buffers */ session->auth_buffers[0].address = &session->auth_client_block; session->auth_buffers[0].length = sizeof (session->auth_client_block); session->auth_buffers[1].address = &session->auth_recv_string_block; session->auth_buffers[1].length = sizeof (session->auth_recv_string_block); session->auth_buffers[2].address = &session->auth_send_string_block; session->auth_buffers[2].length = sizeof (session->auth_send_string_block); session->auth_buffers[3].address = &session->auth_recv_binary_block; session->auth_buffers[3].length = sizeof (session->auth_recv_binary_block); session->auth_buffers[4].address = &session->auth_send_binary_block; session->auth_buffers[4].length = sizeof (session->auth_send_binary_block); session->num_auth_buffers = 5; log_debug(6, "authentication setup complete..."); } else { session->num_auth_buffers = 0; log_debug(6, "no authentication configured..."); } return 0; } void iscsi_copy_operational_params(struct iscsi_conn *conn, struct iscsi_session_operational_config *session_conf, struct iscsi_conn_operational_config *conn_conf) { struct iscsi_session *session = conn->session; struct iscsi_transport *t = session->t; conn->hdrdgst_en = conn_conf->HeaderDigest; conn->datadgst_en = conn_conf->DataDigest; conn->max_recv_dlength = __padding(conn_conf->MaxRecvDataSegmentLength); if (conn->max_recv_dlength < ISCSI_MIN_MAX_RECV_SEG_LEN || conn->max_recv_dlength > ISCSI_MAX_MAX_RECV_SEG_LEN) { log_error("Invalid iscsi.MaxRecvDataSegmentLength. Must be " "within %u and %u. Setting to %u\n", ISCSI_MIN_MAX_RECV_SEG_LEN, ISCSI_MAX_MAX_RECV_SEG_LEN, DEF_INI_MAX_RECV_SEG_LEN); conn_conf->MaxRecvDataSegmentLength = DEF_INI_MAX_RECV_SEG_LEN; conn->max_recv_dlength = DEF_INI_MAX_RECV_SEG_LEN; } /* zero indicates to use the target's value */ conn->max_xmit_dlength = __padding(conn_conf->MaxXmitDataSegmentLength); if (conn->max_xmit_dlength == 0) conn->max_xmit_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN; if (conn->max_xmit_dlength < ISCSI_MIN_MAX_RECV_SEG_LEN || conn->max_xmit_dlength > ISCSI_MAX_MAX_RECV_SEG_LEN) { log_error("Invalid iscsi.MaxXmitDataSegmentLength. Must be " "within %u and %u. Setting to %u\n", ISCSI_MIN_MAX_RECV_SEG_LEN, ISCSI_MAX_MAX_RECV_SEG_LEN, DEF_INI_MAX_RECV_SEG_LEN); conn_conf->MaxXmitDataSegmentLength = DEF_INI_MAX_RECV_SEG_LEN; conn->max_xmit_dlength = DEF_INI_MAX_RECV_SEG_LEN; } /* session's operational parameters */ session->initial_r2t_en = session_conf->InitialR2T; session->imm_data_en = session_conf->ImmediateData; session->first_burst = __padding(session_conf->FirstBurstLength); /* * some targets like netapp fail the login if sent bad first_burst * and max_burst lens, even when immediate data=no and * initial r2t = Yes, so we always check the user values. */ if (session->first_burst < ISCSI_MIN_FIRST_BURST_LEN || session->first_burst > ISCSI_MAX_FIRST_BURST_LEN) { log_error("Invalid iscsi.FirstBurstLength of %u. Must be " "within %u and %u. Setting to %u\n", session->first_burst, ISCSI_MIN_FIRST_BURST_LEN, ISCSI_MAX_FIRST_BURST_LEN, DEF_INI_FIRST_BURST_LEN); session_conf->FirstBurstLength = DEF_INI_FIRST_BURST_LEN; session->first_burst = DEF_INI_FIRST_BURST_LEN; } session->max_burst = __padding(session_conf->MaxBurstLength); if (session->max_burst < ISCSI_MIN_MAX_BURST_LEN || session->max_burst > ISCSI_MAX_MAX_BURST_LEN) { log_error("Invalid iscsi.MaxBurstLength of %u. Must be " "within %u and %u. Setting to %u\n", session->max_burst, ISCSI_MIN_MAX_BURST_LEN, ISCSI_MAX_MAX_BURST_LEN, DEF_INI_MAX_BURST_LEN); session_conf->MaxBurstLength = DEF_INI_MAX_BURST_LEN; session->max_burst = DEF_INI_MAX_BURST_LEN; } if (session->first_burst > session->max_burst) { log_error("Invalid iscsi.FirstBurstLength of %u. Must be " "less than iscsi.MaxBurstLength. Setting to %u\n", session->first_burst, session->max_burst); session_conf->FirstBurstLength = session->max_burst; session->first_burst = session->max_burst; } session->def_time2wait = session_conf->DefaultTime2Wait; session->def_time2retain = session_conf->DefaultTime2Retain; session->erl = session_conf->ERL; if (session->type == ISCSI_SESSION_TYPE_DISCOVERY) { /* * Right now, we only support 8K max for kernel based * sendtargets discovery, because the recv pdu buffers are * limited to this size. */ if ((t->caps & CAP_TEXT_NEGO) && conn->max_recv_dlength > ISCSI_DEF_MAX_RECV_SEG_LEN) conn->max_recv_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN; /* We do not support discovery sessions with digests */ conn->hdrdgst_en = ISCSI_DIGEST_NONE; conn->datadgst_en = ISCSI_DIGEST_NONE; } if (t->template->create_conn) t->template->create_conn(conn); } int iscsi_setup_portal(struct iscsi_conn *conn, char *address, int port) { char serv[NI_MAXSERV]; sprintf(serv, "%d", port); if (resolve_address(address, serv, &conn->saddr)) { log_error("cannot resolve host name %s", address); return ISCSI_ERR_TRANS; } conn->failback_saddr = conn->saddr; getnameinfo((struct sockaddr *)&conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), NULL, 0, NI_NUMERICHOST); log_debug(4, "resolved %s to %s", address, conn->host); return 0; } int host_set_param(struct iscsi_transport *t, uint32_t host_no, int param, char *value, int type) { int rc; rc = ipc->set_host_param(t->handle, host_no, param, value, type); /* 2.6.20 and below returns EINVAL */ if (rc && rc != -ENOSYS && rc != -EINVAL) { log_error("can't set operational parameter %d for " "host %d, retcode %d (%d)", param, host_no, rc, errno); return rc; } return 0; } static void print_param_value(enum iscsi_param param, void *value, int type) { log_debug(3, "set operational parameter %d to:", param); if (type == ISCSI_STRING) log_debug(3, "%s", value ? (char *)value : "NULL"); else log_debug(3, "%u", *(uint32_t *)value); } #define MAX_HOST_PARAMS 2 int iscsi_host_set_params(struct iscsi_session *session) { struct iscsi_transport *t = session->t; int i; struct hostparam { int param; int type; void *value; } hosttbl[MAX_HOST_PARAMS] = { { .param = ISCSI_HOST_PARAM_NETDEV_NAME, .value = session->nrec.iface.netdev, .type = ISCSI_STRING, }, { .param = ISCSI_HOST_PARAM_HWADDRESS, .value = session->nrec.iface.hwaddress, .type = ISCSI_STRING, }, }; for (i = 0; i < MAX_HOST_PARAMS; i++) { if (host_set_param(t, session->hostno, hosttbl[i].param, hosttbl[i].value, hosttbl[i].type)) { return EPERM; } print_param_value(hosttbl[i].param, hosttbl[i].value, hosttbl[i].type); } return 0; } #define MAX_SESSION_PARAMS 32 int iscsi_session_set_params(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; struct iscsi_transport *t = session->t; int i, rc; uint32_t one = 1, zero = 0; struct connparam { int param; int type; void *value; int conn_only; } conntbl[MAX_SESSION_PARAMS] = { { .param = ISCSI_PARAM_MAX_RECV_DLENGTH, .value = &conn->max_recv_dlength, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_MAX_XMIT_DLENGTH, .value = &conn->max_xmit_dlength, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_HDRDGST_EN, .value = &conn->hdrdgst_en, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_DATADGST_EN, .value = &conn->datadgst_en, .type = ISCSI_INT, .conn_only = 1, }, { .param = ISCSI_PARAM_INITIAL_R2T_EN, .value = &session->initial_r2t_en, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_MAX_R2T, .value = &one, /* FIXME: session->max_r2t */ .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_IMM_DATA_EN, .value = &session->imm_data_en, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_FIRST_BURST, .value = &session->first_burst, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_MAX_BURST, .value = &session->max_burst, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_PDU_INORDER_EN, .value = &session->pdu_inorder_en, .type = ISCSI_INT, .conn_only = 0, }, { .param =ISCSI_PARAM_DATASEQ_INORDER_EN, .value = &session->dataseq_inorder_en, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_ERL, .value = &zero, /* FIXME: session->erl */ .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_IFMARKER_EN, .value = &zero,/* FIXME: session->ifmarker_en */ .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_OFMARKER_EN, .value = &zero,/* FIXME: session->ofmarker_en */ .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_EXP_STATSN, .value = &conn->exp_statsn, .type = ISCSI_INT, .conn_only = 1, }, { .param = ISCSI_PARAM_TARGET_NAME, .conn_only = 0, .type = ISCSI_STRING, .value = session->target_name, }, { .param = ISCSI_PARAM_TPGT, .value = &session->portal_group_tag, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_PERSISTENT_ADDRESS, .value = session->nrec.conn[conn->id].address, .type = ISCSI_STRING, .conn_only = 1, }, { .param = ISCSI_PARAM_PERSISTENT_PORT, .value = &session->nrec.conn[conn->id].port, .type = ISCSI_INT, .conn_only = 1, }, { .param = ISCSI_PARAM_SESS_RECOVERY_TMO, .value = &session->replacement_timeout, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_USERNAME, .value = session->username, .type = ISCSI_STRING, .conn_only = 0, }, { .param = ISCSI_PARAM_USERNAME_IN, .value = session->username_in, .type = ISCSI_STRING, .conn_only = 0, }, { .param = ISCSI_PARAM_PASSWORD, .value = session->password, .type = ISCSI_STRING, .conn_only = 0, }, { .param = ISCSI_PARAM_PASSWORD_IN, .value = session->password_in, .type = ISCSI_STRING, .conn_only = 0, }, { .param = ISCSI_PARAM_FAST_ABORT, .value = &session->fast_abort, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_ABORT_TMO, .value = &session->abort_timeout, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_LU_RESET_TMO, .value = &session->lu_reset_timeout, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_TGT_RESET_TMO, .value = &session->tgt_reset_timeout, .type = ISCSI_INT, .conn_only = 0, }, { .param = ISCSI_PARAM_PING_TMO, .value = &conn->noop_out_timeout, .type = ISCSI_INT, .conn_only = 1, }, { .param = ISCSI_PARAM_RECV_TMO, .value = &conn->noop_out_interval, .type = ISCSI_INT, .conn_only = 1, }, { .param = ISCSI_PARAM_IFACE_NAME, .value = session->nrec.iface.name, .type = ISCSI_STRING, }, { .param = ISCSI_PARAM_INITIATOR_NAME, .value = session->initiator_name, .type = ISCSI_STRING, }, }; session->param_mask = ~0ULL; if (!(t->caps & CAP_MULTI_R2T)) session->param_mask &= ~ISCSI_MAX_R2T; if (!(t->caps & CAP_HDRDGST)) session->param_mask &= ~ISCSI_HDRDGST_EN; if (!(t->caps & CAP_DATADGST)) session->param_mask &= ~ISCSI_DATADGST_EN; if (!(t->caps & CAP_MARKERS)) { session->param_mask &= ~ISCSI_IFMARKER_EN; session->param_mask &= ~ISCSI_OFMARKER_EN; } /* some llds will send nops internally */ if (!iscsi_sysfs_session_supports_nop(session->id)) { session->param_mask &= ~ISCSI_PING_TMO; session->param_mask &= ~ISCSI_RECV_TMO; } /* Entered full-feature phase! */ for (i = 0; i < MAX_SESSION_PARAMS; i++) { if (conn->id != 0 && !conntbl[i].conn_only) continue; if (!(session->param_mask & (1ULL << conntbl[i].param))) continue; rc = ipc->set_param(session->t->handle, session->id, conn->id, conntbl[i].param, conntbl[i].value, conntbl[i].type); if (rc && rc != -ENOSYS) { log_error("can't set operational parameter %d for " "connection %d:%d, retcode %d (%d)", conntbl[i].param, session->id, conn->id, rc, errno); return EPERM; } if (rc == -ENOSYS) { switch (conntbl[i].param) { case ISCSI_PARAM_PING_TMO: /* * older kernels may not support nops * in kernel */ conn->userspace_nop = 1; break; #if 0 TODO handle this case ISCSI_PARAM_INITIATOR_NAME: /* use host level one instead */ hosttbl[ISCSI_HOST_PARAM_INITIATOR_NAME].set = 1; break; #endif } } print_param_value(conntbl[i].param, conntbl[i].value, conntbl[i].type); } return 0; } int iscsi_host_set_net_params(struct iface_rec *iface, struct iscsi_session *session) { struct iscsi_transport *t = session->t; int rc = 0; char *netdev; struct host_info hinfo; log_debug(3, "setting iface %s, dev %s, set ip %s, hw %s, " "transport %s.\n", iface->name, iface->netdev, iface->ipaddress, iface->hwaddress, iface->transport_name); if (!t->template->set_host_ip) return 0; /* if we need to set the ip addr then set all the iface net settings */ if (!iface_is_bound_by_ipaddr(iface)) { log_warning("Please set the iface.ipaddress for iface %s, " "then retry the login command.\n", iface->name); return EINVAL; } /* these type of drivers need the netdev upd */ if (strlen(iface->netdev)) netdev = iface->netdev; else { memset(&hinfo, 0, sizeof(hinfo)); hinfo.host_no = session->hostno; iscsi_sysfs_get_hostinfo_by_host_no(&hinfo); netdev = hinfo.iface.netdev; } if (net_ifup_netdev(netdev)) log_warning("Could not brining up netdev %s. Try running " "'ifup %s' first if login fails.", netdev, netdev); rc = host_set_param(t, session->hostno, ISCSI_HOST_PARAM_IPADDRESS, iface->ipaddress, ISCSI_STRING); if (rc) return rc; if (iface_is_bound_by_netdev(iface)) { rc = host_set_param(t, session->hostno, ISCSI_HOST_PARAM_NETDEV_NAME, iface->netdev, ISCSI_STRING); if (rc) return rc; } if (iface_is_bound_by_hwaddr(iface)) { rc = host_set_param(t, session->hostno, ISCSI_HOST_PARAM_HWADDRESS, iface->hwaddress, ISCSI_STRING); if (rc) return rc; } return 0; } open-iscsi-2.0.873/usr/io.c000066400000000000000000000517321175631155400153500ustar00rootroot00000000000000/* * iSCSI I/O Library * * Copyright (C) 2002 Cisco Systems, Inc. * maintained by linux-iscsi-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "types.h" #include "iscsi_proto.h" #include "iscsi_settings.h" #include "initiator.h" #include "iscsi_ipc.h" #include "log.h" #include "transport.h" #include "idbm.h" #include "iface.h" #include "sysdeps.h" #define LOG_CONN_CLOSED(conn) \ do { \ getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), \ conn->host, sizeof(conn->host), NULL, 0, NI_NUMERICHOST); \ log_error("Connection to Discovery Address %s closed", conn->host); \ } while (0) #define LOG_CONN_FAIL(conn) \ do { \ getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), \ conn->host, sizeof(conn->host), NULL, 0, NI_NUMERICHOST); \ log_error("Connection to Discovery Address %s failed", conn->host); \ } while (0) static int timedout; static void sigalarm_handler(int unused) { timedout = 1; } static void set_non_blocking(int fd) { int res = fcntl(fd, F_GETFL); if (res != -1) { res = fcntl(fd, F_SETFL, res | O_NONBLOCK); if (res) log_warning("unable to set fd flags (%s)!", strerror(errno)); } else log_warning("unable to get fd flags (%s)!", strerror(errno)); } #if 0 /* not used by anyone */ static int get_hwaddress_from_netdev(char *netdev, char *hwaddress) { struct ifaddrs *ifap, *ifa; struct sockaddr_in *s4; struct sockaddr_in6 *s6; struct ifreq if_hwaddr; int found = 0, sockfd; unsigned char *hwaddr; char buf[INET6_ADDRSTRLEN]; if (getifaddrs(&ifap)) { log_error("Could not match hwaddress %s to netdev. " "getifaddrs failed %d", hwaddress, errno); return 0; } /* Open a basic socket. */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { log_error("Could not open socket for ioctl."); goto free_ifap; } for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; switch (ifa->ifa_addr->sa_family) { case AF_INET: s4 = (struct sockaddr_in *)(ifa->ifa_addr); if (!inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, INET_ADDRSTRLEN)) continue; log_debug(4, "name %s addr %s\n", ifa->ifa_name, buf); break; case AF_INET6: s6 = (struct sockaddr_in6 *)(ifa->ifa_addr); if (!inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s6->sin6_addr), buf, INET6_ADDRSTRLEN)) continue; log_debug(4, "name %s addr %s\n", ifa->ifa_name, buf); break; default: continue; } if (strcmp(ifa->ifa_name, netdev)) continue; strncpy(if_hwaddr.ifr_name, ifa->ifa_name, IFNAMSIZ); if (ioctl(sockfd, SIOCGIFHWADDR, &if_hwaddr) < 0) { log_error("Could not match %s to netdevice.", hwaddress); continue; } /* check for ARPHRD_ETHER (ethernet) */ if (if_hwaddr.ifr_hwaddr.sa_family != 1) continue; hwaddr = (unsigned char *)if_hwaddr.ifr_hwaddr.sa_data; memset(hwaddress, 0, ISCSI_MAX_IFACE_LEN); /* TODO should look and covert so we do not need tmp buf */ sprintf(hwaddress, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); log_debug(4, "Found hardware address %s", hwaddress); found = 1; break; } close(sockfd); free_ifap: freeifaddrs(ifap); return found; } #endif #if 0 This is not supported for now, because it is not exactly what we want. It also turns out that targets will send packets to other interfaces causing all types of weird things to happen. static int bind_src_by_address(int sockfd, char *address) { int rc = 0; char port[NI_MAXSERV]; struct sockaddr_storage saddr; memset(&saddr, 0, sizeof(struct sockaddr_storage)); if (resolve_address(address, port, &saddr)) { log_error("Could not bind %s to conn.", address); return -1; } switch (saddr.ss_family) { case AF_INET: rc = bind(sockfd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in)); break; case AF_INET6: rc = bind(sockfd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in6)); break; default: rc = -1; } if (rc) log_error("Could not bind %s to %d.", address, sockfd); else log_debug(4, "Bound %s to socket fd %d", address, sockfd); return rc; } #endif static int bind_conn_to_iface(iscsi_conn_t *conn, struct iface_rec *iface) { struct iscsi_session *session = conn->session; if (strcmp(iface->transport_name, DEFAULT_TRANSPORT)) return 0; memset(session->netdev, 0, IFNAMSIZ); if (iface_is_bound_by_hwaddr(iface)) { if (net_get_netdev_from_hwaddress(iface->hwaddress, session->netdev)) { log_error("Cannot match %s to net/scsi interface.", iface->hwaddress); return -1; } } else if (iface_is_bound_by_netdev(iface)) { strcpy(session->netdev, iface->netdev); } else if (iface_is_bound_by_ipaddr(iface)) { /* * we never supported this but now with offload having to * set the ip address in the iface, useris may forget to * set the offload's transport type and we end up here by * accident. */ log_error("Cannot bind %s to net/scsi interface. This is not " "supported with software iSCSI (iscsi_tcp).", iface->ipaddress); return -1; } if (strlen(session->netdev)) { struct ifreq ifr; log_debug(4, "Binding session %d to %s", session->id, session->netdev); memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, session->netdev, IFNAMSIZ); if (setsockopt(conn->socket_fd, SOL_SOCKET, SO_BINDTODEVICE, session->netdev, strlen(session->netdev) + 1) < 0) { log_error("Could not bind connection %d to %s\n", conn->id, session->netdev); return -1; } } return 0; } int iscsi_io_tcp_connect(iscsi_conn_t *conn, int non_blocking) { int rc, onearg; struct sockaddr_storage *ss = &conn->saddr; char serv[NI_MAXSERV]; /* create a socket */ conn->socket_fd = socket(ss->ss_family, SOCK_STREAM, IPPROTO_TCP); /* the trasport ep handle is used to bind with */ conn->transport_ep_handle = conn->socket_fd; if (conn->socket_fd < 0) { log_error("cannot create TCP socket"); return -1; } if (bind_conn_to_iface(conn, &conn->session->nrec.iface)) return -1; onearg = 1; rc = setsockopt(conn->socket_fd, IPPROTO_TCP, TCP_NODELAY, &onearg, sizeof (onearg)); if (rc < 0) { log_error("cannot set TCP_NODELAY option on socket"); close(conn->socket_fd); conn->socket_fd = -1; return rc; } /* optionally set the window sizes */ if (conn->tcp_window_size) { int window_size = conn->tcp_window_size; socklen_t arglen = sizeof (window_size); if (setsockopt(conn->socket_fd, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, sizeof (window_size)) < 0) { log_warning("failed to set TCP recv window size " "to %u", window_size); } else { if (getsockopt(conn->socket_fd, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, &arglen) >= 0) { log_debug(4, "set TCP recv window size to %u, " "actually got %u", conn->tcp_window_size, window_size); } } window_size = conn->tcp_window_size; arglen = sizeof (window_size); if (setsockopt(conn->socket_fd, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, sizeof (window_size)) < 0) { log_warning("failed to set TCP send window size " "to %u", window_size); } else { if (getsockopt(conn->socket_fd, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, &arglen) >= 0) { log_debug(4, "set TCP send window size to %u, " "actually got %u", conn->tcp_window_size, window_size); } } } /* * Build a TCP connection to the target */ getnameinfo((struct sockaddr *) ss, sizeof(*ss), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); log_debug(1, "connecting to %s:%s", conn->host, serv); if (non_blocking) set_non_blocking(conn->socket_fd); rc = connect(conn->socket_fd, (struct sockaddr *) ss, sizeof (*ss)); return rc; } int iscsi_io_tcp_poll(iscsi_conn_t *conn, int timeout_ms) { int rc; struct pollfd pdesc; char serv[NI_MAXSERV], lserv[NI_MAXSERV]; struct sockaddr_storage ss; socklen_t len; pdesc.fd = conn->socket_fd; pdesc.events = POLLOUT; rc = poll(&pdesc, 1, timeout_ms); if (rc == 0) return 0; if (rc < 0) { getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); log_error("cannot make connection to %s:%s (%s)", conn->host, serv, strerror(errno)); return rc; } len = sizeof(int); if (getsockopt(conn->socket_fd, SOL_SOCKET, SO_ERROR, (char *) &rc, &len) < 0) { log_error("getsockopt for connect poll failed\n"); return -1; } if (rc) { getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); log_error("connect to %s:%s failed (%s)\n", conn->host, serv, strerror(rc)); return -rc; } len = sizeof(ss); if (log_level > 0 && getsockname(conn->socket_fd, (struct sockaddr *) &ss, &len) >= 0) { getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); getnameinfo((struct sockaddr *) &ss, sizeof(ss), NULL, 0, lserv, sizeof(lserv), NI_NUMERICSERV); log_debug(1, "connected local port %s to %s:%s", lserv, conn->host, serv); } return 1; } void iscsi_io_tcp_disconnect(iscsi_conn_t *conn) { if (conn->socket_fd >= 0) { log_debug(1, "disconnecting conn %p, fd %d", conn, conn->socket_fd); close(conn->socket_fd); conn->socket_fd = -1; } } int iscsi_io_connect(iscsi_conn_t *conn) { int rc, ret; struct sigaction action; struct sigaction old; /* set a timeout, since the socket calls may take a long time to * timeout on their own */ memset(&action, 0, sizeof (struct sigaction)); memset(&old, 0, sizeof (struct sigaction)); action.sa_sigaction = NULL; action.sa_flags = 0; action.sa_handler = sigalarm_handler; sigaction(SIGALRM, &action, &old); timedout = 0; alarm(conn->login_timeout); /* perform blocking TCP connect operation when no async request * associated. SendTargets Discovery know to work in such a mode. */ rc = iscsi_io_tcp_connect(conn, 0); if (timedout) { log_error("connect to %s timed out", conn->host); log_debug(1, "socket %d connect timed out", conn->socket_fd); ret = 0; goto done; } else if (rc < 0) { log_error("cannot make connection to %s: %s", conn->host, strerror(errno)); close(conn->socket_fd); ret = 0; goto done; } else if (log_level > 0) { struct sockaddr_storage ss; char lserv[NI_MAXSERV]; char serv[NI_MAXSERV]; socklen_t salen = sizeof(ss); if (getsockname(conn->socket_fd, (struct sockaddr *) &ss, &salen) >= 0) { getnameinfo((struct sockaddr *) &conn->saddr, sizeof(conn->saddr), conn->host, sizeof(conn->host), serv, sizeof(serv), NI_NUMERICHOST|NI_NUMERICSERV); getnameinfo((struct sockaddr *) &ss, sizeof(ss), NULL, 0, lserv, sizeof(lserv), NI_NUMERICSERV); log_debug(1, "connected local port %s to %s:%s", lserv, conn->host, serv); } } ret = 1; done: alarm(0); sigaction(SIGALRM, &old, NULL); return ret; } void iscsi_io_disconnect(iscsi_conn_t *conn) { iscsi_io_tcp_disconnect(conn); } static void iscsi_log_text(struct iscsi_hdr *pdu, char *data) { int dlength = ntoh24(pdu->dlength); char *text = data; char *end = text + dlength; while (text && (text < end)) { log_debug(4, "> %s", text); text += strlen(text); while ((text < end) && (*text == '\0')) text++; } } int iscsi_io_send_pdu(iscsi_conn_t *conn, struct iscsi_hdr *hdr, int hdr_digest, char *data, int data_digest, int timeout) { int rc, ret = 0; char *header = (char *) hdr; char *end; char pad[4]; struct iovec vec[3]; int pad_bytes; int pdu_length = sizeof (*hdr) + hdr->hlength + ntoh24(hdr->dlength); int remaining; struct sigaction action; struct sigaction old; iscsi_session_t *session = conn->session; /* set a timeout, since the socket calls may take a long time * to timeout on their own */ if (!session->use_ipc) { memset(&action, 0, sizeof (struct sigaction)); memset(&old, 0, sizeof (struct sigaction)); action.sa_sigaction = NULL; action.sa_flags = 0; action.sa_handler = sigalarm_handler; sigaction(SIGALRM, &action, &old); timedout = 0; alarm(timeout); } memset(&pad, 0, sizeof (pad)); memset(&vec, 0, sizeof (vec)); switch (hdr->opcode & ISCSI_OPCODE_MASK) { case ISCSI_OP_LOGIN:{ struct iscsi_login *login_hdr = (struct iscsi_login *) hdr; log_debug(4, "sending login PDU with current stage " "%d, next stage %d, transit 0x%x, isid" " 0x%02x%02x%02x%02x%02x%02x exp_statsn %u", ISCSI_LOGIN_CURRENT_STAGE(login_hdr->flags), ISCSI_LOGIN_NEXT_STAGE(login_hdr->flags), login_hdr->flags & ISCSI_FLAG_LOGIN_TRANSIT, login_hdr->isid[0], login_hdr->isid[1], login_hdr->isid[2], login_hdr->isid[3], login_hdr->isid[4], login_hdr->isid[5], ntohl(login_hdr->exp_statsn)); iscsi_log_text(hdr, data); break; } case ISCSI_OP_TEXT:{ struct iscsi_text *text_hdr = (struct iscsi_text *) hdr; log_debug(4, "sending text pdu with CmdSN %x, exp_statsn %u", ntohl(text_hdr->cmdsn), ntohl(text_hdr->cmdsn)); iscsi_log_text(hdr, data); break; } case ISCSI_OP_NOOP_OUT:{ struct iscsi_nopout *nopout_hdr = (struct iscsi_nopout *) hdr; log_debug(4, "sending Nop-out pdu with ttt %x, CmdSN %x:", ntohl(nopout_hdr->ttt), ntohl(nopout_hdr->cmdsn)); iscsi_log_text(hdr, data); break; } default: log_debug(4, "sending pdu opcode 0x%x:", hdr->opcode); break; } /* send the PDU header */ header = (char *) hdr; end = header + sizeof (*hdr) + hdr->hlength; /* send all the data and any padding */ if (pdu_length % ISCSI_PAD_LEN) pad_bytes = ISCSI_PAD_LEN - (pdu_length % ISCSI_PAD_LEN); else pad_bytes = 0; if (session->use_ipc) ipc->send_pdu_begin(session->t->handle, session->id, conn->id, end - header, ntoh24(hdr->dlength) + pad_bytes); while (header < end) { vec[0].iov_base = header; vec[0].iov_len = end - header; if (!session->use_ipc) rc = writev(conn->socket_fd, vec, 1); else rc = ipc->writev(0, vec, 1); if (timedout) { log_error("socket %d write timed out", conn->socket_fd); ret = 0; goto done; } else if ((rc <= 0) && (errno != EAGAIN)) { LOG_CONN_FAIL(conn); ret = 0; goto done; } else if (rc > 0) { log_debug(4, "wrote %d bytes of PDU header", rc); header += rc; } } end = data + ntoh24(hdr->dlength); remaining = ntoh24(hdr->dlength) + pad_bytes; while (remaining > 0) { vec[0].iov_base = data; vec[0].iov_len = end - data; vec[1].iov_base = (void *) &pad; vec[1].iov_len = pad_bytes; if (!session->use_ipc) rc = writev(conn->socket_fd, vec, 2); else rc = ipc->writev(0, vec, 2); if (timedout) { log_error("socket %d write timed out", conn->socket_fd); ret = 0; goto done; } else if ((rc <= 0) && (errno != EAGAIN)) { LOG_CONN_FAIL(conn); ret = 0; goto done; } else if (rc > 0) { log_debug(4, "wrote %d bytes of PDU data", rc); remaining -= rc; if (data < end) { data += rc; if (data > end) data = end; } } } if (session->use_ipc) { if (ipc->send_pdu_end(session->t->handle, session->id, conn->id, &rc)) { ret = 0; goto done; } } ret = 1; done: if (!session->use_ipc) { alarm(0); sigaction(SIGALRM, &old, NULL); timedout = 0; } return ret; } int iscsi_io_recv_pdu(iscsi_conn_t *conn, struct iscsi_hdr *hdr, int hdr_digest, char *data, int max_data_length, int data_digest, int timeout) { uint32_t h_bytes = 0; uint32_t ahs_bytes = 0; uint32_t d_bytes = 0; uint32_t ahslength = 0; uint32_t dlength = 0; uint32_t pad = 0; int rlen = 0; int failed = 0; char *header = (char *) hdr; char *end = data + max_data_length; struct sigaction action; struct sigaction old; iscsi_session_t *session = conn->session; memset(data, 0, max_data_length); /* set a timeout, since the socket calls may take a long * time to timeout on their own */ if (!session->use_ipc) { memset(&action, 0, sizeof (struct sigaction)); memset(&old, 0, sizeof (struct sigaction)); action.sa_sigaction = NULL; action.sa_flags = 0; action.sa_handler = sigalarm_handler; sigaction(SIGALRM, &action, &old); timedout = 0; alarm(timeout); } else { failed = ipc->recv_pdu_begin(conn); if (failed == -EAGAIN) return -EAGAIN; else if (failed < 0) { failed = 1; goto done; } } /* read a response header */ do { if (!session->use_ipc) rlen = read(conn->socket_fd, header, sizeof (*hdr) - h_bytes); else rlen = ipc->read(header, sizeof (*hdr) - h_bytes); if (timedout) { log_error("socket %d header read timed out", conn->socket_fd); failed = 1; goto done; } else if (rlen == 0) { LOG_CONN_CLOSED(conn); failed = 1; goto done; } else if ((rlen < 0) && (errno != EAGAIN)) { LOG_CONN_FAIL(conn); failed = 1; goto done; } else if (rlen > 0) { log_debug(4, "read %d bytes of PDU header", rlen); header += rlen; h_bytes += rlen; } } while (h_bytes < sizeof (*hdr)); log_debug(4, "read %d PDU header bytes, opcode 0x%x, dlength %u, " "data %p, max %u", h_bytes, hdr->opcode & ISCSI_OPCODE_MASK, ntoh24(hdr->dlength), data, max_data_length); /* check for additional headers */ ahslength = hdr->hlength; /* already includes padding */ if (ahslength) { log_warning("additional header segment length %u not supported", ahslength); failed = 1; goto done; } /* read exactly what we expect, plus padding */ dlength = hdr->dlength[0] << 16; dlength |= hdr->dlength[1] << 8; dlength |= hdr->dlength[2]; /* if we only expected to receive a header, exit */ if (dlength == 0) goto done; if (data + dlength > end) { log_warning("buffer size %u too small for data length %u", max_data_length, dlength); failed = 1; goto done; } /* read the rest into our buffer */ d_bytes = 0; while (d_bytes < dlength) { if (!session->use_ipc) rlen = read(conn->socket_fd, data + d_bytes, dlength - d_bytes); else rlen = ipc->read(data + d_bytes, dlength - d_bytes); if (timedout) { log_error("socket %d data read timed out", conn->socket_fd); failed = 1; goto done; } else if (rlen == 0) { LOG_CONN_CLOSED(conn); failed = 1; goto done; } else if ((rlen < 0 && errno != EAGAIN)) { LOG_CONN_FAIL(conn); failed = 1; goto done; } else if (rlen > 0) { log_debug(4, "read %d bytes of PDU data", rlen); d_bytes += rlen; } } /* handle PDU data padding. * data is padded in case of kernel_io */ pad = dlength % ISCSI_PAD_LEN; if (pad && !session->use_ipc) { int pad_bytes = pad = ISCSI_PAD_LEN - pad; char bytes[ISCSI_PAD_LEN]; while (pad_bytes > 0) { rlen = read(conn->socket_fd, &bytes, pad_bytes); if (timedout) { log_error("socket %d pad read timed out", conn->socket_fd); failed = 1; goto done; } else if (rlen == 0) { LOG_CONN_CLOSED(conn); failed = 1; goto done; } else if ((rlen < 0 && errno != EAGAIN)) { LOG_CONN_FAIL(conn); failed = 1; goto done; } else if (rlen > 0) { log_debug(4, "read %d pad bytes", rlen); pad_bytes -= rlen; } } } switch (hdr->opcode) { case ISCSI_OP_TEXT_RSP: log_debug(4, "finished reading text PDU, %u hdr, %u " "ah, %u data, %u pad", h_bytes, ahs_bytes, d_bytes, pad); iscsi_log_text(hdr, data); break; case ISCSI_OP_LOGIN_RSP:{ struct iscsi_login_rsp *login_rsp = (struct iscsi_login_rsp *) hdr; log_debug(4, "finished reading login PDU, %u hdr, " "%u ah, %u data, %u pad", h_bytes, ahs_bytes, d_bytes, pad); log_debug(4, "login current stage %d, next stage " "%d, transit 0x%x", ISCSI_LOGIN_CURRENT_STAGE(login_rsp->flags), ISCSI_LOGIN_NEXT_STAGE(login_rsp->flags), login_rsp->flags & ISCSI_FLAG_LOGIN_TRANSIT); iscsi_log_text(hdr, data); break; } case ISCSI_OP_ASYNC_EVENT: /* FIXME: log the event info */ break; default: break; } done: if (!session->use_ipc) { alarm(0); sigaction(SIGALRM, &old, NULL); } else { /* finalyze receive transaction */ if (ipc->recv_pdu_end(conn)) { failed = 1; } } if (timedout || failed) { timedout = 0; return -EIO; } return h_bytes + ahs_bytes + d_bytes; } open-iscsi-2.0.873/usr/ioctl.c000066400000000000000000000242661175631155400160550ustar00rootroot00000000000000/* * iSCSI Ioctl/Unix Interface * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include "iscsi_if.h" #include "iscsid.h" #include "log.h" #include "iscsi_ipc.h" #define CTL_DEVICE "/dev/iscsictl" static int ctrl_fd; static void *xmitbuf = NULL; static int xmitlen = 0; static void *recvbuf = NULL; static int recvlen = 0; static void *ioctl_sendbuf; static void *ioctl_recvbuf; static void *pdu_sendbuf; #define IOCTL_BUF_DEFAULT_MAX \ (ISCSI_DEF_MAX_RECV_SEG_LEN + sizeof(struct iscsi_hdr)) #define PDU_SENDBUF_DEFAULT_MAX \ (ISCSI_DEF_MAX_RECV_SEG_LEN + sizeof(struct iscsi_hdr)) static int kread(char *data, int count) { log_debug(7, "in %s", __FUNCTION__); return count; } static int kwritev(enum iscsi_uevent_e type, struct iovec *iovp, int count) { log_debug(7, "in %s", __FUNCTION__); return 0; } /* * __kipc_call() should never block */ static int __kipc_call(void *iov_base, int iov_len) { log_debug(7, "in %s", __FUNCTION__); return 0; } static int kcreate_session(uint64_t transport_handle, uint32_t initial_cmdsn, uint32_t *out_sid, uint32_t *out_hostno) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_CREATE_SESSION; ev.transport_handle = transport_handle; ev.u.c_session.initial_cmdsn = initial_cmdsn; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } if (!ev.r.c_session_ret.session_handle || ev.r.c_session_ret.sid < 0) return -EIO; *out_handle = ev.r.c_session_ret.session_handle; *out_sid = ev.r.c_session_ret.sid; return 0; } static int kdestroy_session(uint64_t transport_handle, uint64_t sessionh, uint32_t sid) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_DESTROY_SESSION; ev.transport_handle = transport_handle; ev.u.d_session.session_handle = sessionh; ev.u.d_session.sid = sid; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } return 0; } static int kcreate_conn(uint64_t transport_handle, uint64_t sessionh, uint32_t sid, uint32_t cid, uint64_t *out_handle) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_CREATE_CONN; ev.transport_handle = transport_handle; ev.u.c_conn.session_handle = sessionh; ev.u.c_conn.cid = cid; ev.u.c_conn.sid = sid; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } if (!ev.r.handle) return -EIO; *out_handle = ev.r.handle; return 0; } static int kdestroy_conn(uint64_t transport_handle, uint64_t connh, int cid) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_DESTROY_CONN; ev.transport_handle = transport_handle; ev.u.d_conn.conn_handle = connh; ev.u.d_conn.cid = cid; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } return 0; } static int kbind_conn(uint64_t transport_handle, uint64_t sessionh, uint64_t connh, uint32_t transport_fd, int is_leading, int *retcode) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_BIND_CONN; ev.transport_handle = transport_handle; ev.u.b_conn.session_handle = sessionh; ev.u.b_conn.conn_handle = connh; ev.u.b_conn.transport_fd = transport_fd; ev.u.b_conn.is_leading = is_leading; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } *retcode = ev.r.retcode; return 0; } static void ksend_pdu_begin(uint64_t transport_handle, uint64_t connh, int hdr_size, int data_size) { struct iscsi_uevent *ev; log_debug(7, "in %s", __FUNCTION__); if (xmitbuf) { log_error("send's begin state machine bug?"); exit(-EIO); } xmitbuf = pdu_sendbuf; memset(xmitbuf, 0, sizeof(*ev) + hdr_size + data_size); xmitlen = sizeof(*ev); ev = xmitbuf; memset(ev, 0, sizeof(*ev)); ev->type = ISCSI_UEVENT_SEND_PDU; ev->transport_handle = transport_handle; ev->u.send_pdu.conn_handle = connh; ev->u.send_pdu.hdr_size = hdr_size; ev->u.send_pdu.data_size = data_size; log_debug(3, "send PDU began for hdr %d bytes and data %d bytes", hdr_size, data_size); } static int ksend_pdu_end(uint64_t transport_handle, uint64_t connh, int *retcode) { int rc; struct iscsi_uevent *ev; struct iovec iov; log_debug(7, "in %s", __FUNCTION__); if (!xmitbuf) { log_error("send's end state machine bug?"); exit(-EIO); } ev = xmitbuf; if (ev->u.send_pdu.conn_handle != connh) { log_error("send's end state machine corruption?"); exit(-EIO); } iov.iov_base = xmitbuf; iov.iov_len = xmitlen; if ((rc = __kipc_call(xmitbuf, xmitlen)) < 0) goto err; if (ev->r.retcode) { *retcode = ev->r.retcode; goto err; } if (ev->type != ISCSI_UEVENT_SEND_PDU) { log_error("bad event: bug on send_pdu_end?"); exit(-EIO); } log_debug(3, "send PDU finished for conn (handle %p)", iscsi_ptr(connh)); xmitbuf = NULL; return 0; err: xmitbuf = NULL; xmitlen = 0; return rc; } static int kset_param(uint64_t transport_handle, uint64_t connh, enum iscsi_param param, uint32_t value, int *retcode) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_SET_PARAM; ev.transport_handle = transport_handle; ev.u.set_param.conn_handle = connh; ev.u.set_param.param = param; ev.u.set_param.value = value; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } *retcode = ev.r.retcode; return 0; } static int kstop_conn(uint64_t transport_handle, uint64_t connh, int flag) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_STOP_CONN; ev.transport_handle = transport_handle; ev.u.stop_conn.conn_handle = connh; ev.u.stop_conn.flag = flag; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } return 0; } static int kstart_conn(uint64_t transport_handle, uint64_t connh, int *retcode) { int rc; struct iscsi_uevent ev; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_START_CONN; ev.transport_handle = transport_handle; ev.u.start_conn.conn_handle = connh; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } *retcode = ev.r.retcode; return 0; } static int krecv_pdu_begin(uint64_t transport_handle, uint64_t connh, uintptr_t recv_handle, uintptr_t *pdu_handle, int *pdu_size) { log_debug(7, "in %s", __FUNCTION__); if (recvbuf) { log_error("recv's begin state machine bug?"); return -EIO; } recvbuf = (void*)recv_handle + sizeof(struct iscsi_uevent); recvlen = 0; *pdu_handle = recv_handle; log_debug(3, "recv PDU began, pdu handle 0x%p", (void*)*pdu_handle); return 0; } static int krecv_pdu_end(uint64_t transport_handle, uintptr_t conn_handle, uintptr_t pdu_handle) { log_debug(7, "in %s", __FUNCTION__); if (!recvbuf) { log_error("recv's end state machine bug?"); return -EIO; } log_debug(3, "recv PDU finished for pdu handle 0x%p", (void*)pdu_handle); recvpool_put((void*)conn_handle, (void*)pdu_handle); recvbuf = NULL; return 0; } static int ktrans_list(void) { struct iscsi_uevent ev; int rc; log_debug(7, "in %s", __FUNCTION__); memset(ev, 0, sizeof(struct iscsi_uevent)); /* * need to define this for bsd */ ev->type = ISCSI_UEVENT_TRANS_LIST; if ((rc = __kipc_call(&ev, sizeof(ev))) < 0) { return rc; } for (i = 0; i < ISCSI_TRANSPORT_MAX; i++) { if (ev.r.t_list.elements[i].trans_handle) { provider[i].handle = ev.r.t_list.elements[i].trans_handle; strncpy(provider[i].name, ev.r.t_list.elements[i].name, ISCSI_TRANSPORT_NAME_MAXLEN); provider[i].caps = ev.r.t_list.elements[i].caps; } } return 0; } static int ctldev_handle(void) { log_debug(7, "in %s", __FUNCTION__); return 0; } static int ctldev_open(void) { log_debug(7, "in %s", __FUNCTION__); ioctl_sendbuf = calloc(1, IOCTL_BUF_DEFAULT_MAX); if (!ioctl_sendbuf) { log_error("can not allocate ioctl_sendbuf"); return -1; } ioctl_recvbuf = calloc(1, IOCTL_BUF_DEFAULT_MAX); if (!ioctl_recvbuf) { free(ioctl_sendbuf); log_error("can not allocate ioctl_recvbuf"); return -1; } pdu_sendbuf = calloc(1, PDU_SENDBUF_DEFAULT_MAX); if (!pdu_sendbuf) { free(ioctl_recvbuf); free(ioctl_sendbuf); log_error("can not allocate ioctl_sendbuf"); return -1; } return ctrl_fd; } static void ctldev_close(void) { free(pdu_sendbuf); free(ioctl_recvbuf); free(ioctl_sendbuf); //close(ctrl_fd); } struct iscsi_ipc ioctl_ipc = { .name = "Open-iSCSI Kernel IPC/IOCTL v.1", .ctldev_bufmax = IOCTL_BUF_DEFAULT_MAX, .ctldev_open = ctldev_open, .ctldev_close = ctldev_close, .ctldev_handle = ctldev_handle, .trans_list = ktrans_list, .create_session = kcreate_session, .destroy_session = kdestroy_session, .create_conn = kcreate_conn, .destroy_conn = kdestroy_conn, .bind_conn = kbind_conn, .set_param = kset_param, .get_param = NULL, .start_conn = kstart_conn, .stop_conn = kstop_conn, .writev = kwritev, .send_pdu_begin = ksend_pdu_begin, .send_pdu_end = ksend_pdu_end, .read = kread, .recv_pdu_begin = krecv_pdu_begin, .recv_pdu_end = krecv_pdu_end, }; struct iscsi_ipc *ipc = &ioctl_ipc; open-iscsi-2.0.873/usr/iscsi_err.c000066400000000000000000000045071175631155400167210ustar00rootroot00000000000000/* * iSCSI error helpers * * Copyright (C) 2011 Mike Christie * Copyright (C) 2011 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include "stdlib.h" #include "iscsi_err.h" #include "log.h" static char *iscsi_err_msgs[] = { /* 0 */ "", /* 1 */ "unknown error", /* 2 */ "session not found", /* 3 */ "no available memory", /* 4 */ "encountered connection failure", /* 5 */ "encountered iSCSI login failure", /* 6 */ "encountered iSCSI database failure", /* 7 */ "invalid parameter", /* 8 */ "connection timed out", /* 9 */ "internal error", /* 10 */ "encountered iSCSI logout failure", /* 11 */ "iSCSI PDU timed out", /* 12 */ "iSCSI driver not found. Please make sure it is loaded, and retry the operation", /* 13 */ "daemon access denied", /* 14 */ "iSCSI driver does not support requested capability.", /* 15 */ "session exists", /* 16 */ "Unknown request", /* 17 */ "iSNS service not supported", /* 18 */ "could not communicate to iscsid", /* 19 */ "encountered non-retryable iSCSI login failure", /* 20 */ "could not connect to iscsid", /* 21 */ "no objects found", /* 22 */ "sysfs lookup failure", /* 23 */ "host not found", /* 24 */ "iSCSI login failed due to authorization failure", /* 25 */ "iSNS query failed", /* 26 */ "iSNS registration failed", /* 27 */ "operation not supported", /* 28 */ "device or resource in use", }; char *iscsi_err_to_str(int err) { if (err >= ISCSI_MAX_ERR_VAL || err < 0) { log_error("invalid error code %d", err); return NULL; } return iscsi_err_msgs[err]; } void iscsi_err_print_msg(int err) { if (err >= ISCSI_MAX_ERR_VAL || err < 0) { log_error("invalid error code %d", err); return; } log_error("initiator reported error (%d - %s)", err, iscsi_err_msgs[err]); } open-iscsi-2.0.873/usr/iscsi_ipc.h000066400000000000000000000110531175631155400167030ustar00rootroot00000000000000/* * User/Kernel Transport IPC API Ioctl/NETLINK/etc * * Copyright (C) 2005 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. * * NOTE: OSes must implement this API in terms of user's control-plane re-use. */ #ifndef ISCSI_IPC_H #define ISCSI_IPC_H #if defined(FreeBSD) #include #endif #include "iscsi_if.h" enum { ISCSI_INT, ISCSI_STRING, }; struct iscsi_conn; struct iscsi_ev_context; /* * When handling async events, the initiator may not be able to * handle the event in the same context, so this allows the interface * code to call into the initiator to shedule handling. */ struct iscsi_ipc_ev_clbk { void (*create_session) (uint32_t host_no, uint32_t sid); void (*destroy_session) (uint32_t host_no, uint32_t sid); struct iscsi_ev_context *(*get_ev_context) (struct iscsi_conn *conn, int ev_size); void (*put_ev_context) (struct iscsi_ev_context *ev_context); int (*sched_ev_context) (struct iscsi_ev_context *ev_context, struct iscsi_conn *conn, unsigned long tmo, int event); }; extern void ipc_register_ev_callback(struct iscsi_ipc_ev_clbk *ipc_ev_clbk); /** * struct iscsi_ipc - Open-iSCSI Interface for Kernel IPC * * All functions allowed to return POSIX kind of error. i.e. 0 - OK, non-zero * means IPC error and errno set. */ struct iscsi_ipc { char *name; int ctldev_bufmax; int (*ctldev_open) (void); void (*ctldev_close) (void); int (*ctldev_handle) (void); int (*sendtargets) (uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr); int (*create_session) (uint64_t transport_handle, uint64_t ep_handle, uint32_t initial_cmdsn, uint16_t cmds_max, uint16_t qdepth, uint32_t *out_sid, uint32_t *hostno); int (*destroy_session) (uint64_t transport_handle, uint32_t sid); int (*unbind_session) (uint64_t transport_handle, uint32_t sid); int (*create_conn) (uint64_t transport_handle, uint32_t sid, uint32_t cid, uint32_t *out_cid); int (*destroy_conn) (uint64_t transport_handle, uint32_t sid, uint32_t cid); int (*bind_conn) (uint64_t transport_handle, uint32_t sid, uint32_t cid, uint64_t transport_eph, int is_leading, int *retcode); int (*set_param) (uint64_t transport_handle, uint32_t sid, uint32_t cid, enum iscsi_param param, void *value, int type); int (*set_host_param) (uint64_t transport_handle, uint32_t host_no, enum iscsi_host_param param, void *value, int type); /* not implemented yet */ int (*get_param) (uint64_t transport_handle, uint32_t sid, uint32_t cid, enum iscsi_param param, uint32_t *value, int *retcode); int (*get_stats) (uint64_t transport_handle, uint32_t sid, uint32_t cid, char *statsbuf, int statsbuf_max); int (*start_conn) (uint64_t transport_handle, uint32_t sid, uint32_t cid, int *retcode); int (*stop_conn) (uint64_t transport_handle, uint32_t sid, uint32_t cid, int flag); int (*read) (char *data, int count); void (*send_pdu_begin) (uint64_t transport_handle, uint32_t sid, uint32_t cid, int hdr_size, int data_size); int (*send_pdu_end) (uint64_t transport_handle, uint32_t sid, uint32_t cid, int *retcode); int (*writev) (enum iscsi_uevent_e type, struct iovec *iovp, int count); int (*recv_pdu_begin) (struct iscsi_conn *conn); int (*recv_pdu_end) (struct iscsi_conn *conn); int (*set_net_config) (uint64_t transport_handle, uint32_t host_no, struct iovec *iovs, uint32_t param_count); int (*recv_conn_state) (struct iscsi_conn *conn, uint32_t *state); int (*exec_ping) (uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr, uint32_t iface_num, uint32_t iface_type, uint32_t size, uint32_t *status); int (*get_chap) (uint64_t transport_handle, uint32_t host_no, uint16_t chap_tbl_idx, uint32_t num_entries, char *chap_buf, uint32_t *valid_chap_entries); int (*delete_chap) (uint64_t transport_handle, uint32_t host_no, uint16_t chap_tbl_idx); }; #endif /* ISCSI_IPC_H */ open-iscsi-2.0.873/usr/iscsi_net_util.c000066400000000000000000000225271175631155400177560ustar00rootroot00000000000000/* * net helpers * * Copyright (C) 2010 Mike Christie * Copyright (C) 2010 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "sysdeps.h" #include "ethtool-copy.h" #include "iscsi_net_util.h" #include "log.h" struct iscsi_net_driver { const char *net_drv_name; const char *iscsi_transport; }; static struct iscsi_net_driver net_drivers[] = { {"cxgb3", "cxgb3i" }, {"cxgb4", "cxgb4i" }, {"bnx2", "bnx2i" }, {"bnx2x", "bnx2i"}, {NULL, NULL} }; /** * net_get_transport_name_from_netdev - get name of transport to use for iface * @netdev: netdev iface name * @transport: buffer to hold transport name * * transport buffer should be ISCSI_TRANSPORT_NAME_MAXLEN bytes */ int net_get_transport_name_from_netdev(char *netdev, char *transport) { struct ethtool_drvinfo drvinfo; struct ifreq ifr; int err, fd, i; memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, netdev); fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { log_error("Could not open socket for ioctl."); return errno; } drvinfo.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (caddr_t)&drvinfo; err = ioctl(fd, SIOCETHTOOL, &ifr); if (err < 0) { log_error("Could not get driver %s.", netdev); err = errno; goto close_sock; } for (i = 0; net_drivers[i].net_drv_name != NULL; i++) { struct iscsi_net_driver *net_driver = &net_drivers[i]; if (!strcmp(net_driver->net_drv_name, drvinfo.driver)) { strcpy(transport, net_driver->iscsi_transport); err = 0; goto close_sock; } } err = ENODEV; close_sock: close(fd); return err; } /** * net_get_netdev_from_hwaddress - given a hwaddress return the ethX * @hwaddress: hw address no larger than ISCSI_HWADDRESS_BUF_SIZE * @netdev: buffer of IFNAMSIZ size that will hold the ethX * * Does not support interfaces like a bond or alias because * multiple interfaces will have the same hwaddress. */ int net_get_netdev_from_hwaddress(char *hwaddress, char *netdev) { struct if_nameindex *ifni; struct ifreq if_hwaddr; int found = 0, sockfd, i = 0; unsigned char *hwaddr; char tmp_hwaddress[ISCSI_HWADDRESS_BUF_SIZE]; ifni = if_nameindex(); if (ifni == NULL) { log_error("Could not match hwaddress %s to netdev. " "getifaddrs failed %d", hwaddress, errno); return errno; } /* Open a basic socket. */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { log_error("Could not open socket for ioctl."); goto free_ifni; } for (i = 0; ifni[i].if_index && ifni[i].if_name; i++) { struct if_nameindex *n = &ifni[i]; strlcpy(if_hwaddr.ifr_name, n->if_name, IFNAMSIZ); if (ioctl(sockfd, SIOCGIFHWADDR, &if_hwaddr) < 0) { log_error("Could not match %s to netdevice.", hwaddress); continue; } /* check for ARPHRD_ETHER (ethernet) */ if (if_hwaddr.ifr_hwaddr.sa_family != 1) continue; hwaddr = (unsigned char *)if_hwaddr.ifr_hwaddr.sa_data; memset(tmp_hwaddress, 0, ISCSI_HWADDRESS_BUF_SIZE); /* TODO should look and covert so we do not need tmp buf */ sprintf(tmp_hwaddress, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); log_debug(4, "Found hardware address %s", tmp_hwaddress); if (!strcasecmp(tmp_hwaddress, hwaddress)) { log_debug(4, "Matches %s to %s", hwaddress, n->if_name); memset(netdev, 0, IFNAMSIZ); strlcpy(netdev, n->if_name, IFNAMSIZ); found = 1; break; } } close(sockfd); free_ifni: if_freenameindex(ifni); if (!found) return ENODEV; return 0; } /** * net_setup_netdev - bring up NIC * @netdev: network device name * @local: ip address for netdev * @mask: net mask * @gateway: gateway * @remote_ip: target portal ip * @needs_bringup: bool indicating if the netdev needs to be started * * Bring up required NIC and use routing * to force iSCSI traffic through correct NIC. */ int net_setup_netdev(char *netdev, char *local_ip, char *mask, char *gateway, char *remote_ip, int needs_bringup) { struct sockaddr_in sk_ipaddr = { .sin_family = AF_INET }; struct sockaddr_in sk_netmask = { .sin_family = AF_INET }; struct sockaddr_in sk_hostmask = { .sin_family = AF_INET }; struct sockaddr_in sk_gateway = { .sin_family = AF_INET }; struct sockaddr_in sk_tgt_ipaddr = { .sin_family = AF_INET }; struct rtentry rt; struct ifreq ifr; int sock; int ret; if (!strlen(netdev)) { log_error("No netdev name in fw entry.\n"); return EINVAL; } /* Create socket for making networking changes */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { log_error("Could not open socket to manage network " "(err %d - %s)", errno, strerror(errno)); return errno; } /* Bring up NIC with correct address - unless it * has already been handled (2 targets in IBFT may share one NIC) */ if (!inet_aton(local_ip, &sk_ipaddr.sin_addr)) { log_error("Invalid or missing ipaddr in fw entry\n"); ret = EINVAL; goto done; } if (!inet_aton(mask, &sk_netmask.sin_addr)) { log_error("Invalid or missing netmask in fw entry\n"); ret = EINVAL; goto done; } inet_aton("255.255.255.255", &sk_hostmask.sin_addr); if (!inet_aton(remote_ip, &sk_tgt_ipaddr.sin_addr)) { log_error("Invalid or missing target ipaddr in fw entry\n"); ret = EINVAL; goto done; } /* Only set IP/NM if this is a new interface */ if (needs_bringup) { /* TODO: create vlan if strlen(vlan) */ /* Bring up interface */ memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, netdev, IFNAMSIZ); ifr.ifr_flags = IFF_UP | IFF_RUNNING; if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { log_error("Could not bring up netdev %s (err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } /* Set IP address */ memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, netdev, IFNAMSIZ); memcpy(&ifr.ifr_addr, &sk_ipaddr, sizeof(struct sockaddr)); if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) { log_error("Could not set ip for %s (err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } /* Set netmask */ memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, netdev, IFNAMSIZ); memcpy(&ifr.ifr_addr, &sk_netmask, sizeof(struct sockaddr)); if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) { log_error("Could not set ip for %s (err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } } /* Set static route to target via this interface */ memset((char *) &rt, 0, sizeof(rt)); memcpy(&rt.rt_dst, &sk_tgt_ipaddr, sizeof(sk_tgt_ipaddr)); memcpy(&rt.rt_genmask, &sk_hostmask, sizeof(sk_hostmask)); rt.rt_flags = RTF_UP | RTF_HOST; rt.rt_dev = netdev; if ((sk_tgt_ipaddr.sin_addr.s_addr & sk_netmask.sin_addr.s_addr) == (sk_ipaddr.sin_addr.s_addr & sk_netmask.sin_addr.s_addr)) { /* Same subnet */ if (ioctl(sock, SIOCADDRT, &rt) < 0) { if (errno != EEXIST) { log_error("Could not set ip for %s " "(err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } } } else { /* Different subnet. Use gateway */ rt.rt_flags |= RTF_GATEWAY; if (!inet_aton(gateway, &sk_gateway.sin_addr)) { log_error("Invalid or missing gateway for %s " "(err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } memcpy(&rt.rt_gateway, &sk_gateway, sizeof(sk_gateway)); if (ioctl(sock, SIOCADDRT, &rt) < 0) { if (errno != EEXIST) { log_error("Could not set gateway for %s " "(err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } } } ret = 0; done: close(sock); return ret; } /** * net_ifup_netdev - bring up network interface * @netdev: netdevice to bring up. */ int net_ifup_netdev(char *netdev) { struct ifreq ifr; int sock; int ret = 0; if (!strlen(netdev)) { log_error("No netdev name in fw entry.\n"); return EINVAL; } /* Create socket for making networking changes */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { log_error("Could not open socket to manage network " "(err %d - %s)", errno, strerror(errno)); return errno; } memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, netdev, IFNAMSIZ); if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { log_error("Could not bring up netdev %s (err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } if (ifr.ifr_flags & IFF_UP) { log_debug(3, "%s up\n", netdev); goto done; } log_debug(3, "bringing %s up\n", netdev); /* Bring up interface */ memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, netdev, IFNAMSIZ); ifr.ifr_flags = IFF_UP; if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { log_error("Could not bring up netdev %s (err %d - %s)", netdev, errno, strerror(errno)); ret = errno; goto done; } done: close(sock); return ret; } open-iscsi-2.0.873/usr/iscsi_netlink.h000066400000000000000000000021241175631155400175730ustar00rootroot00000000000000/* * iSCSI Netlink attr helpers * * Copyright (C) 2011 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_NLA_H #define ISCSI_NLA_H #include struct iovec; #define ISCSI_NLA_HDRLEN ((int) NLA_ALIGN(sizeof(struct nlattr))) #define ISCSI_NLA_DATA(nla) ((void *)((char*)(nla) + ISCSI_NLA_HDRLEN)) #define ISCSI_NLA_LEN(len) ((len) + NLA_ALIGN(ISCSI_NLA_HDRLEN)) #define ISCSI_NLA_TOTAL_LEN(len) (NLA_ALIGN(ISCSI_NLA_LEN(len))) extern struct nlattr *iscsi_nla_alloc(uint16_t type, uint16_t len); #endif open-iscsi-2.0.873/usr/iscsi_settings.h000066400000000000000000000022251175631155400177710ustar00rootroot00000000000000/* * Default initiator settings. These may not be the same as * in the RFC. See iscsi_proto.h for those. */ /* timeouts in seconds */ #define DEF_LOGIN_TIMEO 30 #define DEF_LOGOUT_TIMEO 15 #define DEF_NOOP_OUT_INTERVAL 5 #define DEF_NOOP_OUT_TIMEO 5 #define DEF_REPLACEMENT_TIMEO 120 #define DEF_ABORT_TIMEO 15 #define DEF_LU_RESET_TIMEO 30 #define DEF_TGT_RESET_TIMEO 30 #define DEF_HOST_RESET_TIMEO 60 /* q depths */ #define CMDS_MAX 128 #define QUEUE_DEPTH 32 /* system */ #define XMIT_THREAD_PRIORITY -20 /* interface */ #define UNKNOWN_VALUE "" #define DEFAULT_IFACENAME "default" #define DEFAULT_NETDEV "default" #define DEFAULT_IPADDRESS "default" #define DEFAULT_HWADDRESS "default" #define DEFAULT_TRANSPORT "tcp" #define PORTAL_GROUP_TAG_UNKNOWN -1 /* default window size */ #define TCP_WINDOW_SIZE (512 * 1024) /* default iSCSI port number */ #define ISCSI_DEFAULT_PORT 3260 /* data and segment lengths in bytes */ #define DEF_INI_FIRST_BURST_LEN 262144 #define DEF_INI_MAX_BURST_LEN 16776192 #define DEF_INI_MAX_RECV_SEG_LEN 262144 #define DEF_INI_DISC_MAX_RECV_SEG_LEN 32768 /* login retries */ #define DEF_INITIAL_LOGIN_RETRIES_MAX 4 open-iscsi-2.0.873/usr/iscsi_sysfs.c000066400000000000000000001075721175631155400173060ustar00rootroot00000000000000/* * iSCSI sysfs * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "initiator.h" #include "transport.h" #include "idbm.h" #include "version.h" #include "iscsi_sysfs.h" #include "sysdeps.h" #include "iscsi_settings.h" #include "iface.h" #include "session_info.h" #include "host.h" #include "iscsi_err.h" /* * TODO: remove the _DIR defines and search for subsys dirs like * is done in sysfs.c. */ #define ISCSI_TRANSPORT_DIR "/sys/class/iscsi_transport" #define ISCSI_SESSION_DIR "/sys/class/iscsi_session" #define ISCSI_HOST_DIR "/sys/class/iscsi_host" #define ISCSI_SESSION_SUBSYS "iscsi_session" #define ISCSI_CONN_SUBSYS "iscsi_connection" #define ISCSI_HOST_SUBSYS "iscsi_host" #define ISCSI_TRANSPORT_SUBSYS "iscsi_transport" #define ISCSI_IFACE_SUBSYS "iscsi_iface" #define SCSI_HOST_SUBSYS "scsi_host" #define SCSI_SUBSYS "scsi" #define ISCSI_SESSION_ID "session%d" #define ISCSI_CONN_ID "connection%d:0" #define ISCSI_HOST_ID "host%d" /* * TODO: make this into a real API and check inputs better and add doc. */ static int num_transports; LIST_HEAD(transports); void free_transports(void) { struct iscsi_transport *t, *tmp; list_for_each_entry_safe(t, tmp, &transports, list) { list_del(&t->list); free(t); } } static int trans_filter(const struct dirent *dir) { return strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."); } static int read_transports(void) { struct dirent **namelist; int i, n, found; struct iscsi_transport *t; log_debug(7, "in %s", __FUNCTION__); n = scandir(ISCSI_TRANSPORT_DIR, &namelist, trans_filter, alphasort); if (n < 0) { log_error("Could not scan %s.", ISCSI_TRANSPORT_DIR); return n; } for (i = 0; i < n; i++) { found = 0; list_for_each_entry(t, &transports, list) { if (!strcmp(t->name, namelist[i]->d_name)) { found = 1; break; } } if (!found) { /* copy new transport */ t = malloc(sizeof(*t)); if (!t) continue; log_debug(7, "Adding new transport %s", namelist[i]->d_name); INIT_LIST_HEAD(&t->sessions); INIT_LIST_HEAD(&t->list); strlcpy(t->name, namelist[i]->d_name, ISCSI_TRANSPORT_NAME_MAXLEN); if (set_transport_template(t)) { free(t); return -1; } } else log_debug(7, "Updating transport %s", namelist[i]->d_name); if (sysfs_get_uint64(t->name, ISCSI_TRANSPORT_SUBSYS, "handle", &t->handle)) { if (list_empty(&t->list)) free(t); else log_error("Could not update %s.\n", t->name); continue; } if (sysfs_get_uint(t->name, ISCSI_TRANSPORT_SUBSYS, "caps", &t->caps)) { if (list_empty(&t->list)) free(t); else log_error("Could not update %s.\n", t->name); continue; } /* * tmp hack for qla4xx compat */ if (!strcmp(t->name, "qla4xxx")) { t->caps |= CAP_DATA_PATH_OFFLOAD; } if (list_empty(&t->list)) list_add_tail(&t->list, &transports); } for (i = 0; i < n; i++) free(namelist[i]); free(namelist); num_transports = n; return 0; } /* caller must check lengths */ void iscsi_sysfs_get_auth_conf(int sid, struct iscsi_auth_config *conf) { char id[NAME_SIZE]; memset(conf, 0, sizeof(*conf)); snprintf(id, sizeof(id), ISCSI_SESSION_ID, sid); sysfs_get_str(id, ISCSI_SESSION_SUBSYS, "username", conf->username, sizeof(conf->username)); sysfs_get_str(id, ISCSI_SESSION_SUBSYS, "username_in", conf->username_in, sizeof(conf->username_in)); sysfs_get_str(id, ISCSI_SESSION_SUBSYS, "password", (char *)conf->password, sizeof(conf->password)); if (strlen((char *)conf->password)) conf->password_length = strlen((char *)conf->password); sysfs_get_str(id, ISCSI_SESSION_SUBSYS, "password_in", (char *)conf->password_in, sizeof(conf->password_in)); if (strlen((char *)conf->password_in)) conf->password_in_length = strlen((char *)conf->password_in); } /* called must check for -1=invalid value */ void iscsi_sysfs_get_negotiated_conn_conf(int sid, struct iscsi_conn_operational_config *conf) { char id[NAME_SIZE]; memset(conf, 0, sizeof(*conf)); snprintf(id, sizeof(id), ISCSI_CONN_ID, sid); sysfs_get_int(id, ISCSI_CONN_SUBSYS, "data_digest", &conf->DataDigest); sysfs_get_int(id, ISCSI_CONN_SUBSYS, "header_digest", &conf->HeaderDigest); sysfs_get_int(id, ISCSI_CONN_SUBSYS, "max_xmit_dlength", &conf->MaxXmitDataSegmentLength); sysfs_get_int(id, ISCSI_CONN_SUBSYS, "max_recv_dlength", &conf->MaxRecvDataSegmentLength); } /* called must check for -1=invalid value */ void iscsi_sysfs_get_negotiated_session_conf(int sid, struct iscsi_session_operational_config *conf) { char id[NAME_SIZE]; memset(conf, 0, sizeof(*conf)); snprintf(id, sizeof(id), ISCSI_SESSION_ID, sid); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "data_pdu_in_order", &conf->DataPDUInOrder); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "data_seq_in_order", &conf->DataSequenceInOrder); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "erl", &conf->ERL); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "first_burst_len", &conf->FirstBurstLength); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "max_burst_len", &conf->MaxBurstLength); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "immediate_data", &conf->ImmediateData); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "initial_r2t", &conf->InitialR2T); sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "max_outstanding_r2t", &conf->MaxOutstandingR2T); } /* * iscsi_sysfs_session_user_created - return if session was setup by userspace * @sid: id of session to test * * Returns -1 if we could not tell due to kernel not supporting the * feature. 0 is returned if kernel created it. And 1 is returned * if userspace created it. */ int iscsi_sysfs_session_user_created(int sid) { char id[NAME_SIZE]; pid_t pid; snprintf(id, sizeof(id), ISCSI_SESSION_ID, sid); if (sysfs_get_int(id, ISCSI_SESSION_SUBSYS, "creator", &pid)) return -1; if (pid == -1) return 0; else return 1; } uint32_t iscsi_sysfs_get_host_no_from_sid(uint32_t sid, int *err) { struct sysfs_device *session_dev, *host_dev; char devpath[PATH_SIZE]; char id[NAME_SIZE]; *err = 0; snprintf(id, sizeof(id), "session%u", sid); if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), ISCSI_SESSION_SUBSYS, id)) { log_error("Could not lookup devpath for %s. Possible sysfs " "incompatibility.\n", id); *err = ISCSI_ERR_SYSFS_LOOKUP; return 0; } session_dev = sysfs_device_get(devpath); if (!session_dev) { log_error("Could not get dev for %s. Possible sysfs " "incompatibility.\n", id); *err = ISCSI_ERR_SYSFS_LOOKUP; return 0; } /* * 2.6.27 moved from scsi_host to scsi for the subsys when * sysfs compat is not on. */ host_dev = sysfs_device_get_parent_with_subsystem(session_dev, SCSI_SUBSYS); if (!host_dev) { struct sysfs_device *dev_parent; dev_parent = sysfs_device_get_parent(session_dev); while (dev_parent != NULL) { if (strncmp(dev_parent->kernel, "host", 4) == 0) { host_dev = dev_parent; break; } dev_parent = sysfs_device_get_parent(dev_parent); } if (!host_dev) { log_error("Could not get host dev for %s. Possible " "sysfs incompatibility.\n", id); *err = ISCSI_ERR_SYSFS_LOOKUP; return 0; } } return atol(host_dev->kernel_number); } /* TODO: merge and make macro */ static int __get_host_no_from_netdev(void *data, struct host_info *info) { struct host_info *ret_info = data; if (!strcmp(ret_info->iface.netdev, info->iface.netdev)) { ret_info->host_no = info->host_no; return 1; } return 0; } static uint32_t get_host_no_from_netdev(char *netdev, int *rc) { uint32_t host_no = -1; struct host_info *info; int nr_found, local_rc; *rc = 0; info = calloc(1, sizeof(*info)); if (!info) { *rc = ISCSI_ERR_NOMEM; return -1; } strcpy(info->iface.netdev, netdev); local_rc = iscsi_sysfs_for_each_host(info, &nr_found, __get_host_no_from_netdev); if (local_rc == 1) host_no = info->host_no; else *rc = ISCSI_ERR_HOST_NOT_FOUND; free(info); return host_no; } static int __get_host_no_from_hwaddress(void *data, struct host_info *info) { struct host_info *ret_info = data; if (!strcasecmp(ret_info->iface.hwaddress, info->iface.hwaddress)) { ret_info->host_no = info->host_no; return 1; } return 0; } uint32_t iscsi_sysfs_get_host_no_from_hwaddress(char *hwaddress, int *rc) { uint32_t host_no = -1; struct host_info *info; int nr_found, local_rc; *rc = 0; info = calloc(1, sizeof(*info)); if (!info) { *rc = ISCSI_ERR_NOMEM; return -1; } strcpy(info->iface.hwaddress, hwaddress); local_rc = iscsi_sysfs_for_each_host(info, &nr_found, __get_host_no_from_hwaddress); if (local_rc == 1) host_no = info->host_no; else *rc = ISCSI_ERR_HOST_NOT_FOUND; free(info); return host_no; } static int __get_host_no_from_ipaddress(void *data, struct host_info *info) { struct host_info *ret_info = data; if (!strcmp(ret_info->iface.ipaddress, info->iface.ipaddress)) { ret_info->host_no = info->host_no; return 1; } return 0; } static uint32_t get_host_no_from_ipaddress(char *address, int *rc) { uint32_t host_no = -1; struct host_info *info; int nr_found; int local_rc; *rc = 0; info = calloc(1, sizeof(*info)); if (!info) { *rc = ISCSI_ERR_NOMEM; return -1; } strcpy(info->iface.ipaddress, address); local_rc = iscsi_sysfs_for_each_host(info, &nr_found, __get_host_no_from_ipaddress); if (local_rc == 1) host_no = info->host_no; else *rc = ISCSI_ERR_HOST_NOT_FOUND; free(info); return host_no; } uint32_t iscsi_sysfs_get_host_no_from_hwinfo(struct iface_rec *iface, int *rc) { int tmp_rc; uint32_t host_no = -1; if (strlen(iface->hwaddress) && strcasecmp(iface->hwaddress, DEFAULT_HWADDRESS)) host_no = iscsi_sysfs_get_host_no_from_hwaddress( iface->hwaddress, &tmp_rc); else if (strlen(iface->netdev) && strcasecmp(iface->netdev, DEFAULT_NETDEV)) host_no = get_host_no_from_netdev(iface->netdev, &tmp_rc); else if (strlen(iface->ipaddress) && strcasecmp(iface->ipaddress, DEFAULT_IPADDRESS)) host_no = get_host_no_from_ipaddress(iface->ipaddress, &tmp_rc); else tmp_rc = ISCSI_ERR_INVAL; *rc = tmp_rc; return host_no; } /* * Read in iface settings based on host and session values. If * session is not passed in, then the ifacename will not be set. And * if the session is not passed in then iname will only be set for * qla4xxx. */ static int iscsi_sysfs_read_iface(struct iface_rec *iface, int host_no, char *session, char *iface_kern_id) { uint32_t tmp_host_no, iface_num; char host_id[NAME_SIZE]; struct iscsi_transport *t; int ret, iface_type; t = iscsi_sysfs_get_transport_by_hba(host_no); if (!t) log_debug(7, "could not get transport name for host%d", host_no); else strcpy(iface->transport_name, t->name); snprintf(host_id, sizeof(host_id), ISCSI_HOST_ID, host_no); /* * backward compat * If we cannot get the address we assume we are doing the old * style and use default. */ ret = sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "hwaddress", iface->hwaddress, sizeof(iface->hwaddress)); if (ret) log_debug(7, "could not read hwaddress for host%d\n", host_no); if (iface_kern_id) ret = sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "ipaddress", iface->ipaddress, sizeof(iface->ipaddress)); else /* if not found just print out default */ ret = sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "ipaddress", iface->ipaddress, sizeof(iface->ipaddress)); if (ret) log_debug(7, "could not read local address for host%d\n", host_no); /* if not found just print out default */ ret = sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "netdev", iface->netdev, sizeof(iface->netdev)); if (ret) log_debug(7, "could not read netdev for host%d\n", host_no); /* * For drivers like qla4xxx we can only set the iname at the * host level because we cannot create different initiator ports * (cannot set isid either). The LLD also exports the iname at the * hba level so apps can see it, but we no longer set the iname for * each iscsid controlled host since bnx2i cxgbi can support multiple * initiator names and of course software iscsi can support anything. */ ret = 1; memset(iface->iname, 0, sizeof(iface->iname)); if (session) { ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "initiatorname", iface->iname, sizeof(iface->iname)); /* * qlaxxx will not set this at the session level so we * always drop down for it. * * And. * * For older kernels/tools (2.6.26 and below and 2.0.870) * we will not have a session level initiator name, so * we will drop down. */ } if (ret) { ret = sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "initiatorname", iface->iname, sizeof(iface->iname)); if (ret) /* * default iname is picked up later from * initiatorname.iscsi if software/partial-offload. * * TODO: we should make it easier to get the * global iname so we can just fill it in here. */ log_debug(7, "Could not read initiatorname for " "host%d\n", host_no); /* optional so do not return error */ ret = 0; } sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "port_state", iface->port_state, sizeof(iface->port_state)); sysfs_get_str(host_id, ISCSI_HOST_SUBSYS, "port_speed", iface->port_speed, sizeof(iface->port_speed)); /* * this is on the session, because we support multiple bindings * per device. */ memset(iface->name, 0, sizeof(iface->name)); if (session) { /* * this was added after 2.0.869 so we could be doing iscsi_tcp * session binding, but there may not be a ifacename set * if binding is not used. */ ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "ifacename", iface->name, sizeof(iface->name)); if (ret) { log_debug(7, "could not read iface name for " "session %s\n", session); /* * if the ifacename file is not there then we are * using a older kernel and can try to find the * binding by the net info which was used on these * older kernels. */ if (iface_get_by_net_binding(iface, iface)) log_debug(7, "Could not find iface for session " "bound to:" iface_fmt "\n", iface_str(iface)); } } if (!iface_kern_id) goto done; strlcpy(iface->name, iface_kern_id, sizeof(iface->name)); if (!strncmp(iface_kern_id, "ipv4", 4)) { sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "bootproto", iface->bootproto, sizeof(iface->bootproto)); sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "gateway", iface->gateway, sizeof(iface->gateway)); sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "subnet", iface->subnet_mask, sizeof(iface->subnet_mask)); } else { sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "ipaddr_autocfg", iface->ipv6_autocfg, sizeof(iface->ipv6_autocfg)); sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "link_local_addr", iface->ipv6_linklocal, sizeof(iface->ipv6_linklocal)); sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "link_local_autocfg", iface->linklocal_autocfg, sizeof(iface->linklocal_autocfg)); sysfs_get_str(iface_kern_id, ISCSI_IFACE_SUBSYS, "router_addr", iface->ipv6_router, sizeof(iface->ipv6_router)); } if (sysfs_get_uint16(iface_kern_id, ISCSI_IFACE_SUBSYS, "port", &iface->port)) iface->port = 0; if (sysfs_get_uint16(iface_kern_id, ISCSI_IFACE_SUBSYS, "mtu", &iface->mtu)) iface->mtu = 0; if (sysfs_get_uint16(iface_kern_id, ISCSI_IFACE_SUBSYS, "vlan_id", &iface->vlan_id)) iface->vlan_id = UINT16_MAX; if (sysfs_get_uint8(iface_kern_id, ISCSI_IFACE_SUBSYS, "vlan_priority", &iface->vlan_priority)) iface->vlan_priority = UINT8_MAX; if (sscanf(iface_kern_id, "ipv%d-iface-%u-%u", &iface_type, &tmp_host_no, &iface_num) == 3) iface->iface_num = iface_num; done: if (ret) return ISCSI_ERR_SYSFS_LOOKUP; else return 0; } int iscsi_sysfs_get_hostinfo_by_host_no(struct host_info *hinfo) { return iscsi_sysfs_read_iface(&hinfo->iface, hinfo->host_no, NULL, NULL); } int iscsi_sysfs_for_each_host(void *data, int *nr_found, iscsi_sysfs_host_op_fn *fn) { struct dirent **namelist; int rc = 0, i, n; struct host_info *info; info = malloc(sizeof(*info)); if (!info) return ISCSI_ERR_NOMEM; n = scandir(ISCSI_HOST_DIR, &namelist, trans_filter, alphasort); if (n <= 0) goto free_info; for (i = 0; i < n; i++) { memset(info, 0, sizeof(*info)); if (sscanf(namelist[i]->d_name, "host%u", &info->host_no) != 1) { log_error("Invalid iscsi host dir: %s", namelist[i]->d_name); break; } iscsi_sysfs_get_hostinfo_by_host_no(info); rc = fn(data, info); if (rc != 0) break; (*nr_found)++; } for (i = 0; i < n; i++) free(namelist[i]); free(namelist); free_info: free(info); return rc; } int iscsi_sysfs_for_each_iface_on_host(void *data, uint32_t host_no, int *nr_found, iscsi_sysfs_iface_op_fn *fn) { struct dirent **namelist; int rc = 0, i, n; struct iface_rec iface; char devpath[PATH_SIZE]; char sysfs_path[PATH_SIZE]; char id[NAME_SIZE]; snprintf(id, sizeof(id), "host%u", host_no); if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), SCSI_SUBSYS, id)) { log_error("Could not look up host's ifaces via scsi bus."); return ISCSI_ERR_SYSFS_LOOKUP; } sprintf(sysfs_path, "/sys"); strlcat(sysfs_path, devpath, sizeof(sysfs_path)); strlcat(sysfs_path, "/iscsi_iface", sizeof(sysfs_path)); n = scandir(sysfs_path, &namelist, trans_filter, alphasort); if (n <= 0) /* older kernels or some drivers will not have ifaces */ return 0; for (i = 0; i < n; i++) { memset(&iface, 0, sizeof(iface)); iscsi_sysfs_read_iface(&iface, host_no, NULL, namelist[i]->d_name); rc = fn(data, &iface); if (rc != 0) break; (*nr_found)++; } for (i = 0; i < n; i++) free(namelist[i]); free(namelist); return rc; } /** * sysfs_session_has_leadconn - checks if session has lead conn in kernel * @sid: session id * * return 1 if session has lead conn and 0 if not. */ int iscsi_sysfs_session_has_leadconn(uint32_t sid) { char devpath[PATH_SIZE]; char id[NAME_SIZE]; snprintf(id, sizeof(id), "connection%u:0", sid); return sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), ISCSI_CONN_SUBSYS, id); } /* * iscsi_sysfs_get_sid_from_path - parse a string for the sid * @session: session path * * Given sysfs_device is a directory name of the form: * * /sys/devices/platform/hostH/sessionS/targetH:B:I/H:B:I:L * /sys/devices/platform/hostH/sessionS/targetH:B:I * /sys/devices/platform/hostH/sessionS * * return the sid S. If just the sid is passed in it will be covnerted * to a int. */ int iscsi_sysfs_get_sid_from_path(char *session) { struct sysfs_device *dev_parent, *dev; struct stat statb; char devpath[PATH_SIZE]; if (lstat(session, &statb)) { log_debug(1, "Could not stat %s failed with %d", session, errno); if (index(session, '/')) { log_error("%s is an invalid session path\n", session); exit(1); } return atoi(session); } if (!S_ISDIR(statb.st_mode) && !S_ISLNK(statb.st_mode)) { log_error("%s is not a directory", session); exit(1); } if (!strncmp(session, "/sys", 4)) strlcpy(devpath, session + 4, sizeof(devpath)); else strlcpy(devpath, session, sizeof(devpath)); dev = sysfs_device_get(devpath); if (!dev) { log_error("Could not get dev for %s. Possible sysfs " "incompatibility.\n", devpath); return -1; } if (!strncmp(dev->kernel, "session", 7)) return atoi(dev->kernel_number); dev_parent = sysfs_device_get_parent(dev); while (dev_parent != NULL) { if (strncmp(dev_parent->kernel, "session", 7) == 0) return atoi(dev_parent->kernel_number); dev_parent = sysfs_device_get_parent(dev_parent); } log_error("Unable to find sid in path %s", session); return -1; } int iscsi_sysfs_get_sessioninfo_by_id(struct session_info *info, char *session) { char id[NAME_SIZE]; int ret, pers_failed = 0; uint32_t host_no; if (sscanf(session, "session%d", &info->sid) != 1) { log_error("invalid session '%s'", session); return ISCSI_ERR_INVAL; } ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "targetname", info->targetname, sizeof(info->targetname)); if (ret) { log_error("could not read session targetname: %d", ret); return ISCSI_ERR_SYSFS_LOOKUP; } ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "username", (info->chap).username, sizeof((info->chap).username)); if (ret) log_debug(5, "could not read username: %d", ret); ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "password", (info->chap).password, sizeof((info->chap).password)); if (ret) log_debug(5, "could not read password: %d", ret); ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "username_in", (info->chap).username_in, sizeof((info->chap).username_in)); if (ret) log_debug(5, "could not read username in: %d", ret); ret = sysfs_get_str(session, ISCSI_SESSION_SUBSYS, "password_in", (info->chap).password_in, sizeof((info->chap).password_in)); if (ret) log_debug(5, "could not read password in: %d", ret); ret = sysfs_get_int(session, ISCSI_SESSION_SUBSYS, "recovery_tmo", &((info->tmo).recovery_tmo)); if (ret) (info->tmo).recovery_tmo = -1; ret = sysfs_get_int(session, ISCSI_SESSION_SUBSYS, "lu_reset_tmo", &((info->tmo).lu_reset_tmo)); if (ret) (info->tmo).lu_reset_tmo = -1; ret = sysfs_get_int(session, ISCSI_SESSION_SUBSYS, "tgt_reset_tmo", &((info->tmo).tgt_reset_tmo)); if (ret) (info->tmo).lu_reset_tmo = -1; sysfs_get_int(session, ISCSI_SESSION_SUBSYS, "abort_tmo", &((info->tmo).abort_tmo)); if (ret) (info->tmo).abort_tmo = -1; ret = sysfs_get_int(session, ISCSI_SESSION_SUBSYS, "tpgt", &info->tpgt); if (ret) { log_error("could not read session tpgt: %d", ret); return ISCSI_ERR_SYSFS_LOOKUP; } snprintf(id, sizeof(id), ISCSI_CONN_ID, info->sid); /* some HW drivers do not export addr and port */ memset(info->persistent_address, 0, NI_MAXHOST); ret = sysfs_get_str(id, ISCSI_CONN_SUBSYS, "persistent_address", info->persistent_address, sizeof(info->persistent_address)); if (ret) { pers_failed = 1; /* older qlogic does not support this */ log_debug(5, "could not read pers conn addr: %d", ret); } memset(info->address, 0, NI_MAXHOST); ret = sysfs_get_str(id, ISCSI_CONN_SUBSYS, "address", info->address, sizeof(info->address)); if (ret) { log_debug(5, "could not read curr addr: %d", ret); /* iser did not export this */ if (!pers_failed) strcpy(info->address, info->persistent_address); } else if (pers_failed) /* * for qla if we could not get the persistent addr * we will use the current for both addrs */ strcpy(info->persistent_address, info->address); pers_failed = 0; info->persistent_port = -1; ret = sysfs_get_int(id, ISCSI_CONN_SUBSYS, "persistent_port", &info->persistent_port); if (ret) { pers_failed = 1; log_debug(5, "Could not read pers conn port %d", ret); } info->port = -1; ret = sysfs_get_int(id, ISCSI_CONN_SUBSYS, "port", &info->port); if (ret) { /* iser did not export this */ if (!pers_failed) info->port = info->persistent_port; log_debug(5, "Could not read curr conn port %d", ret); } else if (pers_failed) /* * for qla if we could not get the persistent addr * we will use the current for both addrs */ info->persistent_port = info->port; ret = 0; host_no = iscsi_sysfs_get_host_no_from_sid(info->sid, &ret); if (ret) { log_error("could not get host_no for session%d: %s.", info->sid, iscsi_err_to_str(ret)); return ret; } iscsi_sysfs_read_iface(&info->iface, host_no, session, NULL); log_debug(7, "found targetname %s address %s pers address %s port %d " "pers port %d driver %s iface name %s ipaddress %s " "netdev %s hwaddress %s iname %s", info->targetname, info->address ? info->address : "NA", info->persistent_address ? info->persistent_address : "NA", info->port, info->persistent_port, info->iface.transport_name, info->iface.name, info->iface.ipaddress, info->iface.netdev, info->iface.hwaddress, info->iface.iname); return 0; } int iscsi_sysfs_for_each_session(void *data, int *nr_found, iscsi_sysfs_session_op_fn *fn) { struct dirent **namelist; int rc = 0, n, i; struct session_info *info; info = calloc(1, sizeof(*info)); if (!info) return ISCSI_ERR_NOMEM; n = scandir(ISCSI_SESSION_DIR, &namelist, trans_filter, alphasort); if (n <= 0) goto free_info; for (i = 0; i < n; i++) { rc = iscsi_sysfs_get_sessioninfo_by_id(info, namelist[i]->d_name); if (rc) { log_error("could not find session info for %s", namelist[i]->d_name); /* raced. session was shutdown while looping */ rc = 0; continue; } rc = fn(data, info); if (rc > 0) break; else if (rc == 0) (*nr_found)++; else /* if less than zero it means it was not a match */ rc = 0; } for (i = 0; i < n; i++) free(namelist[i]); free(namelist); free_info: free(info); return rc; } int iscsi_sysfs_get_session_state(char *state, int sid) { char id[NAME_SIZE]; snprintf(id, sizeof(id), ISCSI_SESSION_ID, sid); if (sysfs_get_str(id, ISCSI_SESSION_SUBSYS, "state", state, SCSI_MAX_STATE_VALUE)) return ISCSI_ERR_SYSFS_LOOKUP; return 0; } int iscsi_sysfs_get_host_state(char *state, int host_no) { char id[NAME_SIZE]; snprintf(id, sizeof(id), ISCSI_HOST_ID, host_no); if (sysfs_get_str(id, SCSI_HOST_SUBSYS, "state", state, SCSI_MAX_STATE_VALUE)) return ISCSI_ERR_SYSFS_LOOKUP; return 0; } int iscsi_sysfs_get_device_state(char *state, int host_no, int target, int lun) { char id[NAME_SIZE]; snprintf(id, sizeof(id), "%d:0:%d:%d", host_no, target, lun); if (sysfs_get_str(id, SCSI_SUBSYS, "state", state, SCSI_MAX_STATE_VALUE)) { log_debug(3, "Could not read attr state for %s\n", id); return ISCSI_ERR_SYSFS_LOOKUP; } return 0; } char *iscsi_sysfs_get_blockdev_from_lun(int host_no, int target, int lun) { char devpath[PATH_SIZE]; char path_full[PATH_SIZE]; char id[NAME_SIZE]; DIR *dirfd; struct dirent *dent; size_t sysfs_len; struct stat statbuf; char *blockdev, *blockdup = NULL; snprintf(id, sizeof(id), "%d:0:%d:%d", host_no, target, lun); if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), SCSI_SUBSYS, id)) { log_debug(3, "Could not lookup devpath for %s %s\n", SCSI_SUBSYS, id); return NULL; } sysfs_len = strlcpy(path_full, sysfs_path, sizeof(path_full)); if (sysfs_len >= sizeof(path_full)) sysfs_len = sizeof(path_full) - 1; strlcat(path_full, devpath, sizeof(path_full)); dirfd = opendir(path_full); if (!dirfd) return NULL; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; /* not sure what tape looks like */ if (strncmp(dent->d_name, "block:", 5)) continue; strlcat(path_full, "/", sizeof(path_full)); strlcat(path_full, dent->d_name, sizeof(path_full)); /* * 2.6.25 dropped the symlink and now block is a dir. */ if (lstat(path_full, &statbuf)) { log_error("Could not stat block path %s err %d\n", path_full, errno); break; } if (S_ISLNK(statbuf.st_mode)) { blockdev = strchr(dent->d_name, ':'); if (!blockdev) break; /* increment past colon */ blockdev++; blockdup = strdup(blockdev); } else if (S_ISDIR(statbuf.st_mode)) { DIR *blk_dirfd; struct dirent *blk_dent; /* it should not be this hard should it? :) */ blk_dirfd = opendir(path_full); if (!blk_dirfd) { log_debug(3, "Could not open blk path %s\n", path_full); break; } while ((blk_dent = readdir(blk_dirfd))) { if (!strcmp(blk_dent->d_name, ".") || !strcmp(blk_dent->d_name, "..")) continue; blockdup = strdup(blk_dent->d_name); break; } closedir(blk_dirfd); } break; } closedir(dirfd); return blockdup; } static uint32_t get_target_no_from_sid(uint32_t sid, int *err) { char devpath[PATH_SIZE]; char path_full[PATH_SIZE]; char id[NAME_SIZE]; DIR *dirfd; struct dirent *dent; uint32_t host, bus, target = 0; size_t sysfs_len; *err = ISCSI_ERR_SESS_NOT_FOUND; snprintf(id, sizeof(id), "session%u", sid); if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), ISCSI_SESSION_SUBSYS, id)) { log_debug(3, "Could not lookup devpath for %s %s\n", ISCSI_SESSION_SUBSYS, id); return 0; } /* * This does not seem safe from future changes, but we currently * want /devices/platform/hostY/sessionX, but we come from the * /class/iscsi_session/sessionX/device. */ sysfs_len = strlcpy(path_full, sysfs_path, sizeof(path_full)); if (sysfs_len >= sizeof(path_full)) sysfs_len = sizeof(path_full) - 1; strlcat(path_full, devpath, sizeof(path_full)); strlcat(path_full, "/device", sizeof(devpath)); dirfd = opendir(path_full); if (!dirfd) return 0; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; if (strncmp(dent->d_name, "target", 6)) continue; if (sscanf(dent->d_name, "target%u:%u:%u", &host, &bus, &target) != 3) break; *err = 0; break; } closedir(dirfd); return target; } int iscsi_sysfs_is_transport_loaded(char *transport_name) { struct iscsi_transport *t; /* sync up kernel and userspace */ read_transports(); /* check if the transport is loaded and matches */ list_for_each_entry(t, &transports, list) { if (t->handle && !strncmp(t->name, transport_name, ISCSI_TRANSPORT_NAME_MAXLEN)) return 1; } return 0; } struct iscsi_transport *iscsi_sysfs_get_transport_by_name(char *transport_name) { struct iscsi_transport *t; int retry = 0; retry: /* sync up kernel and userspace */ read_transports(); /* check if the transport is loaded and matches */ list_for_each_entry(t, &transports, list) { if (t->handle && !strncmp(t->name, transport_name, ISCSI_TRANSPORT_NAME_MAXLEN)) return t; } if (retry < 1) { retry++; if (!transport_load_kmod(transport_name)) goto retry; } return NULL; } /* TODO: replace the following functions with some decent sysfs links */ struct iscsi_transport *iscsi_sysfs_get_transport_by_hba(uint32_t host_no) { char name[ISCSI_TRANSPORT_NAME_MAXLEN]; char id[NAME_SIZE]; int rc; if (host_no == -1) return NULL; snprintf(id, sizeof(id), ISCSI_HOST_ID, host_no); rc = sysfs_get_str(id, SCSI_HOST_SUBSYS, "proc_name", name, ISCSI_TRANSPORT_NAME_MAXLEN); if (rc) { log_error("Could not read proc_name for host%u rc %d.", host_no, rc); return NULL; } /* * stupid, stupid. We named the transports tcp or iser, but the * the modules are named iscsi_tcp and iscsi_iser */ if (strstr(name, "iscsi_")) return iscsi_sysfs_get_transport_by_name(name + 6); else return iscsi_sysfs_get_transport_by_name(name); } struct iscsi_transport *iscsi_sysfs_get_transport_by_sid(uint32_t sid) { uint32_t host_no; int err; host_no = iscsi_sysfs_get_host_no_from_sid(sid, &err); if (err) return NULL; return iscsi_sysfs_get_transport_by_hba(host_no); } /* * For connection reinstatement we need to send the exp_statsn from * the previous connection * * This is only called when the connection is halted so exp_statsn is safe * to read without racing. */ int iscsi_sysfs_get_exp_statsn(int sid) { char id[NAME_SIZE]; uint32_t exp_statsn = 0; snprintf(id, sizeof(id), ISCSI_CONN_ID, sid); if (sysfs_get_uint(id, ISCSI_CONN_SUBSYS, "exp_statsn", &exp_statsn)) { log_error("Could not read expstatsn for sid %d. " "Using zero for exp_statsn.", sid); exp_statsn = 0; } return exp_statsn; } int iscsi_sysfs_session_supports_nop(int sid) { char id[NAME_SIZE]; uint32_t ping_tmo = 0; snprintf(id, sizeof(id), ISCSI_CONN_ID, sid); if (sysfs_get_uint(id, ISCSI_CONN_SUBSYS, "ping_tmo", &ping_tmo)) { return 0; } return 1; } int iscsi_sysfs_for_each_device(void *data, int host_no, uint32_t sid, void (* fn)(void *data, int host_no, int target, int lun)) { struct dirent **namelist; int h, b, t, l, i, n, err = 0, target; char devpath[PATH_SIZE]; char id[NAME_SIZE]; char path_full[PATH_SIZE]; target = get_target_no_from_sid(sid, &err); if (err) return err; snprintf(id, sizeof(id), "session%u", sid); if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), ISCSI_SESSION_SUBSYS, id)) { log_debug(3, "Could not lookup devpath for %s %s\n", ISCSI_SESSION_SUBSYS, id); return ISCSI_ERR_SYSFS_LOOKUP; } snprintf(path_full, sizeof(path_full), "%s%s/device/target%d:0:%d", sysfs_path, devpath, host_no, target); n = scandir(path_full, &namelist, trans_filter, alphasort); if (n <= 0) return 0; for (i = 0; i < n; i++) { if (sscanf(namelist[i]->d_name, "%d:%d:%d:%d\n", &h, &b, &t, &l) != 4) continue; fn(data, h, t, l); } for (i = 0; i < n; i++) free(namelist[i]); free(namelist); return 0; } void iscsi_sysfs_set_queue_depth(void *data, int hostno, int target, int lun) { char id[NAME_SIZE]; char write_buf[20]; int err, qdepth = *((int *)data); snprintf(id, sizeof(id), "%d:0:%d:%d", hostno, target, lun); snprintf(write_buf, sizeof(write_buf), "%d", qdepth); log_debug(4, "set queue depth for %s to %s", id, write_buf); err = sysfs_set_param(id, SCSI_SUBSYS, "queue_depth", write_buf, strlen(write_buf)); if (err && err != EINVAL) log_error("Could not queue depth for LUN %d err %d.", lun, err); } void iscsi_sysfs_set_device_online(void *data, int hostno, int target, int lun) { char *write_buf = "running\n"; char id[NAME_SIZE]; int err; snprintf(id, sizeof(id), "%d:0:%d:%d", hostno, target, lun); log_debug(4, "online device %s", id); err = sysfs_set_param(id, SCSI_SUBSYS, "state", write_buf, strlen(write_buf)); if (err && err != EINVAL) /* we should read the state */ log_error("Could not online LUN %d err %d.", lun, err); } void iscsi_sysfs_rescan_device(void *data, int hostno, int target, int lun) { char *write_buf = "1"; char id[NAME_SIZE]; snprintf(id, sizeof(id), "%d:0:%d:%d", hostno, target, lun); log_debug(4, "rescanning device %s", id); sysfs_set_param(id, SCSI_SUBSYS, "rescan", write_buf, strlen(write_buf)); } pid_t iscsi_sysfs_scan_host(int hostno, int async) { char id[NAME_SIZE]; char *write_buf = "- - -"; pid_t pid = 0; if (async) pid = fork(); if (pid == 0) { /* child */ log_debug(4, "scanning host%d", hostno); snprintf(id, sizeof(id), ISCSI_HOST_ID, hostno); sysfs_set_param(id, SCSI_HOST_SUBSYS, "scan", write_buf, strlen(write_buf)); log_debug(4, "scanning host%d completed\n", hostno); } else if (pid > 0) { log_debug(4, "scanning host%d from pid %d", hostno, pid); } else /* * Session is fine, so log the error and let the user * scan by hand */ log_error("Could not start scanning process for host %d " "err %d. Try scanning through sysfs.", hostno, errno); return pid; } struct iscsi_transport *iscsi_sysfs_get_transport_by_session(char *sys_session) { uint32_t sid; if (sscanf(sys_session, "session%u", &sid) != 1) { log_error("invalid session '%s'.", sys_session); return NULL; } return iscsi_sysfs_get_transport_by_sid(sid); } char *iscsi_sysfs_get_iscsi_kernel_version(void) { return sysfs_attr_get_value("/module/scsi_transport_iscsi", "version"); } open-iscsi-2.0.873/usr/iscsi_sysfs.h000066400000000000000000000075721175631155400173120ustar00rootroot00000000000000/* * iSCSI sysfs * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef ISCSI_SYSFS_H #define ISCSI_SYSFS_H #include #include "sysfs.h" #include "types.h" #include "iscsi_proto.h" #include "config.h" struct session_info; struct host_info; struct iscsi_session; struct iscsi_conn; struct iscsi_session_operational_config; struct iscsi_conn_operational_config; struct iscsi_auth_config; #define SCSI_MAX_STATE_VALUE 32 extern void free_transports(void); extern char *iscsi_sysfs_get_iscsi_kernel_version(void); extern int iscsi_sysfs_get_sessioninfo_by_id(struct session_info *info, char *sys_session); extern int iscsi_sysfs_session_has_leadconn(uint32_t sid); typedef int (iscsi_sysfs_session_op_fn)(void *, struct session_info *); typedef int (iscsi_sysfs_host_op_fn)(void *, struct host_info *); typedef int (iscsi_sysfs_iface_op_fn)(void *, struct iface_rec *); extern int iscsi_sysfs_for_each_iface_on_host(void *data, uint32_t host_no, int *nr_found, iscsi_sysfs_iface_op_fn *fn); extern int iscsi_sysfs_for_each_session(void *data, int *nr_found, iscsi_sysfs_session_op_fn *fn); extern int iscsi_sysfs_for_each_host(void *data, int *nr_found, iscsi_sysfs_host_op_fn *fn); extern uint32_t iscsi_sysfs_get_host_no_from_sid(uint32_t sid, int *err); extern uint32_t iscsi_sysfs_get_host_no_from_hwinfo(struct iface_rec *iface, int *rc); extern uint32_t iscsi_sysfs_get_host_no_from_hwaddress(char *hwaddress, int *rc); extern int iscsi_sysfs_get_hostinfo_by_host_no(struct host_info *hinfo); extern int iscsi_sysfs_get_sid_from_path(char *session); extern char *iscsi_sysfs_get_blockdev_from_lun(int hostno, int target, int sid); static inline int is_valid_operational_value(int value) { return value != -1; } extern void iscsi_sysfs_get_auth_conf(int sid, struct iscsi_auth_config *conf); extern void iscsi_sysfs_get_negotiated_session_conf(int sid, struct iscsi_session_operational_config *conf); extern void iscsi_sysfs_get_negotiated_conn_conf(int sid, struct iscsi_conn_operational_config *conf); extern pid_t iscsi_sysfs_scan_host(int hostno, int async); extern int iscsi_sysfs_get_session_state(char *state, int sid); extern int iscsi_sysfs_get_host_state(char *state, int host_no); extern int iscsi_sysfs_get_device_state(char *state, int host_no, int target, int lun); extern int iscsi_sysfs_get_exp_statsn(int sid); extern void iscsi_sysfs_set_queue_depth(void *data, int hostno, int target, int lun); extern void iscsi_sysfs_set_device_online(void *data, int hostno, int target, int lun); extern void iscsi_sysfs_rescan_device(void *data, int hostno, int target, int lun); extern int iscsi_sysfs_for_each_device(void *data, int host_no, uint32_t sid, void (* fn)(void *, int host_no, int target, int lun)); extern struct iscsi_transport *iscsi_sysfs_get_transport_by_hba(uint32_t host_no); extern struct iscsi_transport *iscsi_sysfs_get_transport_by_session(char *sys_session); extern struct iscsi_transport *iscsi_sysfs_get_transport_by_sid(uint32_t sid); extern struct iscsi_transport *iscsi_sysfs_get_transport_by_name(char *transport_name); extern int iscsi_sysfs_is_transport_loaded(char *transport_name); extern int iscsi_sysfs_session_supports_nop(int sid); extern int iscsi_sysfs_session_user_created(int sid); extern struct list_head transports; #endif open-iscsi-2.0.873/usr/iscsi_timer.c000066400000000000000000000041711175631155400172460ustar00rootroot00000000000000/* * iSCSI timer * * Copyright (C) 2002 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include void iscsi_timer_clear(struct timeval *timer) { memset(timer, 0, sizeof (*timer)); } /* set timer to now + seconds */ void iscsi_timer_set(struct timeval *timer, int seconds) { if (timer) { memset(timer, 0, sizeof (*timer)); gettimeofday(timer, NULL); timer->tv_sec += seconds; } } int iscsi_timer_expired(struct timeval *timer) { struct timeval now; /* no timer, can't have expired */ if ((timer == NULL) || ((timer->tv_sec == 0) && (timer->tv_usec == 0))) return 0; memset(&now, 0, sizeof (now)); gettimeofday(&now, NULL); if (now.tv_sec > timer->tv_sec) return 1; if ((now.tv_sec == timer->tv_sec) && (now.tv_usec >= timer->tv_usec)) return 1; return 0; } int iscsi_timer_msecs_until(struct timeval *timer) { struct timeval now; int msecs; long partial; /* no timer, can't have expired, infinite time til it expires */ if ((timer == NULL) || ((timer->tv_sec == 0) && (timer->tv_usec == 0))) return -1; memset(&now, 0, sizeof (now)); gettimeofday(&now, NULL); /* already expired? */ if (now.tv_sec > timer->tv_sec) return 0; if ((now.tv_sec == timer->tv_sec) && (now.tv_usec >= timer->tv_usec)) return 0; /* not expired yet, do the math */ partial = timer->tv_usec - now.tv_usec; if (partial < 0) { partial += 1000 * 1000; msecs = (partial + 500) / 1000; msecs += (timer->tv_sec - now.tv_sec - 1) * 1000; } else { msecs = (partial + 500) / 1000; msecs += (timer->tv_sec - now.tv_sec) * 1000; } return msecs; } open-iscsi-2.0.873/usr/iscsi_timer.h000066400000000000000000000016661175631155400172610ustar00rootroot00000000000000/* * iSCSI timer * * Copyright (C) 2002 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSI_TIMER_H #define ISCSI_TIMER_H struct timeval; extern void iscsi_timer_clear(struct timeval *timer); extern void iscsi_timer_set(struct timeval *timer, int seconds); extern int iscsi_timer_expired(struct timeval *timer); extern int iscsi_timer_msecs_until(struct timeval *timer); #endif open-iscsi-2.0.873/usr/iscsi_util.c000066400000000000000000000177631175631155400171160ustar00rootroot00000000000000/* * Misc helpers * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 - 2010 Mike Christie * Copyright (C) 2006 - 2010 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "iscsi_settings.h" #include "iface.h" #include "session_info.h" #include "iscsi_util.h" void daemon_init(void) { int fd; fd = open("/dev/null", O_RDWR); if (fd == -1) { exit(-1); } dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); setsid(); if (chdir("/") < 0) log_debug(1, "Could not chdir to /: %s", strerror(errno)); } #define ISCSI_OOM_PATH_LEN 48 int oom_adjust(void) { int fd; char path[ISCSI_OOM_PATH_LEN]; struct stat statb; if (nice(-10) < 0) log_debug(1, "Could not increase process priority: %s", strerror(errno)); snprintf(path, ISCSI_OOM_PATH_LEN, "/proc/%d/oom_score_adj", getpid()); if (stat(path, &statb)) { /* older kernel so use old oom_adj file */ snprintf(path, ISCSI_OOM_PATH_LEN, "/proc/%d/oom_adj", getpid()); } fd = open(path, O_WRONLY); if (fd < 0) return -1; if (write(fd, "-16", 3) < 0) /* for 2.6.11 */ log_debug(1, "Could not set oom score to -16: %s", strerror(errno)); if (write(fd, "-17", 3) < 0) /* for Andrea's patch */ log_debug(1, "Could not set oom score to -17: %s", strerror(errno)); close(fd); return 0; } char* str_to_ipport(char *str, int *port, int *tpgt) { char *stpgt, *sport = str, *ip = str; if (!strchr(ip, '.')) { if (*ip == '[') { /* IPv6 with [] */ if (!(sport = strchr(ip, ']'))) return NULL; *sport++ = '\0'; ip++; str = sport; } else { /* hostname or ipv6 */ sport = strchr(ip, ':'); if (sport) { if (strchr(sport + 1, ':')) /* ipv6 */ sport = NULL; else /* hostname:port */ str = sport; } } } if (sport && (sport = strchr(str, ':'))) { *sport++ = '\0'; *port = strtoul(sport, NULL, 10); str = sport; } if ((stpgt = strchr(str, ','))) { *stpgt++ = '\0'; *tpgt = strtoul(stpgt, NULL, 10); } else *tpgt = PORTAL_GROUP_TAG_UNKNOWN; log_debug(2, "ip %s, port %d, tgpt %d", ip, *port, *tpgt); return ip; } #define ISCSI_MAX_FILES 16384 int increase_max_files(void) { struct rlimit rl; int err; err = getrlimit(RLIMIT_NOFILE, &rl); if (err) { log_debug(1, "Could not get file limit (err %d)\n", errno); return errno; } log_debug(1, "Max file limits %lu %lu\n", rl.rlim_cur, rl.rlim_max); if (rl.rlim_cur < ISCSI_MAX_FILES) rl.rlim_cur = ISCSI_MAX_FILES; if (rl.rlim_max < ISCSI_MAX_FILES) rl.rlim_max = ISCSI_MAX_FILES; err = setrlimit(RLIMIT_NOFILE, &rl); if (err) { log_debug(1, "Could not set file limit to %lu/%lu (err %d)\n", rl.rlim_cur, rl.rlim_max, errno); return errno; } return 0; } /* * from linux kernel */ char *strstrip(char *s) { size_t size; char *end; size = strlen(s); if (!size) return s; end = s + size - 1; while (end >= s && isspace(*end)) end--; *(end + 1) = '\0'; while (*s && isspace(*s)) s++; return s; } /** * cfg_get_string_param - return param value * @pathname: pathname and filename of config file * @key: param name * * Assumes the delim is a "=". "#" comments a line, but if * the "#" is after the key= then it is a valid value. */ char *cfg_get_string_param(char *pathname, const char *key) { FILE *f = NULL; char *line, buffer[1024]; char *value = NULL, *param, *comment; if (!pathname) { log_error("No pathname to load %s from", key); return NULL; } if ((f = fopen(pathname, "r"))) { while ((line = fgets(buffer, sizeof (buffer), f))) { param = strstr(line, key); if (!param) continue; /* make sure it is not commented out */ comment = strchr(line, '#'); if (comment) { if (comment < param) continue; } param = strchr(param, '='); if (!param) { log_error("Invalid config line for %s. " "Missing '='.", key); continue; } param++; if (!strlen(param)) { log_error("Invalid config line for %s. " "Missing value", key); continue; } param = strstrip(param); if (!strlen(param)) { log_error("Invalid config line for %s. " "Missing value", key); continue; } value = strdup(param); break; } fclose(f); if (value) log_debug(5, "%s=%s", key, value); } else log_error("can't open %s configuration file %s", key, pathname); return value; } /** * iscsi_addr_match - check if the addrs are to the same ip * @address1: pattern * @address2: address to check * * If address1 is blank then it matches any string passed in. */ static int iscsi_addr_match(char *address1, char *address2) { struct addrinfo hints1, hints2, *res1, *res2; int rc; if (!strlen(address1)) return 1; if (!strcmp(address1, address2)) return 1; memset(&hints1, 0, sizeof(struct addrinfo)); hints1.ai_family = AF_UNSPEC; hints1.ai_socktype = SOCK_STREAM; memset(&hints2, 0, sizeof(struct addrinfo)); hints2.ai_family = AF_UNSPEC; hints2.ai_socktype = SOCK_STREAM; /* * didn't match so we have to resolve to see if one is a dnsname * that matches a ip address. */ rc = getaddrinfo(address1, NULL, &hints1, &res1); if (rc) { log_debug(1, "Match error. Could not resolve %s: %s", address1, gai_strerror(rc)); return 0; } rc = getaddrinfo(address2, NULL, &hints2, &res2); if (rc) { log_debug(1, "Match error. Could not resolve %s: %s", address2, gai_strerror(rc)); rc = 0; goto free_res1; } if ((res1->ai_addrlen != res2->ai_addrlen) || memcmp(res1->ai_addr, res2->ai_addr, res2->ai_addrlen)) rc = 0; else rc = 1; freeaddrinfo(res2); free_res1: freeaddrinfo(res1); return rc; } int __iscsi_match_session(node_rec_t *rec, char *targetname, char *address, int port, struct iface_rec *iface, unsigned sid) { if (!rec) { log_debug(6, "no rec info to match\n"); return 1; } log_debug(6, "match session [%s,%s,%d][%s %s,%s,%s]:%u", rec->name, rec->conn[0].address, rec->conn[0].port, rec->iface.name, rec->iface.transport_name, rec->iface.hwaddress, rec->iface.ipaddress, rec->session.sid); if (iface) log_debug(6, "to [%s,%s,%d][%s %s,%s,%s]:%u", targetname, address, port, iface->name, iface->transport_name, iface->hwaddress, iface->ipaddress, sid); if (rec->session.sid && sid && rec->session.sid != sid) return 0; if (strlen(rec->name) && strcmp(rec->name, targetname)) return 0; if (!iscsi_addr_match(rec->conn[0].address, address)) return 0; if (rec->conn[0].port != -1 && port != rec->conn[0].port) return 0; if (!iface_match(&rec->iface, iface)) return 0; return 1; } int iscsi_match_session(void *data, struct session_info *info) { return __iscsi_match_session(data, info->targetname, info->persistent_address, info->persistent_port, &info->iface, info->sid); } int iscsi_match_session_count(void *data, struct session_info *info) { /* * iscsi_sysfs_for_each_session expects: * 0==match -1==nomatch >0==error * but iscsi_match_session returns: * 1==match 0==nomatch */ if (iscsi_match_session(data, info)) return 0; return -1; } int iscsi_match_target(void *data, struct session_info *info) { return __iscsi_match_session(data, info->targetname, info->persistent_address, info->persistent_port, NULL, MATCH_ANY_SID); } open-iscsi-2.0.873/usr/iscsi_util.h000066400000000000000000000014221175631155400171040ustar00rootroot00000000000000#ifndef ISCSI_UTIL_H #define ISCSI_UTIL_H #include struct node_rec; struct iface_rec; struct session_info; extern int oom_adjust(void); extern void daemon_init(void); extern int increase_max_files(void); extern char *str_to_ipport(char *str, int *port, int *tgpt); extern int iscsi_match_session(void *data, struct session_info *info); extern int iscsi_match_target(void *data, struct session_info *info); extern int iscsi_match_session_count(void *data, struct session_info *info); extern int __iscsi_match_session(struct node_rec *rec, char *targetname, char *address, int port, struct iface_rec *iface, unsigned sid); #define MATCH_ANY_SID 0 extern char *strstrip(char *s); extern char *cfg_get_string_param(char *pathname, const char *key); #endif open-iscsi-2.0.873/usr/iscsiadm.c000066400000000000000000002055031175631155400165320ustar00rootroot00000000000000/* * iSCSI Administration Utility * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * Copyright (C) 2011 Dell Inc. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include "initiator.h" #include "discovery.h" #include "log.h" #include "mgmt_ipc.h" #include "idbm.h" #include "iscsi_util.h" #include "transport.h" #include "version.h" #include "iscsi_sysfs.h" #include "list.h" #include "iscsi_settings.h" #include "fw_context.h" #include "iface.h" #include "session_info.h" #include "host.h" #include "sysdeps.h" #include "idbm_fields.h" #include "session_mgmt.h" #include "iscsid_req.h" #include "isns-proto.h" #include "iscsi_err.h" #include "iscsi_ipc.h" #include "iscsi_timer.h" static char program_name[] = "iscsiadm"; static char config_file[TARGET_NAME_MAXLEN]; extern struct iscsi_ipc *ipc; enum iscsiadm_mode { MODE_DISCOVERY, MODE_DISCOVERYDB, MODE_NODE, MODE_SESSION, MODE_HOST, MODE_IFACE, MODE_FW, MODE_PING, MODE_CHAP }; enum iscsiadm_op { OP_NOOP = 0x0, OP_NEW = 0x1, OP_DELETE = 0x2, OP_UPDATE = 0x4, OP_SHOW = 0x8, OP_NONPERSISTENT = 0x10, OP_APPLY = 0x20, OP_APPLY_ALL = 0x40 }; static struct option const long_options[] = { {"mode", required_argument, NULL, 'm'}, {"portal", required_argument, NULL, 'p'}, {"targetname", required_argument, NULL, 'T'}, {"interface", required_argument, NULL, 'I'}, {"op", required_argument, NULL, 'o'}, {"type", required_argument, NULL, 't'}, {"name", required_argument, NULL, 'n'}, {"value", required_argument, NULL, 'v'}, {"host", required_argument, NULL, 'H'}, {"sid", required_argument, NULL, 'r'}, {"rescan", no_argument, NULL, 'R'}, {"print", required_argument, NULL, 'P'}, {"discover", no_argument, NULL, 'D'}, {"login", no_argument, NULL, 'l'}, {"loginall", required_argument, NULL, 'L'}, {"logout", no_argument, NULL, 'u'}, {"logoutall", required_argument, NULL, 'U'}, {"stats", no_argument, NULL, 's'}, {"killiscsid", required_argument, NULL, 'k'}, {"debug", required_argument, NULL, 'd'}, {"show", no_argument, NULL, 'S'}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {"submode", required_argument, NULL, 'C'}, {"ip", required_argument, NULL, 'a'}, {"packetsize", required_argument, NULL, 'b'}, {"count", required_argument, NULL, 'c'}, {"interval", required_argument, NULL, 'i'}, {NULL, 0, NULL, 0}, }; static char *short_options = "RlDVhm:a:b:c:C:p:P:T:H:i:I:U:k:L:d:r:n:v:o:sSt:u"; static void usage(int status) { if (status != 0) fprintf(stderr, "Try `%s --help' for more information.\n", program_name); else { printf("\ iscsiadm -m discoverydb [ -hV ] [ -d debug_level ] [-P printlevel] [ -t type -p ip:port -I ifaceN ... [ -Dl ] ] | [ [ -p ip:port -t type] \ [ -o operation ] [ -n name ] [ -v value ] [ -lD ] ] \n\ iscsiadm -m discovery [ -hV ] [ -d debug_level ] [-P printlevel] [ -t type -p ip:port -I ifaceN ... [ -l ] ] | [ [ -p ip:port ] [ -l | -D ] ] \n\ iscsiadm -m node [ -hV ] [ -d debug_level ] [ -P printlevel ] [ -L all,manual,automatic ] [ -U all,manual,automatic ] [ -S ] [ [ -T targetname -p ip:port -I ifaceN ] [ -l | -u | -R | -s] ] \ [ [ -o operation ] [ -n name ] [ -v value ] ]\n\ iscsiadm -m session [ -hV ] [ -d debug_level ] [ -P printlevel] [ -r sessionid | sysfsdir [ -R | -u | -s ] [ -o operation ] [ -n name ] [ -v value ] ]\n\ iscsiadm -m iface [ -hV ] [ -d debug_level ] [ -P printlevel ] [ -I ifacename | -H hostno|MAC ] [ [ -o operation ] [ -n name ] [ -v value ] ] [ -C ping [ -a ip ] [ -b packetsize ] [ -c count ] [ -i interval ] ]\n\ iscsiadm -m fw [ -l ]\n\ iscsiadm -m host [ -P printlevel ] [ -H hostno|MAC ] [ -C chap [ -o operation ] [ -v chap_tbl_idx ] ]\n\ iscsiadm -k priority\n"); } exit(status); } static int str_to_op(char *str) { int op; if (!strcmp("new", str)) op = OP_NEW; else if (!strcmp("delete", str)) op = OP_DELETE; else if (!strcmp("update", str)) op = OP_UPDATE; else if (!strcmp("show", str)) op = OP_SHOW; else if (!strcmp("nonpersistent", str)) op = OP_NONPERSISTENT; else if (!strcmp("apply", str)) op = OP_APPLY; else if (!strcmp("applyall", str)) op = OP_APPLY_ALL; else op = OP_NOOP; return op; } static int str_to_mode(char *str) { int mode; if (!strcmp("discovery", str)) mode = MODE_DISCOVERY; else if (!strcmp("discoverydb", str)) mode = MODE_DISCOVERYDB; else if (!strcmp("node", str)) mode = MODE_NODE; else if (!strcmp("session", str)) mode = MODE_SESSION; else if (!strcmp("iface", str)) mode = MODE_IFACE; else if (!strcmp("fw", str)) mode = MODE_FW; else if (!strcmp("host", str)) mode = MODE_HOST; else mode = -1; return mode; } static int str_to_submode(char *str) { int sub_mode; if (!strcmp("ping", str)) sub_mode = MODE_PING; else if (!strcmp("chap", str)) sub_mode = MODE_CHAP; else sub_mode = -1; return sub_mode; } static int str_to_type(char *str) { int type; if (!strcmp("sendtargets", str) || !strcmp("st", str)) type = DISCOVERY_TYPE_SENDTARGETS; else if (!strcmp("slp", str)) type = DISCOVERY_TYPE_SLP; else if (!strcmp("isns", str)) type = DISCOVERY_TYPE_ISNS; else if (!strcmp("fw", str)) type = DISCOVERY_TYPE_FW; else type = -1; return type; } static void kill_iscsid(int priority) { iscsiadm_req_t req; iscsiadm_rsp_t rsp; int rc; /* * We only support SIGTERM like stoppage of iscsid for now. * In the future we can do something where we try go finish * up operations like login, error handling, etc, before * iscsid is stopped, and we can add different values to indicate * that the user wants iscsid to log out existing sessions before * exiting. */ if (priority != 0) { log_error("Invalid iscsid priority %d. Priority must be 0.", priority); return; } memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_IMMEDIATE_STOP; rc = iscsid_exec_req(&req, &rsp, 0); if (rc) { iscsi_err_print_msg(rc); log_error("Could not stop iscsid. Trying sending iscsid " "SIGTERM or SIGKILL signals manually\n"); } } /* * TODO: we can display how the ifaces are related to node records. * And we can add a scsi_host mode which would display how * sessions are related to hosts * (scsi_host and iscsi_sessions are the currently running instance of * a iface or node record). */ static int print_ifaces(struct iface_rec *iface, int info_level) { int err, num_found = 0; switch (info_level) { case 0: case -1: err = iface_for_each_iface(NULL, 0, &num_found, iface_print_flat); break; case 1: if (iface) { err = iface_conf_read(iface); if (err) { log_error("Could not read iface %s.\n", iface->name); return err; } iface_print_tree(NULL, iface); num_found = 1; } else err = iface_for_each_iface(NULL, 0, &num_found, iface_print_tree); break; default: log_error("Invalid info level %d. Try 0 - 1.", info_level); return ISCSI_ERR_INVAL; } if (!num_found) { log_error("No interfaces found."); err = ISCSI_ERR_NO_OBJS_FOUND; } return err; } static int match_startup_mode(node_rec_t *rec, char *mode) { if ((!strcmp(mode, "automatic") && rec->startup == ISCSI_STARTUP_AUTOMATIC) || (!strcmp(mode, "onboot") && rec->startup == ISCSI_STARTUP_ONBOOT) || (!strcmp(mode, "manual") && rec->startup == ISCSI_STARTUP_MANUAL) || !strcmp(mode, "all")) return 0; /* support conn or session startup params */ if ((!strcmp(mode, "automatic") && rec->conn[0].startup == ISCSI_STARTUP_AUTOMATIC) || (!strcmp(mode, "onboot") && rec->conn[0].startup == ISCSI_STARTUP_ONBOOT) || (!strcmp(mode, "manual") && rec->conn[0].startup == ISCSI_STARTUP_MANUAL) || !strcmp(mode, "all")) return 0; return -1; } static int for_each_session(struct node_rec *rec, iscsi_sysfs_session_op_fn *fn) { int err, num_found = 0; if (rec && rec->session.info) { num_found = 1; err = fn(rec, rec->session.info); } else { err = iscsi_sysfs_for_each_session(rec, &num_found, fn); } if (err) log_error("Could not execute operation on all sessions: %s", iscsi_err_to_str(err)); else if (!num_found) { log_error("No session found."); err = ISCSI_ERR_NO_OBJS_FOUND; } return err; } static int link_recs(void *data, struct node_rec *rec) { struct list_head *list = data; struct node_rec *rec_copy; rec_copy = calloc(1, sizeof(*rec_copy)); if (!rec_copy) return ISCSI_ERR_NOMEM; memcpy(rec_copy, rec, sizeof(*rec_copy)); INIT_LIST_HEAD(&rec_copy->list); list_add_tail(&rec_copy->list, list); return 0; } static int __logout_by_startup(void *data, struct list_head *list, struct session_info *info) { char *mode = data; node_rec_t rec; memset(&rec, 0, sizeof(node_rec_t)); if (idbm_rec_read(&rec, info->targetname, info->tpgt, info->persistent_address, info->persistent_port, &info->iface)) { /* * this is due to a HW driver or some other driver * not hooked in */ log_debug(7, "could not read data for [%s,%s.%d]\n", info->targetname, info->persistent_address, info->persistent_port); return -1; } /* multiple drivers could be connected to the same portal */ if (strcmp(rec.iface.transport_name, info->iface.transport_name)) return -1; /* * we always skip on boot because if the user killed this on * they would not be able to do anything */ if (rec.startup == ISCSI_STARTUP_ONBOOT) return -1; if (match_startup_mode(&rec, mode)) return -1; return iscsi_logout_portal(info, list); } static int logout_by_startup(char *mode) { int nr_found; int rc; if (!mode || !(!strcmp(mode, "automatic") || !strcmp(mode, "all") || !strcmp(mode,"manual"))) { log_error("Invalid logoutall option %s.", mode); usage(ISCSI_ERR_INVAL); return ISCSI_ERR_INVAL; } rc = iscsi_logout_portals(mode, &nr_found, 1, __logout_by_startup); if (rc == ISCSI_ERR_NO_OBJS_FOUND) log_error("No matching sessions found"); return rc; } struct startup_data { char *mode; struct list_head all_logins; struct list_head leading_logins; }; static int link_startup_recs(void *data, struct node_rec *rec) { struct startup_data *startup = data; struct node_rec *rec_copy; if (match_startup_mode(rec, startup->mode)) return -1; rec_copy = calloc(1, sizeof(*rec_copy)); if (!rec_copy) return ISCSI_ERR_NOMEM; memcpy(rec_copy, rec, sizeof(*rec_copy)); INIT_LIST_HEAD(&rec_copy->list); if (rec_copy->leading_login) list_add_tail(&rec_copy->list, &startup->leading_logins); else list_add_tail(&rec_copy->list, &startup->all_logins); return 0; } static int __do_leading_login(void *data, struct list_head *list, struct node_rec *rec) { struct iface_rec *pattern_iface = data; int nr_found; /* Skip any records that do not match the pattern iface */ if (!iface_match(pattern_iface, &rec->iface)) return -1; /* * If there is an existing session that matcthes the target, * the leading login is complete. */ if (iscsi_sysfs_for_each_session(rec, &nr_found, iscsi_match_target)) { log_debug(1, "Skipping %s: Already a session for that target", rec->name); return -1; } /* No existing session: Attempt a login. */ return iscsi_login_portal(NULL, list, rec); } static int login_by_startup(char *mode) { int nr_found = 0, err, rc; struct startup_data startup; if (!mode || !(!strcmp(mode, "automatic") || !strcmp(mode, "all") || !strcmp(mode,"manual") || !strcmp(mode, "onboot"))) { log_error("Invalid loginall option %s.", mode); usage(ISCSI_ERR_INVAL); return ISCSI_ERR_INVAL; } /* * Filter all node records that match the given 'mode' into 2 lists: * Those with leading_login enabled, and those without. */ startup.mode = mode; INIT_LIST_HEAD(&startup.all_logins); INIT_LIST_HEAD(&startup.leading_logins); err = idbm_for_each_rec(&nr_found, &startup, link_startup_recs); if (err && (!list_empty(&startup.all_logins) || !list_empty(&startup.leading_logins))) /* log msg and try to log into what we found */ log_error("Could not read all records: %s", iscsi_err_to_str(err)); else if (list_empty(&startup.all_logins) && list_empty(&startup.leading_logins)) { if (err) { log_error("Could not read node DB: %s.", iscsi_err_to_str(err)); } else { log_error("No records found"); err = ISCSI_ERR_NO_OBJS_FOUND; } return err; } rc = err; if (!list_empty(&startup.all_logins)) { log_debug(1, "Logging into normal (non-leading-login) portals"); /* Login all regular (non-leading-login) portals first */ err = iscsi_login_portals(NULL, &nr_found, 1, &startup.all_logins, iscsi_login_portal); if (err) log_error("Could not log into all portals"); if (err && !rc) rc = err; } if (!list_empty(&startup.leading_logins)) { /* * For each iface in turn, try to login all portals on that * iface that do not already have a session present. */ struct iface_rec *pattern_iface, *tmp_iface; struct node_rec *rec, *tmp_rec; struct list_head iface_list; int missed_leading_login = 0; log_debug(1, "Logging into leading-login portals"); INIT_LIST_HEAD(&iface_list); iface_link_ifaces(&iface_list); list_for_each_entry_safe(pattern_iface, tmp_iface, &iface_list, list) { log_debug(1, "Establishing leading-logins via iface %s", pattern_iface->name); err = iscsi_login_portals_safe(pattern_iface, &nr_found, 1, &startup.leading_logins, __do_leading_login); if (err) log_error("Could not log into all portals on " "%s, trying next interface", pattern_iface->name); /* * Note: We always try all iface records in case there * are targets that are associated with only a subset * of iface records. __do_leading_login already * prevents duplicate sessions if an iface has succeded * for a particular target. */ } /* * Double-check that all leading-login portals have at least * one session */ list_for_each_entry_safe(rec, tmp_rec, &startup.leading_logins, list) { if (!iscsi_sysfs_for_each_session(rec, &nr_found, iscsi_match_target)) missed_leading_login++; /* * Cleanup the list, since 'iscsi_login_portals_safe' * does not */ list_del(&rec->list); free(rec); } if (missed_leading_login) { log_error("Could not login all leading-login portals"); if (!rc) rc = ISCSI_ERR_FATAL_LOGIN; } } return rc; } /** * iscsi_logout_matched_portal - logout of targets matching the rec info * @data: record to session with * @list: list to add logout rec to * @info: session to match with rec */ static int iscsi_logout_matched_portal(void *data, struct list_head *list, struct session_info *info) { struct node_rec *pattern_rec = data; struct iscsi_transport *t; t = iscsi_sysfs_get_transport_by_sid(info->sid); if (!t) return -1; if (!iscsi_match_session(pattern_rec, info)) return -1; return iscsi_logout_portal(info, list); } static int rec_match_fn(void *data, node_rec_t *rec) { struct rec_op_data *op_data = data; if (!__iscsi_match_session(op_data->match_rec, rec->name, rec->conn[0].address, rec->conn[0].port, &rec->iface, rec->session.sid)) return -1; return op_data->fn(op_data->data, rec); } static int __for_each_matched_rec(int verbose, struct node_rec *rec, void *data, idbm_iface_op_fn *fn) { struct rec_op_data op_data; int nr_found = 0, rc; memset(&op_data, 0, sizeof(struct rec_op_data)); op_data.data = data; op_data.match_rec = rec; op_data.fn = fn; rc = idbm_for_each_rec(&nr_found, &op_data, rec_match_fn); if (rc) { if (verbose) log_error("Could not execute operation on all " "records: %s", iscsi_err_to_str(rc)); } else if (!nr_found) { if (verbose) log_error("No records found"); rc = ISCSI_ERR_NO_OBJS_FOUND; } return rc; } static int for_each_matched_rec(struct node_rec *rec, void *data, idbm_iface_op_fn *fn) { return __for_each_matched_rec(1, rec, data, fn); } static int login_portals(struct node_rec *pattern_rec) { struct list_head rec_list; int nr_found, rc, err; INIT_LIST_HEAD(&rec_list); err = for_each_matched_rec(pattern_rec, &rec_list, link_recs); if (err == ISCSI_ERR_NO_OBJS_FOUND) return err; else if (err && list_empty(&rec_list)) return err; rc = err; /* if there is an err but some recs then try to login to what we have */ err = iscsi_login_portals(pattern_rec, &nr_found, 1, &rec_list, iscsi_login_portal); if (err) log_error("Could not log into all portals"); if (err && !rc) rc = err; return rc; } static int print_nodes(int info_level, struct node_rec *rec) { struct node_rec tmp_rec; int rc = 0; switch (info_level) { case 0: case -1: rc = for_each_matched_rec(rec, NULL, idbm_print_node_flat); break; case 1: memset(&tmp_rec, 0, sizeof(node_rec_t)); rc = for_each_matched_rec(rec, &tmp_rec, idbm_print_node_and_iface_tree); break; default: log_error("Invalid info level %d. Try 0 or 1.", info_level); rc = ISCSI_ERR_INVAL; } return rc; } static char *get_config_file(void) { int rc; iscsiadm_req_t req; iscsiadm_rsp_t rsp; memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_CONFIG_FILE; rc = iscsid_exec_req(&req, &rsp, 1); if (rc) return NULL; if (rsp.u.config.var[0] != '\0') { strcpy(config_file, rsp.u.config.var); return config_file; } return NULL; } static int rescan_portal(void *data, struct session_info *info) { int host_no, err; if (!iscsi_match_session(data, info)) return -1; printf("Rescanning session [sid: %d, target: %s, portal: " "%s,%d]\n", info->sid, info->targetname, info->persistent_address, info->port); host_no = iscsi_sysfs_get_host_no_from_sid(info->sid, &err); if (err) { log_error("Could not rescan session sid %d.", info->sid); return err; } /* rescan each device to pick up size changes */ iscsi_sysfs_for_each_device(NULL, host_no, info->sid, iscsi_sysfs_rescan_device); /* now scan for new devices */ iscsi_sysfs_scan_host(host_no, 0); return 0; } static int session_stats(void *data, struct session_info *info) { int rc, i; iscsiadm_req_t req; iscsiadm_rsp_t rsp; if (!iscsi_match_session(data, info)) return -1; memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_SESSION_STATS; req.u.session.sid = info->sid; rc = iscsid_exec_req(&req, &rsp, 1); if (rc) return rc; printf("Stats for session [sid: %d, target: %s, portal: " "%s,%d]\n", info->sid, info->targetname, info->persistent_address, info->port); printf( "iSCSI SNMP:\n" "\ttxdata_octets: %lld\n" "\trxdata_octets: %lld\n" "\tnoptx_pdus: %u\n" "\tscsicmd_pdus: %u\n" "\ttmfcmd_pdus: %u\n" "\tlogin_pdus: %u\n" "\ttext_pdus: %u\n" "\tdataout_pdus: %u\n" "\tlogout_pdus: %u\n" "\tsnack_pdus: %u\n" "\tnoprx_pdus: %u\n" "\tscsirsp_pdus: %u\n" "\ttmfrsp_pdus: %u\n" "\ttextrsp_pdus: %u\n" "\tdatain_pdus: %u\n" "\tlogoutrsp_pdus: %u\n" "\tr2t_pdus: %u\n" "\tasync_pdus: %u\n" "\trjt_pdus: %u\n" "\tdigest_err: %u\n" "\ttimeout_err: %u\n", (unsigned long long)rsp.u.getstats.stats.txdata_octets, (unsigned long long)rsp.u.getstats.stats.rxdata_octets, rsp.u.getstats.stats.noptx_pdus, rsp.u.getstats.stats.scsicmd_pdus, rsp.u.getstats.stats.tmfcmd_pdus, rsp.u.getstats.stats.login_pdus, rsp.u.getstats.stats.text_pdus, rsp.u.getstats.stats.dataout_pdus, rsp.u.getstats.stats.logout_pdus, rsp.u.getstats.stats.snack_pdus, rsp.u.getstats.stats.noprx_pdus, rsp.u.getstats.stats.scsirsp_pdus, rsp.u.getstats.stats.tmfrsp_pdus, rsp.u.getstats.stats.textrsp_pdus, rsp.u.getstats.stats.datain_pdus, rsp.u.getstats.stats.logoutrsp_pdus, rsp.u.getstats.stats.r2t_pdus, rsp.u.getstats.stats.async_pdus, rsp.u.getstats.stats.rjt_pdus, rsp.u.getstats.stats.digest_err, rsp.u.getstats.stats.timeout_err); if (rsp.u.getstats.stats.custom_length) printf( "iSCSI Extended:\n"); for (i = 0; i < rsp.u.getstats.stats.custom_length; i++) { printf("\t%s: %llu\n", rsp.u.getstats.stats.custom[i].desc, (unsigned long long)rsp.u.getstats.stats.custom[i].value); } return 0; } static int add_static_rec(int *found, char *targetname, int tpgt, char *ip, int port, struct iface_rec *iface) { node_rec_t *rec; discovery_rec_t *drec; int rc; rec = calloc(1, sizeof(*rec)); if (!rec) { log_error("Could not allocate memory for node addition"); rc = ISCSI_ERR_NOMEM; goto done; } drec = calloc(1, sizeof(*drec)); if (!drec) { log_error("Could not allocate memory for node addition"); rc = ISCSI_ERR_NOMEM; goto free_rec; } drec->type = DISCOVERY_TYPE_STATIC; idbm_node_setup_from_conf(rec); strlcpy(rec->name, targetname, TARGET_NAME_MAXLEN); rec->tpgt = tpgt; rec->conn[0].port = port; strlcpy(rec->conn[0].address, ip, NI_MAXHOST); if (iface) { rc = iface_conf_read(iface); if (rc) { log_error("Could not read iface %s. Error %d", iface->name, rc); return rc; } iface_copy(&rec->iface, iface); } rc = idbm_add_node(rec, drec, 1); if (!rc) { (*found)++; printf("New iSCSI node [%s:" iface_fmt " %s,%d,%d %s] added\n", rec->iface.transport_name, iface_str(&rec->iface), ip, port, tpgt, targetname); } free(drec); free_rec: free(rec); done: return rc; } static int add_static_portal(int *found, void *data, char *targetname, int tpgt, char *ip, int port) { node_rec_t *rec = data; if (strlen(rec->conn[0].address) && strcmp(rec->conn[0].address, ip)) return -1; if (rec->conn[0].port != -1 && rec->conn[0].port != port) return -1; return add_static_rec(found, targetname, tpgt, ip, port, &rec->iface); } static int add_static_node(int *found, void *data, char *targetname) { node_rec_t *rec = data; if (!strlen(rec->name)) goto search; if (strcmp(rec->name, targetname)) return -1; if (!strlen(rec->conn[0].address)) goto search; return add_static_rec(found, targetname, rec->tpgt, rec->conn[0].address, rec->conn[0].port, &rec->iface); search: return idbm_for_each_portal(found, data, add_static_portal, targetname); } static int add_static_recs(struct node_rec *rec) { int rc, nr_found = 0; rc = idbm_for_each_node(&nr_found, rec, add_static_node); if (rc) goto done; /* success */ if (nr_found > 0) return 0; /* brand new target */ if (strlen(rec->name) && strlen(rec->conn[0].address)) { rc = add_static_rec(&nr_found, rec->name, rec->tpgt, rec->conn[0].address, rec->conn[0].port, &rec->iface); if (!rc) return 0; } done: log_error("Error while adding record: %s", iscsi_err_to_str(rc)); return rc; } /* * start sendtargets discovery process based on the * particular config */ static int do_offload_sendtargets(discovery_rec_t *drec, int host_no, int do_login) { drec->type = DISCOVERY_TYPE_OFFLOAD_SENDTARGETS; return discovery_offload_sendtargets(host_no, do_login, drec); } static int delete_node(void *data, struct node_rec *rec) { if (iscsi_check_for_running_session(rec)) { /* * We could log out the session for the user, but if * the session is being used the user may get something * they were not expecting (FS errors and a read only * remount). */ log_error("This command will remove the record [iface: %s, " "target: %s, portal: %s,%d], but a session is " "using it. Logout session then rerun command to " "remove record.", rec->iface.name, rec->name, rec->conn[0].address, rec->conn[0].port); return ISCSI_ERR_SESS_EXISTS; } return idbm_delete_node(rec); } static int delete_stale_rec(void *data, struct node_rec *rec) { struct list_head *new_rec_list = data; struct node_rec *new_rec; list_for_each_entry(new_rec, new_rec_list, list) { /* * We could also move this to idbm.c and instead of looping * over every node just loop over disc to node links. */ if (rec->disc_type != new_rec->disc_type || rec->disc_port != new_rec->disc_port || strcmp(rec->disc_address, new_rec->disc_address)) /* * if we are not from the same discovery source * ignore it */ return -1; if (__iscsi_match_session(rec, new_rec->name, new_rec->conn[0].address, new_rec->conn[0].port, &new_rec->iface, new_rec->session.sid)) return -1; } /* if there is a error we can continue on */ return delete_node(NULL, rec); } static int exec_disc_op_on_recs(discovery_rec_t *drec, struct list_head *rec_list, int info_level, int do_login, int op) { int rc = 0, err, found = 0; struct node_rec *new_rec, tmp_rec; /* clean up node db */ if (op & OP_DELETE) idbm_for_each_rec(&found, rec_list, delete_stale_rec); if (op & OP_NEW || op & OP_UPDATE) { /* now add/update records */ list_for_each_entry(new_rec, rec_list, list) { rc = idbm_add_node(new_rec, drec, op & OP_UPDATE); if (rc) log_error("Could not add/update " "[%s:" iface_fmt " %s,%d,%d %s]", new_rec->iface.transport_name, iface_str(&new_rec->iface), new_rec->conn[0].address, new_rec->conn[0].port, new_rec->tpgt, new_rec->name); } } memset(&tmp_rec, 0, sizeof(node_rec_t)); list_for_each_entry(new_rec, rec_list, list) { switch (info_level) { case 0: case -1: idbm_print_node_flat(NULL, new_rec); break; case 1: idbm_print_node_and_iface_tree(&tmp_rec, new_rec); } } if (!do_login) return 0; err = iscsi_login_portals(NULL, &found, 1, rec_list, iscsi_login_portal); if (err && !rc) rc = err; return rc; } static int do_software_sendtargets(discovery_rec_t *drec, struct list_head *ifaces, int info_level, int do_login, int op, int sync_drec) { struct list_head rec_list; struct node_rec *rec, *tmp; int rc; INIT_LIST_HEAD(&rec_list); /* * compat: if the user did not pass any op then we do all * ops for them */ if (!op) op = OP_NEW | OP_DELETE | OP_UPDATE; drec->type = DISCOVERY_TYPE_SENDTARGETS; /* * we will probably want to know how a specific iface and discovery * DB lined up, but for now just put all the targets found from * a discovery portal in one place */ if ((!(op & OP_NONPERSISTENT)) && sync_drec) { rc = idbm_add_discovery(drec); if (rc) { log_error("Could not add new discovery record."); return rc; } } rc = idbm_bind_ifaces_to_nodes(discovery_sendtargets, drec, ifaces, &rec_list); if (rc) { log_error("Could not perform SendTargets discovery: %s", iscsi_err_to_str(rc)); return rc; } else if (list_empty(&rec_list)) { log_error("No portals found"); return ISCSI_ERR_NO_OBJS_FOUND; } rc = exec_disc_op_on_recs(drec, &rec_list, info_level, do_login, op); list_for_each_entry_safe(rec, tmp, &rec_list, list) { list_del(&rec->list); free(rec); } return rc; } static int do_sendtargets(discovery_rec_t *drec, struct list_head *ifaces, int info_level, int do_login, int op, int sync_drec) { struct iface_rec *tmp, *iface; int rc, host_no; struct iscsi_transport *t; if (list_empty(ifaces)) { ifaces = NULL; goto sw_st; } /* we allow users to mix hw and sw iscsi so we have to sort it out */ list_for_each_entry_safe(iface, tmp, ifaces, list) { rc = iface_conf_read(iface); if (rc) { log_error("Could not read iface info for %s. " "Make sure a iface config with the file " "name and iface.iscsi_ifacename %s is in %s.", iface->name, iface->name, IFACE_CONFIG_DIR); list_del(&iface->list); free(iface); continue; } /* check for transport name first to make sure it is loaded */ t = iscsi_sysfs_get_transport_by_name(iface->transport_name); if (!t) { log_error("Could not load transport %s." "Dropping interface %s.", iface->transport_name, iface->name); list_del(&iface->list); free(iface); continue; } host_no = iscsi_sysfs_get_host_no_from_hwinfo(iface, &rc); if (rc || host_no == -1) { log_debug(1, "Could not match iface" iface_fmt " to " "host.", iface_str(iface)); /* try software iscsi */ continue; } if (t->caps & CAP_SENDTARGETS_OFFLOAD) { do_offload_sendtargets(drec, host_no, do_login); list_del(&iface->list); free(iface); } } if (list_empty(ifaces)) return ISCSI_ERR_NO_OBJS_FOUND; sw_st: return do_software_sendtargets(drec, ifaces, info_level, do_login, op, sync_drec); } static int do_isns(discovery_rec_t *drec, struct list_head *ifaces, int info_level, int do_login, int op) { struct list_head rec_list; struct node_rec *rec, *tmp; int rc; INIT_LIST_HEAD(&rec_list); /* * compat: if the user did not pass any op then we do all * ops for them */ if (!op) op = OP_NEW | OP_DELETE | OP_UPDATE; drec->type = DISCOVERY_TYPE_ISNS; rc = idbm_bind_ifaces_to_nodes(discovery_isns, drec, ifaces, &rec_list); if (rc) { log_error("Could not perform iSNS discovery: %s", iscsi_err_to_str(rc)); return rc; } else if (list_empty(&rec_list)) { log_error("No portals found"); return ISCSI_ERR_NO_OBJS_FOUND; } rc = exec_disc_op_on_recs(drec, &rec_list, info_level, do_login, op); list_for_each_entry_safe(rec, tmp, &rec_list, list) { list_del(&rec->list); free(rec); } return rc; } static int verify_mode_params(int argc, char **argv, char *allowed, int skip_m) { int ch, longindex; int ret = 0; optind = 0; while ((ch = getopt_long(argc, argv, short_options, long_options, &longindex)) >= 0) { if (!strchr(allowed, ch)) { if (ch == 'm' && skip_m) continue; ret = ch; break; } } return ret; } static void catch_sigint( int signo ) { log_warning("caught SIGINT, exiting..."); exit(1); } static int iface_apply_net_config(struct iface_rec *iface, int op) { int rc = ISCSI_ERR; uint32_t host_no; int param_count; int param_used; int iface_all = 0; int i; struct iovec *iovs = NULL; struct iovec *iov = NULL; struct iscsi_transport *t = NULL; int fd; log_debug(8, "Calling iscsid, to apply net config for" "iface.name = %s\n", iface->name); if (op == OP_APPLY_ALL) iface_all = 1; param_count = iface_get_param_count(iface, iface_all); if (!param_count) { log_error("Nothing to configure."); return ISCSI_SUCCESS; } /* * TODO: create a nicer interface where the caller does not have * know the packet/hdr details */ /* +2 for event and nlmsghdr */ param_count += 2; iovs = calloc((param_count * sizeof(struct iovec)), sizeof(char)); if (!iovs) { log_error("Out of Memory."); return ISCSI_ERR_NOMEM; } /* param_used gives actual number of iovecs used for netconfig */ param_used = iface_build_net_config(iface, iface_all, iovs); if (!param_used) { log_error("Build netconfig failed."); goto free_buf; } t = iscsi_sysfs_get_transport_by_name(iface->transport_name); if (!t) { log_error("Can't find transport."); goto free_buf; } host_no = iscsi_sysfs_get_host_no_from_hwinfo(iface, &rc); if (host_no == -1) { log_error("Can't find host_no."); goto free_buf; } rc = ISCSI_ERR; fd = ipc->ctldev_open(); if (fd < 0) { log_error("Netlink open failed."); goto free_buf; } rc = ipc->set_net_config(t->handle, host_no, iovs, param_count); if (rc < 0) log_error("Set net_config failed. errno=%d", errno); ipc->ctldev_close(); free_buf: /* start at 2, because 0 is for nlmsghdr and 1 for event */ iov = iovs + 2; for (i = 0; i < param_used; i++, iov++) { if (iov->iov_base) free(iov->iov_base); } free(iovs); if (rc) return ISCSI_ERR; return ISCSI_SUCCESS; } static int get_host_chap_info(uint32_t host_no) { struct iscsi_transport *t = NULL; struct iscsi_chap_rec *crec = NULL; char *req_buf = NULL; uint32_t valid_chap_entries; uint32_t num_entries; uint16_t chap_tbl_idx = 0; int rc = 0; int fd, i = 0; t = iscsi_sysfs_get_transport_by_hba(host_no); if (!t) { log_error("Could not match hostno %d to " "transport.", host_no); rc = ISCSI_ERR_TRANS_NOT_FOUND; goto exit_chap_info; } num_entries = MAX_CHAP_BUF_SZ / sizeof(*crec); req_buf = calloc(1, REQ_CHAP_BUF_SZ); if (!req_buf) { log_error("Could not allocate memory for CHAP request."); rc = ISCSI_ERR_NOMEM; goto exit_chap_info; } fd = ipc->ctldev_open(); if (fd < 0) { rc = ISCSI_ERR_INTERNAL; log_error("Netlink open failed."); goto exit_chap_info; } get_chap: memset(req_buf, 0, REQ_CHAP_BUF_SZ); rc = ipc->get_chap(t->handle, host_no, chap_tbl_idx, num_entries, req_buf, &valid_chap_entries); if (rc < 0) { log_error("get_chap_info failed. errno=%d", errno); rc = ISCSI_ERR; goto exit_chap_info; } crec = (struct iscsi_chap_rec *) (req_buf + sizeof(struct iscsi_uevent)); if (valid_chap_entries) chap_tbl_idx = (crec + (valid_chap_entries - 1))->chap_tbl_idx + 1; /* print chap info */ for (i = 0; i < valid_chap_entries; i++) { idbm_print_host_chap_info(crec); crec++; } if (valid_chap_entries != num_entries) goto exit_chap_info; else goto get_chap; ipc->ctldev_close(); exit_chap_info: if (req_buf) free(req_buf); return rc; } static int delete_host_chap_info(uint32_t host_no, char *value) { struct iscsi_transport *t = NULL; int fd, rc = 0; uint16_t chap_tbl_idx; if (!value) { log_error("CHAP deletion requires --value=table_index."); return ISCSI_ERR_INVAL; } chap_tbl_idx = (uint16_t)atoi(value); t = iscsi_sysfs_get_transport_by_hba(host_no); if (!t) { log_error("Could not match hostno %d to " "transport.", host_no); rc = ISCSI_ERR_TRANS_NOT_FOUND; goto exit_delete_chap; } fd = ipc->ctldev_open(); if (fd < 0) { log_error("Netlink open failed."); rc = ISCSI_ERR_INTERNAL; goto exit_delete_chap; } log_info("Deleteing CHAP index: %d\n", chap_tbl_idx); rc = ipc->delete_chap(t->handle, host_no, chap_tbl_idx); if (rc < 0) { log_error("CHAP Delete failed."); if (rc == -EBUSY) { rc = ISCSI_ERR_BUSY; log_error("CHAP index %d is in use.", chap_tbl_idx); } else rc = ISCSI_ERR; } ipc->ctldev_close(); exit_delete_chap: return rc; } static int exec_host_chap_op(int op, int info_level, uint32_t host_no, char *value) { int rc = ISCSI_ERR_INVAL; switch (op) { case OP_SHOW: rc = get_host_chap_info(host_no); break; case OP_DELETE: rc = delete_host_chap_info(host_no, value); break; default: log_error("Invalid operation."); break; } return rc; } static int verify_iface_params(struct list_head *params, struct node_rec *rec) { struct user_param *param; list_for_each_entry(param, params, list) { if (!strcmp(param->name, IFACE_ISCSINAME)) { log_error("Can not update " "iface.iscsi_ifacename. Delete it, " "and then create a new one."); return ISCSI_ERR_INVAL; } if (iface_is_bound_by_hwaddr(&rec->iface) && !strcmp(param->name, IFACE_NETNAME)) { log_error("Can not update interface binding " "from hwaddress to net_ifacename. " "You must delete the interface and " "create a new one"); return ISCSI_ERR_INVAL; } if (iface_is_bound_by_netdev(&rec->iface) && !strcmp(param->name, IFACE_HWADDR)) { log_error("Can not update interface binding " "from net_ifacename to hwaddress. " "You must delete the interface and " "create a new one"); return ISCSI_ERR_INVAL; } } return 0; } /* TODO: merge iter helpers and clean them up, so we can use them here */ static int exec_iface_op(int op, int do_show, int info_level, struct iface_rec *iface, uint32_t host_no, struct list_head *params) { struct host_info hinfo; struct node_rec *rec = NULL; int rc = 0; switch (op) { case OP_NEW: if (!iface) { log_error("Could not add interface. No interface " "passed in."); return EINVAL; } rec = idbm_create_rec(NULL, -1, NULL, -1, iface, 0); if (rec && iscsi_check_for_running_session(rec)) { rc = ISCSI_ERR_SESS_EXISTS; goto new_fail; } iface_setup_defaults(iface); rc = iface_conf_write(iface); if (rc) goto new_fail; printf("New interface %s added\n", iface->name); break; new_fail: log_error("Could not create new interface %s.", iface->name); break; case OP_DELETE: if (!iface) { log_error("Could not delete interface. No interface " "passed in."); return ISCSI_ERR_INVAL; } rec = idbm_create_rec(NULL, -1, NULL, -1, iface, 1); if (!rec) { rc = ISCSI_ERR_INVAL; goto delete_fail; } /* logout and delete records using it first */ rc = __for_each_matched_rec(0, rec, NULL, delete_node); if (rc && rc != ISCSI_ERR_NO_OBJS_FOUND) goto delete_fail; rc = iface_conf_delete(iface); if (rc) goto delete_fail; printf("%s unbound and deleted.\n", iface->name); break; delete_fail: log_error("Could not delete iface %s: %s", iface->name, iscsi_err_to_str(rc)); break; case OP_UPDATE: if (!iface || list_empty(params)) { log_error("Update requires name, value, and iface."); rc = ISCSI_ERR_INVAL; break; } rec = idbm_create_rec(NULL, -1, NULL, -1, iface, 1); if (!rec) { rc = ISCSI_ERR_INVAL; goto update_fail; } if (iscsi_check_for_running_session(rec)) log_warning("Updating iface while iscsi sessions " "are using it. You must logout the running " "sessions then log back in for the " "new settings to take affect."); rc = verify_iface_params(params, rec); if (rc) break; /* pass rec's iface because it has the db values */ rc = iface_conf_update(params, &rec->iface); if (rc) goto update_fail; rc = __for_each_matched_rec(0, rec, params, idbm_node_set_param); if (rc == ISCSI_ERR_NO_OBJS_FOUND) rc = 0; else if (rc) goto update_fail; printf("%s updated.\n", iface->name); break; update_fail: log_error("Could not update iface %s: %s", iface->name, iscsi_err_to_str(rc)); break; case OP_APPLY: if (!iface) { log_error("Apply requires iface."); rc = ISCSI_ERR_INVAL; break; } rc = iface_conf_read(iface); if (rc) { log_error("Could not read iface %s (%d).", iface->name, rc); break; } rc = iface_apply_net_config(iface, op); if (rc) { log_error("Could not apply net configuration: %s", iscsi_err_to_str(rc)); break; } printf("%s applied.\n", iface->name); break; case OP_APPLY_ALL: if (host_no == -1) { log_error("Applyall requires a host number or MAC " "passed in with the --host argument."); rc = ISCSI_ERR_INVAL; break; } /* * Need to get other iface info like transport. */ memset(&hinfo, 0, sizeof(struct host_info)); hinfo.host_no = host_no; if (iscsi_sysfs_get_hostinfo_by_host_no(&hinfo)) { log_error("Could not match host%u to ifaces.", host_no); rc = ISCSI_ERR_INVAL; break; } rc = iface_apply_net_config(&hinfo.iface, op); if (rc) { log_error("Could not apply net configuration: %s", iscsi_err_to_str(rc)); break; } printf("Applied settings to ifaces attached to host%u.\n", host_no); break; default: if (!iface || (iface && info_level > 0)) { if (op == OP_NOOP || op == OP_SHOW) rc = print_ifaces(iface, info_level); else rc = ISCSI_ERR_INVAL; } else { rc = iface_conf_read(iface); if (!rc) idbm_print_iface_info(&do_show, iface); else log_error("Could not read iface %s (%d).", iface->name, rc); } } if (rec) free(rec); return rc; } static int verify_node_params(struct list_head *params, struct node_rec *rec) { struct user_param *param; if (list_empty(params)) { log_error("update requires name and value"); return ISCSI_ERR_INVAL; } list_for_each_entry(param, params, list) { /* compat - old tools used node and iface transport name */ if (!strncmp(param->name, "iface.", 6) && strcmp(param->name, "iface.transport_name")) { log_error("Cannot modify %s. Use iface mode to update " "this value.", param->name); return ISCSI_ERR_INVAL; } if (!strcmp(param->name, "node.transport_name")) { free(param->name); param->name = strdup("iface.transport_name"); if (!param->name) { log_error("Could not allocate memory for " "param."); return ISCSI_ERR_NOMEM; } } /* * tmp hack - we added compat crap above for the transport, * but want to fix Doran's issue in this release too. However * his patch is too harsh on many settings and we do not have * time to update apps so we have this tmp hack until we * can settle on a good interface that distros can use * and we can mark stable. */ if (!strcmp(param->name, "iface.transport_name")) { if (iscsi_check_for_running_session(rec)) { log_warning("Cannot modify node/iface " "transport name while a session " "is using it. Log out the session " "then update record."); return ISCSI_ERR_SESS_EXISTS; } } } return 0; } /* TODO cleanup arguments */ static int exec_node_op(int op, int do_login, int do_logout, int do_show, int do_rescan, int do_stats, int info_level, struct node_rec *rec, struct list_head *params) { int rc = 0; if (rec) log_debug(2, "%s: %s:%s node [%s,%s,%d] sid %u", __FUNCTION__, rec->iface.transport_name, rec->iface.name, rec->name, rec->conn[0].address, rec->conn[0].port, rec->session.sid); if (op == OP_NEW) { rc = add_static_recs(rec); goto out; } if (do_rescan) { rc = for_each_session(rec, rescan_portal); goto out; } if (do_stats) { rc = for_each_session(rec, session_stats); goto out; } if (do_login && do_logout) { log_error("Invalid parameters. Both login and logout passed in"); rc = ISCSI_ERR_INVAL; goto out; } if ((do_login || do_logout) && op > OP_NOOP) { log_error("Invalid parameters. Login/logout and op passed in"); rc = ISCSI_ERR_INVAL; goto out; } if ((!do_login && !do_logout && op == OP_NOOP) && (!strlen(rec->name) && !strlen(rec->conn[0].address) && !strlen(rec->iface.name))) { rc = print_nodes(info_level, rec); goto out; } if (do_login) { rc = login_portals(rec); goto out; } if (do_logout) { int nr_found; rc = iscsi_logout_portals(rec, &nr_found, 1, iscsi_logout_matched_portal); if (rc == ISCSI_ERR_NO_OBJS_FOUND) log_error("No matching sessions found"); goto out; } if (op == OP_NOOP || (!do_login && !do_logout && op == OP_SHOW)) { rc = for_each_matched_rec(rec, &do_show, idbm_print_node_info); goto out; } if (op == OP_UPDATE) { rc = verify_node_params(params, rec); if (rc) goto out; rc = for_each_matched_rec(rec, params, idbm_node_set_param); goto out; } else if (op == OP_DELETE) { rc = for_each_matched_rec(rec, NULL, delete_node); goto out; } else { log_error("operation is not supported."); rc = ISCSI_ERR_INVAL; goto out; } out: return rc; } static int exec_fw_disc_op(discovery_rec_t *drec, struct list_head *ifaces, int info_level, int do_login, int op) { struct list_head targets, rec_list, new_ifaces; struct iface_rec *iface, *tmp_iface; struct node_rec *rec, *tmp_rec; int rc = 0; INIT_LIST_HEAD(&targets); INIT_LIST_HEAD(&rec_list); INIT_LIST_HEAD(&new_ifaces); /* * compat: if the user did not pass any op then we do all * ops for them */ if (!op) op = OP_NEW | OP_DELETE | OP_UPDATE; /* * if a user passed in ifaces then we use them and ignore the ibft * net info */ if (!list_empty(ifaces)) { list_for_each_entry_safe(iface, tmp_iface, ifaces, list) { rc = iface_conf_read(iface); if (rc) { log_error("Could not read iface info for %s. " "Make sure a iface config with the " "file name and iface.iscsi_ifacename " "%s is in %s.", iface->name, iface->name, IFACE_CONFIG_DIR); list_del_init(&iface->list); free(iface); continue; } } goto discover_fw_tgts; } /* * Next, check if we see any offload cards. If we do then * we make a iface if needed. * * Note1: if there is not a offload card we do not setup * software iscsi binding with the nic used for booting, * because we do not know if that was intended. * * Note2: we assume that the user probably wanted to access * all targets through all the ifaces instead of being limited * to what you can export in ibft. */ rc = fw_get_targets(&targets); if (rc) { log_error("Could not get list of targets from firmware. " "(err %d)\n", rc); return rc; } rc = iface_create_ifaces_from_boot_contexts(&new_ifaces, &targets); if (rc) goto done; if (!list_empty(&new_ifaces)) ifaces = &new_ifaces; discover_fw_tgts: rc = idbm_bind_ifaces_to_nodes(discovery_fw, drec, ifaces, &rec_list); if (rc) log_error("Could not perform fw discovery.\n"); else rc = exec_disc_op_on_recs(drec, &rec_list, info_level, do_login, op); done: fw_free_targets(&targets); list_for_each_entry_safe(iface, tmp_iface, &new_ifaces, list) { list_del(&iface->list); free(iface); } list_for_each_entry_safe(rec, tmp_rec, &rec_list, list) { list_del(&rec->list); free(rec); } return rc; } static int exec_fw_op(discovery_rec_t *drec, struct list_head *ifaces, int info_level, int do_login, int op) { struct boot_context *context; struct list_head targets, rec_list; struct node_rec *rec; int rc = 0; INIT_LIST_HEAD(&targets); INIT_LIST_HEAD(&rec_list); if (drec) return exec_fw_disc_op(drec, ifaces, info_level, do_login, op); /* The following ops do not interact with the DB */ rc = fw_get_targets(&targets); if (rc) { log_error("Could not get list of targets from firmware. " "(err %d)\n", rc); return rc; } if (do_login) { list_for_each_entry(context, &targets, list) { rec = idbm_create_rec_from_boot_context(context); if (!rec) { log_error("Could not convert firmware info to " "node record.\n"); rc = ISCSI_ERR_NOMEM; break; } iscsi_login_portal(NULL, NULL, rec); free(rec); } } else { list_for_each_entry(context, &targets, list) fw_print_entry(context); } fw_free_targets(&targets); return rc; } static void setup_drec_defaults(int type, char *ip, int port, struct discovery_rec *drec) { switch (type) { case DISCOVERY_TYPE_ISNS: idbm_isns_defaults(&drec->u.isns); break; case DISCOVERY_TYPE_SENDTARGETS: idbm_sendtargets_defaults(&drec->u.sendtargets); break; default: log_error("Invalid disc type."); } strlcpy(drec->address, ip, sizeof(drec->address)); drec->port = port; drec->type = type; } /** * exec_discover - prep, add, read and exec discovery on drec * @type: discovery type * @ip: IP address * @port: port * @ifaces: list of ifaces to bind to * @info_level: print level * @do_login: set to 1 if discovery function should also log into portals found * @do_discover: set to 1 if discovery was requested * @op: ops passed in by user * @drec: discovery rec struct * * This function determines what type of op needs to be executed * and will read and add a drec, and perform discovery if needed. * * returns: * Greater than 0 - error * 0 - op/discovery completed * -1 - exec db op */ static int exec_discover(int disc_type, char *ip, int port, struct list_head *ifaces, int info_level, int do_login, int do_discover, int op, struct discovery_rec *drec) { int rc; if (ip == NULL) { log_error("Please specify portal as [:]"); return ISCSI_ERR_INVAL; } if (op & OP_NEW && !do_discover) { setup_drec_defaults(disc_type, ip, port, drec); rc = idbm_add_discovery(drec); if (rc) { log_error("Could not add new discovery record."); return rc; } else { printf("New discovery record for [%s,%d] added.\n", ip, port); return 0; } } rc = idbm_discovery_read(drec, disc_type, ip, port); if (rc) { if (!do_discover) { log_error("Discovery record [%s,%d] not found.", ip, port); return rc; } /* Just add default rec for user */ log_debug(1, "Discovery record [%s,%d] not found!", ip, port); setup_drec_defaults(disc_type, ip, port, drec); if (!(op & OP_NONPERSISTENT)) { rc = idbm_add_discovery(drec); if (rc) { log_error("Could not add new discovery " "record."); return rc; } } } else if (!do_discover) return -1; rc = 0; switch (disc_type) { case DISCOVERY_TYPE_SENDTARGETS: /* * idbm_add_discovery call above handles drec syncing so * we always pass in 0 here. */ rc = do_sendtargets(drec, ifaces, info_level, do_login, op, 0); break; case DISCOVERY_TYPE_ISNS: rc = do_isns(drec, ifaces, info_level, do_login, op); break; default: log_error("Unsupported discovery type."); break; } return rc; } static int exec_disc2_op(int disc_type, char *ip, int port, struct list_head *ifaces, int info_level, int do_login, int do_discover, int op, struct list_head *params, int do_show) { struct discovery_rec drec; int rc = 0; memset(&drec, 0, sizeof(struct discovery_rec)); if (disc_type != -1) drec.type = disc_type; switch (disc_type) { case DISCOVERY_TYPE_SENDTARGETS: if (port < 0) port = ISCSI_LISTEN_PORT; rc = exec_discover(disc_type, ip, port, ifaces, info_level, do_login, do_discover, op, &drec); if (rc < 0) goto do_db_op; goto done; case DISCOVERY_TYPE_SLP: log_error("SLP discovery is not fully implemented yet."); rc = ISCSI_ERR_INVAL; goto done; case DISCOVERY_TYPE_ISNS: if (port < 0) port = ISNS_DEFAULT_PORT; rc = exec_discover(disc_type, ip, port, ifaces, info_level, do_login, do_discover, op, &drec); if (rc < 0) goto do_db_op; goto done; case DISCOVERY_TYPE_FW: if (!do_discover) { log_error("Invalid command. Possibly missing " "--discover argument."); rc = ISCSI_ERR_INVAL; goto done; } drec.type = DISCOVERY_TYPE_FW; rc = exec_fw_op(&drec, ifaces, info_level, do_login, op); goto done; default: rc = ISCSI_ERR_INVAL; if (!ip) { if (op == OP_NOOP || op == OP_SHOW) { if (idbm_print_all_discovery(info_level)) /* successfully found some recs */ rc = 0; else rc = ISCSI_ERR_NO_OBJS_FOUND; } else log_error("Invalid operation. Operation not " "supported."); } else if (op) log_error("Invalid command. Possibly missing discovery " "--type."); else log_error("Invalid command. Portal not needed or " "Possibly missing discovery --type."); goto done; } do_db_op: rc = 0; if (op == OP_NOOP || op == OP_SHOW) { if (!idbm_print_discovery_info(&drec, do_show)) { log_error("No records found"); rc = ISCSI_ERR_NO_OBJS_FOUND; } } else if (op == OP_DELETE) { rc = idbm_delete_discovery(&drec); if (rc) log_error("Unable to delete record!"); } else if (op == OP_UPDATE) { if (list_empty(params)) { log_error("Update requires name and value."); rc = ISCSI_ERR_INVAL; goto done; } rc = idbm_discovery_set_param(params, &drec); } else { log_error("Operation is not supported."); rc = ISCSI_ERR_INVAL; goto done; } done: return rc; } static int exec_disc_op(int disc_type, char *ip, int port, struct list_head *ifaces, int info_level, int do_login, int do_discover, int op, struct list_head *params, int do_show) { struct discovery_rec drec; int rc = 0; memset(&drec, 0, sizeof(struct discovery_rec)); switch (disc_type) { case DISCOVERY_TYPE_SENDTARGETS: drec.type = DISCOVERY_TYPE_SENDTARGETS; if (port < 0) port = ISCSI_LISTEN_PORT; if (ip == NULL) { log_error("Please specify portal as " "[:]"); rc = ISCSI_ERR_INVAL; goto done; } idbm_sendtargets_defaults(&drec.u.sendtargets); strlcpy(drec.address, ip, sizeof(drec.address)); drec.port = port; rc = do_sendtargets(&drec, ifaces, info_level, do_login, op, 1); if (rc) goto done; break; case DISCOVERY_TYPE_SLP: log_error("SLP discovery is not fully implemented yet."); rc = ISCSI_ERR_INVAL; break; case DISCOVERY_TYPE_ISNS: if (!ip) { log_error("Please specify portal as " ":[]"); rc = ISCSI_ERR_INVAL; goto done; } strlcpy(drec.address, ip, sizeof(drec.address)); if (port < 0) drec.port = ISNS_DEFAULT_PORT; else drec.port = port; rc = do_isns(&drec, ifaces, info_level, do_login, op); if (rc) goto done; break; case DISCOVERY_TYPE_FW: drec.type = DISCOVERY_TYPE_FW; rc = exec_fw_op(&drec, ifaces, info_level, do_login, op); break; default: if (ip) { /* * We only have sendtargets disc recs in discovery * mode, so we can hardcode the port check to the * iscsi default here. * * For isns or slp recs then discovery db mode * must be used. */ if (port < 0) port = ISCSI_LISTEN_PORT; if (idbm_discovery_read(&drec, DISCOVERY_TYPE_SENDTARGETS, ip, port)) { log_error("Discovery record [%s,%d] " "not found!", ip, port); rc = ISCSI_ERR_INVAL; goto done; } if ((do_discover || do_login) && drec.type == DISCOVERY_TYPE_SENDTARGETS) { rc = do_sendtargets(&drec, ifaces, info_level, do_login, op, 0); } else if (op == OP_NOOP || op == OP_SHOW) { if (!idbm_print_discovery_info(&drec, do_show)) { log_error("No records found"); rc = ISCSI_ERR_NO_OBJS_FOUND; } } else if (op == OP_DELETE) { rc = idbm_delete_discovery(&drec); if (rc) log_error("Unable to delete record!"); } else if (op == OP_UPDATE || op == OP_NEW) { log_error("Operations new and update for " "discovery mode is not supported. " "Use discoverydb mode."); rc = ISCSI_ERR_INVAL; goto done; } else { log_error("Invalid operation."); rc = ISCSI_ERR_INVAL; goto done; } } else if (op == OP_NOOP || op == OP_SHOW) { if (!idbm_print_all_discovery(info_level)) rc = ISCSI_ERR_NO_OBJS_FOUND; goto done; } else { log_error("Invalid operation."); rc = ISCSI_ERR_INVAL; goto done; } /* fall through */ } done: return rc; } static uint32_t parse_host_info(char *optarg, int *rc) { int err = 0; uint32_t host_no = -1; *rc = 0; if (strstr(optarg, ":")) { transport_probe_for_offload(); host_no = iscsi_sysfs_get_host_no_from_hwaddress(optarg, &err); if (err) { log_error("Could not match MAC to host."); *rc = ISCSI_ERR_INVAL; } } else { host_no = strtoul(optarg, NULL, 10); if (errno) { log_error("Invalid host no %s. %s.", optarg, strerror(errno)); *rc = ISCSI_ERR_INVAL; } } return host_no; } static char *iscsi_ping_stat_strs[] = { /* ISCSI_PING_SUCCESS */ "success", /* ISCSI_PING_FW_DISABLED */ "firmware disabled", /* ISCSI_PING_IPADDR_INVALID */ "invalid IP address", /* ISCSI_PING_LINKLOCAL_IPV6_ADDR_INVALID */ "invalid link local IPv6 address", /* ISCSI_PING_TIMEOUT */ "timed out", /* ISCSI_PING_INVALID_DEST_ADDR */ "invalid destination address", /* ISCSI_PING_OVERSIZE_PACKET */ "oversized packet", /* ISCSI_PING_ICMP_ERROR */ "ICMP error", /* ISCSI_PING_MAX_REQ_EXCEEDED */ "Max request exceeded", /* ISCSI_PING_NO_ARP_RECEIVED */ "No ARP response received", }; static char *iscsi_ping_stat_to_str(uint32_t status) { if (status < 0 || status > ISCSI_PING_NO_ARP_RECEIVED) { log_error("Invalid ping status %u\n", status); return NULL; } return iscsi_ping_stat_strs[status]; } static int exec_ping_op(struct iface_rec *iface, char *ip, int size, int count, int interval) { int rc = ISCSI_ERR; uint32_t iface_type = ISCSI_IFACE_TYPE_IPV4; struct iscsi_transport *t = NULL; uint32_t host_no, status = 0; struct sockaddr_storage addr; int i; if (!iface) { log_error("Ping requires iface."); rc = ISCSI_ERR_INVAL; goto ping_exit; } if (!ip) { log_error("Ping requires destination ipaddress."); rc = ISCSI_ERR_INVAL; goto ping_exit; } if (size <= 0) { log_error("Invalid packet size: %d.", size); rc = ISCSI_ERR_INVAL; goto ping_exit; } if (count <= 0) { log_error("Invalid number of packets to transmit: %d.", count); rc = ISCSI_ERR_INVAL; goto ping_exit; } if (interval < 0) { log_error("Invalid timing interval: %d.", interval); rc = ISCSI_ERR_INVAL; goto ping_exit; } rc = iface_conf_read(iface); if (rc) { log_error("Could not read iface %s (%d).", iface->name, rc); goto ping_exit; } iface_type = iface_get_iptype(iface); t = iscsi_sysfs_get_transport_by_name(iface->transport_name); if (!t) { log_error("Can't find transport."); rc = ISCSI_ERR_INVAL; goto ping_exit; } host_no = iscsi_sysfs_get_host_no_from_hwinfo(iface, &rc); if (host_no == -1) { log_error("Can't find host_no."); rc = ISCSI_ERR_INVAL; goto ping_exit; } rc = resolve_address(ip, NULL, &addr); if (rc) { log_error("Invalid IP address."); rc = ISCSI_ERR_INVAL; goto ping_exit; } /* TODO: move this. It is needed by interface for pid */ srand(time(NULL)); for (i = 1; i <= count; i++) { /* * To support drivers like bnx2i that do not use * the iscsi if to send a ping, we can add a transport * callout here. */ status = 0; rc = ipc->exec_ping(t->handle, host_no, (struct sockaddr *)&addr, iface->iface_num, iface_type, size, &status); if (!rc && !status) printf("Ping %d completed\n", i); else if (status) printf("Ping %d failed: %s\n", i, iscsi_ping_stat_to_str(status)); else printf("Ping %d failed: %s\n", i, iscsi_err_to_str(rc)); if (i < count) sleep(interval); } ping_exit: return rc; } int main(int argc, char **argv) { char *ip = NULL, *name = NULL, *value = NULL; char *targetname = NULL, *group_session_mgmt_mode = NULL; int ch, longindex, mode=-1, port=-1, do_login=0, do_rescan=0; int rc=0, sid=-1, op=OP_NOOP, type=-1, do_logout=0, do_stats=0; int do_login_all=0, do_logout_all=0, info_level=-1, num_ifaces = 0; int tpgt = PORTAL_GROUP_TAG_UNKNOWN, killiscsid=-1, do_show=0; int packet_size=32, ping_count=1, ping_interval=0; int do_discover = 0, sub_mode = -1; struct sigaction sa_old; struct sigaction sa_new; struct list_head ifaces; struct iface_rec *iface = NULL, *tmp; struct node_rec *rec = NULL; uint32_t host_no = -1; struct user_param *param; struct list_head params; INIT_LIST_HEAD(¶ms); INIT_LIST_HEAD(&ifaces); /* do not allow ctrl-c for now... */ memset(&sa_old, 0, sizeof(struct sigaction)); memset(&sa_new, 0, sizeof(struct sigaction)); sa_new.sa_handler = catch_sigint; sigemptyset(&sa_new.sa_mask); sa_new.sa_flags = 0; sigaction(SIGINT, &sa_new, &sa_old ); umask(0177); /* enable stdout logging */ log_init(program_name, 1024, log_do_log_std, NULL); sysfs_init(); optopt = 0; while ((ch = getopt_long(argc, argv, short_options, long_options, &longindex)) >= 0) { switch (ch) { case 'k': killiscsid = atoi(optarg); if (killiscsid < 0) { log_error("Invalid killiscsid priority %d " "Priority must be greater than or " "equal to zero.", killiscsid); rc = ISCSI_ERR_INVAL; goto free_ifaces; } break; case 't': type = str_to_type(optarg); break; case 'o': op |= str_to_op(optarg); if (op == OP_NOOP) { log_error("can not recognize operation: '%s'", optarg); rc = ISCSI_ERR_INVAL; goto free_ifaces; } break; case 'n': name = optarg; break; case 'v': value = optarg; break; case 'H': host_no = parse_host_info(optarg, &rc); if (rc) goto free_ifaces; break; case 'r': sid = iscsi_sysfs_get_sid_from_path(optarg); if (sid < 0) { log_error("invalid sid '%s'", optarg); rc = ISCSI_ERR_INVAL; goto free_ifaces; } break; case 'R': do_rescan = 1; break; case 'P': info_level = atoi(optarg); break; case 'D': do_discover = 1; break; case 'l': do_login = 1; break; case 'u': do_logout = 1; break; case 'U': do_logout_all = 1; group_session_mgmt_mode= optarg; break; case 'L': do_login_all= 1; group_session_mgmt_mode= optarg; break; case 's': do_stats = 1; break; case 'S': do_show = 1; break; case 'd': log_level = atoi(optarg); break; case 'm': mode = str_to_mode(optarg); break; case 'C': sub_mode = str_to_submode(optarg); break; case 'T': targetname = optarg; break; case 'p': ip = str_to_ipport(optarg, &port, &tpgt); break; case 'a': ip = optarg; break; case 'b': packet_size = atoi(optarg); break; case 'c': ping_count = atoi(optarg); break; case 'i': ping_interval = atoi(optarg); break; case 'I': iface = iface_alloc(optarg, &rc); if (rc == ISCSI_ERR_INVAL) { printf("Invalid iface name %s. Must be from " "1 to %d characters.\n", optarg, ISCSI_MAX_IFACE_LEN - 1); goto free_ifaces; } else if (!iface || rc) { printf("Could not add iface %s.", optarg); rc = ISCSI_ERR_INVAL; goto free_ifaces; } list_add_tail(&iface->list, &ifaces); num_ifaces++; break; case 'V': printf("%s version %s\n", program_name, ISCSI_VERSION_STR); return 0; case 'h': usage(0); } if (name && value) { param = idbm_alloc_user_param(name, value); if (!param) { log_error("Cannot allocate memory for params."); rc = ISCSI_ERR_NOMEM; goto free_ifaces; } list_add_tail(¶m->list, ¶ms); name = NULL; value = NULL; } } if (optopt) { log_error("unrecognized character '%c'", optopt); rc = ISCSI_ERR_INVAL; goto free_ifaces; } if (killiscsid >= 0) { kill_iscsid(killiscsid); goto free_ifaces; } if (mode < 0) usage(ISCSI_ERR_INVAL); if (mode == MODE_FW) { if ((rc = verify_mode_params(argc, argv, "ml", 0))) { log_error("fw mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto free_ifaces; } rc = exec_fw_op(NULL, NULL, info_level, do_login, op); goto free_ifaces; } increase_max_files(); if (idbm_init(get_config_file)) { log_warning("exiting due to idbm configuration error"); rc = ISCSI_ERR_IDBM; goto free_ifaces; } switch (mode) { case MODE_HOST: if ((rc = verify_mode_params(argc, argv, "CHdmPov", 0))) { log_error("host mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto out; } if (sub_mode != -1) { switch (sub_mode) { case MODE_CHAP: if (!op || !host_no) { log_error("CHAP mode requires host " "no and valid operation"); rc = ISCSI_ERR_INVAL; break; } rc = exec_host_chap_op(op, info_level, host_no, value); break; default: log_error("Invalid Sub Mode"); break; } } else rc = host_info_print(info_level, host_no); break; case MODE_IFACE: iface_setup_host_bindings(); if ((rc = verify_mode_params(argc, argv, "HIdnvmPoCabci", 0))) { log_error("iface mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto out; } if (!list_empty(&ifaces)) { iface = list_entry(ifaces.next, struct iface_rec, list); if (num_ifaces > 1) log_error("iface mode only accepts one " "interface. Using the first one " "%s.", iface->name); } if (sub_mode == MODE_PING) rc = exec_ping_op(iface, ip, packet_size, ping_count, ping_interval); else rc = exec_iface_op(op, do_show, info_level, iface, host_no, ¶ms); break; case MODE_DISCOVERYDB: if ((rc = verify_mode_params(argc, argv, "DSIPdmntplov", 0))) { log_error("discovery mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto out; } rc = exec_disc2_op(type, ip, port, &ifaces, info_level, do_login, do_discover, op, ¶ms, do_show); break; case MODE_DISCOVERY: if ((rc = verify_mode_params(argc, argv, "DSIPdmntplov", 0))) { log_error("discovery mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto out; } rc = exec_disc_op(type, ip, port, &ifaces, info_level, do_login, do_discover, op, ¶ms, do_show); break; case MODE_NODE: if ((rc = verify_mode_params(argc, argv, "RsPIdmlSonvupTUL", 0))) { log_error("node mode: option '-%c' is not " "allowed/supported", rc); rc = ISCSI_ERR_INVAL; goto out; } if (do_login_all) { rc = login_by_startup(group_session_mgmt_mode); goto out; } if (do_logout_all) { rc = logout_by_startup(group_session_mgmt_mode); goto out; } if (!list_empty(&ifaces)) { iface = list_entry(ifaces.next, struct iface_rec, list); if (num_ifaces > 1) log_error("NODE mode only accepts one " "interface. Using the first one " "driver %s hwaddress %s ipaddress " "%s.", iface->transport_name, iface->hwaddress, iface->ipaddress); } if (ip && port == -1) port = ISCSI_LISTEN_PORT; rec = idbm_create_rec(targetname, tpgt, ip, port, iface, 1); if (!rec) { rc = ISCSI_ERR_NOMEM; goto out; } rc = exec_node_op(op, do_login, do_logout, do_show, do_rescan, do_stats, info_level, rec, ¶ms); break; case MODE_SESSION: if ((rc = verify_mode_params(argc, argv, "PiRdrmusonuSv", 1))) { log_error("session mode: option '-%c' is not " "allowed or supported", rc); rc = ISCSI_ERR_INVAL; goto out; } if (sid >= 0) { char session[64]; struct session_info *info; snprintf(session, 63, "session%d", sid); session[63] = '\0'; info = calloc(1, sizeof(*info)); if (!info) { rc = ISCSI_ERR_NOMEM; goto out; } rc = iscsi_sysfs_get_sessioninfo_by_id(info, session); if (rc) { log_error("Could not get session info for sid " "%d", sid); goto free_info; } /* * We should be able to go on, but for now * we only support session mode ops if the module * is loaded and we support that module. */ if (!iscsi_sysfs_get_transport_by_sid(sid)) goto free_info; if (!do_logout && !do_rescan && !do_stats && op == OP_NOOP && info_level > 0) { rc = session_info_print(info_level, info, do_show); goto free_info; } rec = idbm_create_rec(info->targetname, info->tpgt, info->persistent_address, info->persistent_port, &info->iface, 1); if (!rec) { rc = ISCSI_ERR_NOMEM; goto free_info; } rec->session.info = info; rec->session.sid = sid; /* * A "new" session means to login a multiple of the * currently-detected session. */ if (op == OP_NEW) { op = OP_NOOP; do_login = 1; rec->session.multiple = 1; } /* drop down to node ops */ rc = exec_node_op(op, do_login, do_logout, do_show, do_rescan, do_stats, info_level, rec, ¶ms); free_info: free(info); goto out; } else { if (op == OP_NEW) { log_error("session mode: Operation 'new' only " "allowed with specific session IDs"); rc = ISCSI_ERR_INVAL; goto out; } if (do_logout || do_rescan || do_stats) { rc = exec_node_op(op, do_login, do_logout, do_show, do_rescan, do_stats, info_level, NULL, ¶ms); goto out; } rc = session_info_print(info_level, NULL, do_show); } break; default: log_error("This mode is not yet supported"); /* fall through */ } out: if (rec) free(rec); idbm_terminate(); free_ifaces: list_for_each_entry_safe(iface, tmp, &ifaces, list) { list_del(&iface->list); free(iface); } free_transports(); sysfs_cleanup(); return rc; } open-iscsi-2.0.873/usr/iscsid.c000066400000000000000000000351471175631155400162210ustar00rootroot00000000000000/* * iSCSI Initiator Daemon * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "iscsid.h" #include "mgmt_ipc.h" #include "event_poll.h" #include "iscsi_ipc.h" #include "log.h" #include "iscsi_util.h" #include "initiator.h" #include "transport.h" #include "idbm.h" #include "version.h" #include "iscsi_sysfs.h" #include "iface.h" #include "session_info.h" #include "sysdeps.h" #include "discoveryd.h" #include "iscsid_req.h" #include "iscsi_err.h" /* global config info */ struct iscsi_daemon_config daemon_config; struct iscsi_daemon_config *dconfig = &daemon_config; static char program_name[] = "iscsid"; static pid_t log_pid; static gid_t gid; static int daemonize = 1; static int mgmt_ipc_fd; static struct option const long_options[] = { {"config", required_argument, NULL, 'c'}, {"initiatorname", required_argument, NULL, 'i'}, {"foreground", no_argument, NULL, 'f'}, {"debug", required_argument, NULL, 'd'}, {"uid", required_argument, NULL, 'u'}, {"gid", required_argument, NULL, 'g'}, {"no-pid-file", no_argument, NULL, 'n'}, {"pid", required_argument, NULL, 'p'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0}, }; static void usage(int status) { if (status != 0) fprintf(stderr, "Try `%s --help' for more information.\n", program_name); else { printf("Usage: %s [OPTION]\n", program_name); printf("\ Open-iSCSI initiator daemon.\n\ -c, --config=[path] Execute in the config file (" CONFIG_FILE ").\n\ -i, --initiatorname=[path] read initiatorname from file (" INITIATOR_NAME_FILE ").\n\ -f, --foreground make the program run in the foreground\n\ -d, --debug debuglevel print debugging information\n\ -u, --uid=uid run as uid, default is current user\n\ -g, --gid=gid run as gid, default is current user group\n\ -n, --no-pid-file do not use a pid file\n\ -p, --pid=pidfile use pid file (default " PID_FILE ").\n\ -h, --help display this help and exit\n\ -v, --version display version and exit\n\ "); } exit(status); } static void setup_rec_from_negotiated_values(node_rec_t *rec, struct session_info *info) { struct iscsi_session_operational_config session_conf; struct iscsi_conn_operational_config conn_conf; struct iscsi_auth_config auth_conf; idbm_node_setup_from_conf(rec); strlcpy(rec->name, info->targetname, TARGET_NAME_MAXLEN); rec->conn[0].port = info->persistent_port; strlcpy(rec->conn[0].address, info->persistent_address, NI_MAXHOST); memcpy(&rec->iface, &info->iface, sizeof(struct iface_rec)); rec->tpgt = info->tpgt; iface_copy(&rec->iface, &info->iface); iscsi_sysfs_get_negotiated_session_conf(info->sid, &session_conf); iscsi_sysfs_get_negotiated_conn_conf(info->sid, &conn_conf); iscsi_sysfs_get_auth_conf(info->sid, &auth_conf); if (strlen(auth_conf.username)) strcpy(rec->session.auth.username, auth_conf.username); if (strlen(auth_conf.username_in)) strcpy(rec->session.auth.username_in, auth_conf.username_in); if (strlen((char *)auth_conf.password)) { strcpy((char *)rec->session.auth.password, (char *)auth_conf.password); rec->session.auth.password_length = auth_conf.password_length; } if (strlen((char *)auth_conf.password_in)) { strcpy((char *)rec->session.auth.password_in, (char *)auth_conf.password_in); rec->session.auth.password_in_length = auth_conf.password_in_length; } if (is_valid_operational_value(conn_conf.HeaderDigest)) { if (conn_conf.HeaderDigest) rec->conn[0].iscsi.HeaderDigest = CONFIG_DIGEST_PREFER_ON; else rec->conn[0].iscsi.HeaderDigest = CONFIG_DIGEST_PREFER_OFF; } if (is_valid_operational_value(conn_conf.DataDigest)) { if (conn_conf.DataDigest) rec->conn[0].iscsi.DataDigest = CONFIG_DIGEST_PREFER_ON; else rec->conn[0].iscsi.DataDigest = CONFIG_DIGEST_PREFER_OFF; } if (is_valid_operational_value(conn_conf.MaxRecvDataSegmentLength)) rec->conn[0].iscsi.MaxRecvDataSegmentLength = conn_conf.MaxRecvDataSegmentLength; if (is_valid_operational_value(conn_conf.MaxXmitDataSegmentLength)) rec->conn[0].iscsi.MaxXmitDataSegmentLength = conn_conf.MaxXmitDataSegmentLength; if (is_valid_operational_value(session_conf.FirstBurstLength)) rec->session.iscsi.FirstBurstLength = session_conf.FirstBurstLength; if (is_valid_operational_value(session_conf.MaxBurstLength)) rec->session.iscsi.MaxBurstLength = session_conf.MaxBurstLength; if (is_valid_operational_value(session_conf.ImmediateData)) { if (session_conf.ImmediateData) rec->session.iscsi.ImmediateData = 1; else rec->session.iscsi.ImmediateData = 0; } if (is_valid_operational_value(session_conf.InitialR2T)) { if (session_conf.InitialR2T) rec->session.iscsi.InitialR2T = 0; else rec->session.iscsi.InitialR2T = 1; } } static int sync_session(void *data, struct session_info *info) { node_rec_t rec, sysfsrec; iscsiadm_req_t req; iscsiadm_rsp_t rsp; struct iscsi_transport *t; int rc, retries = 0; log_debug(7, "sync session [%d][%s,%s.%d][%s]\n", info->sid, info->targetname, info->persistent_address, info->port, info->iface.hwaddress); t = iscsi_sysfs_get_transport_by_sid(info->sid); if (!t) return 0; /* * Just rescan the device in case this is the first startup. * (TODO: should do this async and check for state). */ if (t->caps & CAP_FW_DB) { uint32_t host_no; int err; host_no = iscsi_sysfs_get_host_no_from_sid(info->sid, &err); if (err) { log_error("Could not get host no from sid %u. Can not " "sync session: %s", info->sid, iscsi_err_to_str(err)); return 0; } iscsi_sysfs_scan_host(host_no, 0); return 0; } if (!iscsi_sysfs_session_user_created(info->sid)) return 0; memset(&rec, 0, sizeof(node_rec_t)); /* * We might get the local ip address for software. We do not * want to try and bind a session by ip though. */ if (!t->template->set_host_ip) memset(info->iface.ipaddress, 0, sizeof(info->iface.ipaddress)); if (idbm_rec_read(&rec, info->targetname, info->tpgt, info->persistent_address, info->persistent_port, &info->iface)) { log_warning("Could not read data from db. Using default and " "currently negotiated values\n"); setup_rec_from_negotiated_values(&rec, info); } else { /* * we have a valid record and iface so lets merge * the values from them and sysfs to try and get * the most uptodate values. * * Currenlty that means we will use the CHAP, target, portal * and iface values from sysfs and use timer, queue depth, * and segment length values from the record. */ memset(&sysfsrec, 0, sizeof(node_rec_t)); setup_rec_from_negotiated_values(&sysfsrec, info); /* * target, portal and iface name values have to be the same * or we would not have found the record, so just copy * CHAP and iface settings. */ memcpy(&rec.session.auth, &sysfsrec.session.auth, sizeof(struct iscsi_auth_config)); memcpy(&rec.iface, &info->iface, sizeof(rec.iface)); } /* multiple drivers could be connected to the same portal */ if (!iscsi_match_session(&rec, info)) return -1; /* * We use the initiator name from sysfs because * the session could have come from our db or ibft or some other * app. */ strcpy(rec.iface.iname, info->iface.iname); memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_SESSION_SYNC; req.u.session.sid = info->sid; memcpy(&req.u.session.rec, &rec, sizeof(node_rec_t)); retry: rc = iscsid_exec_req(&req, &rsp, 0); if (rc == ISCSI_ERR_ISCSID_NOTCONN && retries < 30) { retries++; sleep(1); goto retry; } return 0; } static char *iscsid_get_config_file(void) { return daemon_config.config_file; } static void iscsid_shutdown(void) { pid_t pid; killpg(gid, SIGTERM); while ((pid = waitpid(0, NULL, 0) > 0)) log_debug(7, "cleaned up pid %d", pid); log_warning("iscsid shutting down."); if (daemonize && log_pid >= 0) { log_debug(1, "daemon stopping"); log_close(log_pid); } } static void catch_signal(int signo) { log_debug(1, "pid %d caught signal %d", getpid(), signo); /* In foreground mode, treat SIGINT like SIGTERM */ if (!daemonize && signo == SIGINT) signo = SIGTERM; switch (signo) { case SIGTERM: iscsid_shutdown(); exit(0); break; default: break; } } static void missing_iname_warn(char *initiatorname_file) { log_error("Warning: InitiatorName file %s does not exist or does not " "contain a properly formated InitiatorName. If using " "software iscsi (iscsi_tcp or ib_iser) or partial offload " "(bnx2i or cxgbi iscsi), you may not be able to log " "into or discover targets. Please create a file %s that " "contains a sting with the format: InitiatorName=" "iqn.yyyy-mm.[:identifier].\n\n" "Example: InitiatorName=iqn.2001-04.com.redhat:fc6.\n" "If using hardware iscsi like qla4xxx this message can be " "ignored.\n", initiatorname_file, initiatorname_file); } int main(int argc, char *argv[]) { struct utsname host_info; /* will use to compound initiator alias */ char *config_file = CONFIG_FILE; char *initiatorname_file = INITIATOR_NAME_FILE; char *pid_file = PID_FILE; int ch, longindex; uid_t uid = 0; struct sigaction sa_old; struct sigaction sa_new; int control_fd; pid_t pid; while ((ch = getopt_long(argc, argv, "c:i:fd:nu:g:p:vh", long_options, &longindex)) >= 0) { switch (ch) { case 'c': config_file = optarg; break; case 'i': initiatorname_file = optarg; break; case 'f': daemonize = 0; break; case 'd': log_level = atoi(optarg); break; case 'u': uid = strtoul(optarg, NULL, 10); break; case 'g': gid = strtoul(optarg, NULL, 10); break; case 'n': pid_file = NULL; break; case 'p': pid_file = optarg; break; case 'v': printf("%s version %s\n", program_name, ISCSI_VERSION_STR); exit(0); case 'h': usage(0); break; default: usage(1); break; } } /* initialize logger */ log_pid = log_init(program_name, DEFAULT_AREA_SIZE, daemonize ? log_do_log_daemon : log_do_log_std, NULL); if (log_pid < 0) exit(ISCSI_ERR); /* do not allow ctrl-c for now... */ sa_new.sa_handler = catch_signal; sigemptyset(&sa_new.sa_mask); sa_new.sa_flags = 0; sigaction(SIGINT, &sa_new, &sa_old ); sigaction(SIGPIPE, &sa_new, &sa_old ); sigaction(SIGTERM, &sa_new, &sa_old ); sysfs_init(); if (idbm_init(iscsid_get_config_file)) { log_close(log_pid); exit(ISCSI_ERR); } umask(0177); mgmt_ipc_fd = -1; control_fd = -1; daemon_config.initiator_name = NULL; daemon_config.initiator_alias = NULL; if ((mgmt_ipc_fd = mgmt_ipc_listen()) < 0) { log_close(log_pid); exit(ISCSI_ERR); } if (daemonize) { char buf[64]; int fd = -1; if (pid_file) { fd = open(pid_file, O_WRONLY|O_CREAT, 0644); if (fd < 0) { log_error("Unable to create pid file"); log_close(log_pid); exit(ISCSI_ERR); } } pid = fork(); if (pid < 0) { log_error("Starting daemon failed"); log_close(log_pid); exit(ISCSI_ERR); } else if (pid) { log_error("iSCSI daemon with pid=%d started!", pid); exit(0); } if ((control_fd = ipc->ctldev_open()) < 0) { log_close(log_pid); exit(ISCSI_ERR); } if (chdir("/") < 0) log_debug(1, "Unable to chdir to /"); if (fd > 0) { if (lockf(fd, F_TLOCK, 0) < 0) { log_error("Unable to lock pid file"); log_close(log_pid); exit(ISCSI_ERR); } if (ftruncate(fd, 0) < 0) { log_error("Unable to truncate pid file"); log_close(log_pid); exit(ISCSI_ERR); } sprintf(buf, "%d\n", getpid()); if (write(fd, buf, strlen(buf)) < 0) { log_error("Unable to write pid file"); log_close(log_pid); exit(ISCSI_ERR); } } daemon_init(); } else { if ((control_fd = ipc->ctldev_open()) < 0) { log_close(log_pid); exit(1); } } if (uid && setuid(uid) < 0) perror("setuid\n"); if (gid && setgid(gid) < 0) perror("setgid\n"); memset(&daemon_config, 0, sizeof (daemon_config)); daemon_config.pid_file = pid_file; daemon_config.config_file = config_file; daemon_config.initiator_name = cfg_get_string_param(initiatorname_file, "InitiatorName"); if (daemon_config.initiator_name == NULL) missing_iname_warn(initiatorname_file); /* optional InitiatorAlias */ daemon_config.initiator_alias = cfg_get_string_param(initiatorname_file, "InitiatorAlias"); if (!daemon_config.initiator_alias) { memset(&host_info, 0, sizeof (host_info)); if (uname(&host_info) >= 0) { daemon_config.initiator_alias = strdup(host_info.nodename); } } log_debug(1, "InitiatorName=%s", daemon_config.initiator_name ? daemon_config.initiator_name : "NOT SET"); log_debug(1, "InitiatorAlias=%s", daemon_config.initiator_alias); pid = fork(); if (pid == 0) { int nr_found = 0; /* child */ iscsi_sysfs_for_each_session(NULL, &nr_found, sync_session); exit(0); } else if (pid < 0) { log_error("Fork failed error %d: existing sessions" " will not be synced", errno); } else reap_inc(); iscsi_initiator_init(); increase_max_files(); discoveryd_start(daemon_config.initiator_name); /* oom-killer will not kill us at the night... */ if (oom_adjust()) log_debug(1, "can not adjust oom-killer's pardon"); /* we don't want our active sessions to be paged out... */ if (mlockall(MCL_CURRENT | MCL_FUTURE)) { log_error("failed to mlockall, exiting..."); log_close(log_pid); exit(ISCSI_ERR); } actor_init(); event_loop(ipc, control_fd, mgmt_ipc_fd); idbm_terminate(); sysfs_cleanup(); ipc->ctldev_close(); mgmt_ipc_close(mgmt_ipc_fd); if (daemon_config.initiator_name) free(daemon_config.initiator_name); if (daemon_config.initiator_alias) free(daemon_config.initiator_alias); free_initiator(); iscsid_shutdown(); return 0; } open-iscsi-2.0.873/usr/iscsid.h000066400000000000000000000017561175631155400162250ustar00rootroot00000000000000/* * iSCSI Initiator Daemon * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSID_H #define ISCSID_H /* IPC API */ extern struct iscsi_ipc *ipc; /* iscsid.c: daemon config */ struct iscsi_daemon_config { char *config_file; char *pid_file; char *initiator_name; char *initiator_alias; }; extern struct iscsi_daemon_config *dconfig; #endif /* ISCSID_H */ open-iscsi-2.0.873/usr/iscsid_req.c000066400000000000000000000110671175631155400170630ustar00rootroot00000000000000/* * iscsid communication helpers * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 - 2010 Mike Christie * Copyright (C) 2006 - 2010 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include "initiator.h" #include "log.h" #include "mgmt_ipc.h" #include "iscsi_util.h" #include "config.h" #include "iscsi_err.h" static void iscsid_startup(void) { char *startup_cmd; startup_cmd = cfg_get_string_param(CONFIG_FILE, "iscsid.startup"); if (!startup_cmd) { log_error("iscsid is not running. Could not start it up " "automatically using the startup command in the " "/etc/iscsi/iscsid.conf iscsid.startup setting. " "Please check that the file exists or that your " "init scripts have started iscsid."); return; } if (system(startup_cmd) < 0) log_error("Could not execute '%s' (err %d)", startup_cmd, errno); } #define MAXSLEEP 128 static int iscsid_connect(int *fd, int start_iscsid) { int nsec; struct sockaddr_un addr; *fd = socket(AF_LOCAL, SOCK_STREAM, 0); if (*fd < 0) { log_error("can not create IPC socket (%d)!", errno); return ISCSI_ERR_ISCSID_NOTCONN; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_LOCAL; memcpy((char *) &addr.sun_path + 1, ISCSIADM_NAMESPACE, strlen(ISCSIADM_NAMESPACE)); /* * Trying to connect with exponential backoff */ for (nsec = 1; nsec <= MAXSLEEP; nsec <<= 1) { if (connect(*fd, (struct sockaddr *) &addr, sizeof(addr)) == 0) /* Connection established */ return ISCSI_SUCCESS; /* If iscsid isn't there, there's no sense * in retrying. */ if (errno == ECONNREFUSED) { if (start_iscsid && nsec == 1) iscsid_startup(); else break; } /* * Delay before trying again */ if (nsec <= MAXSLEEP/2) sleep(nsec); } log_error("can not connect to iSCSI daemon (%d)!", errno); return ISCSI_ERR_ISCSID_NOTCONN; } int iscsid_request(int *fd, iscsiadm_req_t *req, int start_iscsid) { int err; err = iscsid_connect(fd, start_iscsid); if (err) return err; if ((err = write(*fd, req, sizeof(*req))) != sizeof(*req)) { log_error("got write error (%d/%d) on cmd %d, daemon died?", err, errno, req->command); close(*fd); return ISCSI_ERR_ISCSID_COMM_ERR; } return ISCSI_SUCCESS; } int iscsid_response(int fd, iscsiadm_cmd_e cmd, iscsiadm_rsp_t *rsp) { int iscsi_err; int err; if ((err = recv(fd, rsp, sizeof(*rsp), MSG_WAITALL)) != sizeof(*rsp)) { log_error("got read error (%d/%d), daemon died?", err, errno); iscsi_err = ISCSI_ERR_ISCSID_COMM_ERR; } else iscsi_err = rsp->err; close(fd); if (!iscsi_err && cmd != rsp->command) iscsi_err = ISCSI_ERR_ISCSID_COMM_ERR; return iscsi_err; } int iscsid_exec_req(iscsiadm_req_t *req, iscsiadm_rsp_t *rsp, int start_iscsid) { int fd; int err; err = iscsid_request(&fd, req, start_iscsid); if (err) return err; return iscsid_response(fd, req->command, rsp); } int iscsid_req_wait(iscsiadm_cmd_e cmd, int fd) { iscsiadm_rsp_t rsp; memset(&rsp, 0, sizeof(iscsiadm_rsp_t)); return iscsid_response(fd, cmd, &rsp); } int iscsid_req_by_rec_async(iscsiadm_cmd_e cmd, node_rec_t *rec, int *fd) { iscsiadm_req_t req; memset(&req, 0, sizeof(iscsiadm_req_t)); req.command = cmd; memcpy(&req.u.session.rec, rec, sizeof(node_rec_t)); return iscsid_request(fd, &req, 1); } int iscsid_req_by_rec(iscsiadm_cmd_e cmd, node_rec_t *rec) { int err, fd; err = iscsid_req_by_rec_async(cmd, rec, &fd); if (err) return err; return iscsid_req_wait(cmd, fd); } int iscsid_req_by_sid_async(iscsiadm_cmd_e cmd, int sid, int *fd) { iscsiadm_req_t req; memset(&req, 0, sizeof(iscsiadm_req_t)); req.command = cmd; req.u.session.sid = sid; return iscsid_request(fd, &req, 1); } int iscsid_req_by_sid(iscsiadm_cmd_e cmd, int sid) { int err, fd; err = iscsid_req_by_sid_async(cmd, sid, &fd); if (err) return err; return iscsid_req_wait(cmd, fd); } open-iscsi-2.0.873/usr/iscsid_req.h000066400000000000000000000023661175631155400170720ustar00rootroot00000000000000/* * iscsid communication helpers * * Copyright (C) 2010 Mike Christie * Copyright (C) 2010 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef ISCSID_REQ_H_ #define ISCSID_REQ_H struct iscsiadm_req; struct iscsiadm_rsp; struct node_rec; extern int iscsid_exec_req(struct iscsiadm_req *req, struct iscsiadm_rsp *rsp, int iscsid_start); extern int iscsid_req_wait(int cmd, int fd); extern int iscsid_req_by_rec_async(int cmd, struct node_rec *rec, int *fd); extern int iscsid_req_by_rec(int cmd, struct node_rec *rec); extern int iscsid_req_by_sid_async(int cmd, int sid, int *fd); extern int iscsid_req_by_sid(int cmd, int sid); #endif open-iscsi-2.0.873/usr/iscsistart.c000066400000000000000000000332371175631155400171310ustar00rootroot00000000000000/* * iSCSI Root Boot Program based on daemon code * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "initiator.h" #include "iscsi_ipc.h" #include "event_poll.h" #include "transport.h" #include "log.h" #include "iscsi_util.h" #include "idbm.h" #include "idbm_fields.h" #include "version.h" #include "iscsi_sysfs.h" #include "iscsi_settings.h" #include "fw_context.h" #include "iface.h" #include "sysdeps.h" #include "iscsid_req.h" #include "iscsi_err.h" #include "iface.h" /* global config info */ /* initiator needs initiator name/alias */ struct iscsi_daemon_config daemon_config; struct iscsi_daemon_config *dconfig = &daemon_config; static node_rec_t config_rec; static LIST_HEAD(targets); static LIST_HEAD(user_params); static char program_name[] = "iscsistart"; /* used by initiator */ extern struct iscsi_ipc *ipc; static struct option const long_options[] = { {"initiatorname", required_argument, NULL, 'i'}, {"targetname", required_argument, NULL, 't'}, {"tgpt", required_argument, NULL, 'g'}, {"address", required_argument, NULL, 'a'}, {"port", required_argument, NULL, 'p'}, {"username", required_argument, NULL, 'u'}, {"password", required_argument, NULL, 'w'}, {"username_in", required_argument, NULL, 'U'}, {"password_in", required_argument, NULL, 'W'}, {"debug", required_argument, NULL, 'd'}, {"fwparam_connect", no_argument, NULL, 'b'}, {"fwparam_network", no_argument, NULL, 'N'}, {"fwparam_print", no_argument, NULL, 'f'}, {"param", required_argument, NULL, 'P'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0}, }; static void usage(int status) { if (status != 0) fprintf(stderr, "Try `%s --help' for more information.\n", program_name); else { printf("Usage: %s [OPTION]\n", program_name); printf("\ Open-iSCSI initiator.\n\ -i, --initiatorname=name set InitiatorName to name (Required)\n\ -t, --targetname=name set TargetName to name (Required)\n\ -g, --tgpt=N set target portal group tag to N (Required)\n\ -a, --address=A.B.C.D set IP addres to A.B.C.D (Required)\n\ -p, --port=N set port to N (Default 3260)\n\ -u, --username=N set username to N (optional)\n\ -w, --password=N set password to N (optional\n\ -U, --username_in=N set incoming username to N (optional)\n\ -W, --password_in=N set incoming password to N (optional)\n\ -d, --debug=debuglevel print debugging information \n\ -b, --fwparam_connect create a session to the target using iBFT or OF\n\ -N, --fwparam_network bring up the network as specified by iBFT or OF\n\ -f, --fwparam_print print the iBFT or OF info to STDOUT \n\ -P, --param=NAME=VALUE set parameter with the name NAME to VALUE\n\ -h, --help display this help and exit\n\ -v, --version display version and exit\n\ "); } exit(status); } static int stop_event_loop(void) { iscsiadm_req_t req; iscsiadm_rsp_t rsp; int rc; memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_IMMEDIATE_STOP; rc = iscsid_exec_req(&req, &rsp, 0); if (rc) { iscsi_err_print_msg(rc); log_error("Could not stop event_loop\n"); } return rc; } static int apply_params(struct node_rec *rec) { struct user_param *param; int rc; /* Must init this so we can check if user overrode them */ rec->session.initial_login_retry_max = -1; rec->conn[0].timeo.noop_out_interval = -1; rec->conn[0].timeo.noop_out_timeout = -1; list_for_each_entry(param, &user_params, list) { /* * user may not have passed in all params that were set by * ibft/iscsi_boot, so clear out values that might conflict * with user overrides */ if (!strcmp(param->name, IFACE_NETNAME)) { /* overriding netname so MAC will be for old netdev */ memset(rec->iface.hwaddress, 0, sizeof(rec->iface.hwaddress)); } else if (!strcmp(param->name, IFACE_HWADDR)) { /* overriding MAC so netdev will be for old MAC */ memset(rec->iface.netdev, 0, sizeof(rec->iface.netdev)); } else if (!strcmp(param->name, IFACE_TRANSPORTNAME)) { /* * switching drivers so all old binding info is no * longer valid. Old values were either for offload * and we are switching to software or the reverse, * or switching types of cards (bnx2i to cxgb3i). */ memset(&rec->iface, 0, sizeof(rec->iface)); iface_setup_defaults(&rec->iface); } } rc = idbm_node_set_rec_from_param(&user_params, rec, 0); if (rc) return rc; /* * For root boot we could not change this in older versions so * if user did not override then use the defaults. * * Increase to account for boot using static setup. */ if (rec->session.initial_login_retry_max == -1) rec->session.initial_login_retry_max = 30; /* we used to not be able to answer so turn off */ if (rec->conn[0].timeo.noop_out_interval == -1) rec->conn[0].timeo.noop_out_interval = 0; if (rec->conn[0].timeo.noop_out_timeout == -1) rec->conn[0].timeo.noop_out_timeout = 0; return 0; } static int parse_param(char *param_str) { struct user_param *param; char *name, *value; name = param_str; value = strchr(param_str, '='); if (!value) { log_error("Invalid --param %s. Missing value.", param_str); return ISCSI_ERR_INVAL; } *value = '\0'; value++; if (!strlen(value)) { log_error("Invalid --param %s. Missing value.", param_str); return ISCSI_ERR_INVAL; } param = idbm_alloc_user_param(name, value); if (!param) { log_error("Could not allocate memory for param."); return ISCSI_ERR_NOMEM; } list_add(¶m->list, &user_params); return 0; } static int login_session(struct node_rec *rec) { iscsiadm_req_t req; iscsiadm_rsp_t rsp; int rc, retries = 0; rc = apply_params(rec); if (rc) return rc; printf("%s: Logging into %s %s:%d,%d\n", program_name, rec->name, rec->conn[0].address, rec->conn[0].port, rec->tpgt); memset(&req, 0, sizeof(req)); req.command = MGMT_IPC_SESSION_LOGIN; memcpy(&req.u.session.rec, rec, sizeof(*rec)); retry: rc = iscsid_exec_req(&req, &rsp, 0); /* * handle race where iscsid proc is starting up while we are * trying to connect. */ if (rc == ISCSI_ERR_ISCSID_NOTCONN && retries < 30) { retries++; sleep(1); goto retry; } else if (rc) iscsi_err_print_msg(rc); return rc; } static int setup_session(void) { struct boot_context *context; int rc = 0, rc2 = 0; if (list_empty(&targets)) return login_session(&config_rec); list_for_each_entry(context, &targets, list) { struct node_rec *rec; rec = idbm_create_rec_from_boot_context(context); if (!rec) { log_error("Could not allocate memory. Could " "not start boot session to " "%s,%s,%d", context->targetname, context->target_ipaddr, context->target_port); continue; } rc2 = login_session(rec); if (rc2) rc = rc2; free(rec); } fw_free_targets(&targets); return rc; } static void catch_signal(int signo) { log_warning("pid %d caught signal -%d", getpid(), signo); } static int check_params(char *initiatorname) { if (!initiatorname) { log_error("InitiatorName not set. Exiting %s\n", program_name); return EINVAL; } if (config_rec.tpgt == PORTAL_GROUP_TAG_UNKNOWN) { log_error("Portal Group not set. Exiting %s\n", program_name); return EINVAL; } if (!strlen(config_rec.name)) { log_error("TargetName not set. Exiting %s\n", program_name); return EINVAL; } if (!strlen(config_rec.conn[0].address)) { log_error("IP Address not set. Exiting %s\n", program_name); return EINVAL; } return 0; } #define check_str_param_len(str, max_len, param) \ do { \ if (strlen(str) > max_len) { \ printf("%s: invalid %s %s. Max %s length is %d.\n", \ program_name, param, str, param, max_len); \ exit(ISCSI_ERR_INVAL); \ } \ } while (0); int main(int argc, char *argv[]) { struct utsname host_info; /* will use to compound initiator alias */ struct iscsi_auth_config *auth; char *initiatorname = NULL; int ch, longindex, ret; struct boot_context *context, boot_context; struct sigaction sa_old; struct sigaction sa_new; int control_fd, mgmt_ipc_fd, err; pid_t pid; idbm_node_setup_defaults(&config_rec); config_rec.name[0] = '\0'; config_rec.conn[0].address[0] = '\0'; auth = &config_rec.session.auth; /* do not allow ctrl-c for now... */ sa_new.sa_handler = catch_signal; sigemptyset(&sa_new.sa_mask); sa_new.sa_flags = 0; sigaction(SIGINT, &sa_new, &sa_old ); /* initialize logger */ log_init(program_name, DEFAULT_AREA_SIZE, log_do_log_std, NULL); sysfs_init(); while ((ch = getopt_long(argc, argv, "P:i:t:g:a:p:d:u:w:U:W:bNfvh", long_options, &longindex)) >= 0) { switch (ch) { case 'i': initiatorname = optarg; break; case 't': check_str_param_len(optarg, TARGET_NAME_MAXLEN, "targetname"); strlcpy(config_rec.name, optarg, TARGET_NAME_MAXLEN); break; case 'g': config_rec.tpgt = atoi(optarg); break; case 'a': check_str_param_len(optarg, NI_MAXHOST, "address"); strlcpy(config_rec.conn[0].address, optarg, NI_MAXHOST); break; case 'p': config_rec.conn[0].port = atoi(optarg); break; case 'w': check_str_param_len(optarg, AUTH_STR_MAX_LEN, "password"); strlcpy((char *)auth->password, optarg, AUTH_STR_MAX_LEN); auth->password_length = strlen((char *)auth->password); break; case 'W': check_str_param_len(optarg, AUTH_STR_MAX_LEN, "password_in"); strlcpy((char *)auth->password_in, optarg, AUTH_STR_MAX_LEN); auth->password_in_length = strlen((char *)auth->password_in); break; case 'u': check_str_param_len(optarg, AUTH_STR_MAX_LEN, "username"); strlcpy(auth->username, optarg, AUTH_STR_MAX_LEN); break; case 'U': check_str_param_len(optarg, AUTH_STR_MAX_LEN, "username_in"); strlcpy(auth->username_in, optarg, AUTH_STR_MAX_LEN); break; case 'd': log_level = atoi(optarg); break; case 'b': memset(&boot_context, 0, sizeof(boot_context)); ret = fw_get_entry(&boot_context); if (ret) { printf("Could not get boot entry.\n"); exit(ret); } initiatorname = boot_context.initiatorname; ret = fw_get_targets(&targets); if (ret || list_empty(&targets)) { printf("Could not setup fw entries.\n"); exit(ret); } break; case 'N': exit(fw_setup_nics()); case 'f': ret = fw_get_targets(&targets); if (ret || list_empty(&targets)) { printf("Could not get list of targets from " "firmware.\n"); exit(ret); } list_for_each_entry(context, &targets, list) fw_print_entry(context); fw_free_targets(&targets); exit(0); case 'P': err = parse_param(optarg); if (err) exit(err); break; case 'v': printf("%s version %s\n", program_name, ISCSI_VERSION_STR); exit(0); case 'h': usage(0); break; default: usage(ISCSI_ERR_INVAL); break; } } if (list_empty(&targets) && check_params(initiatorname)) exit(ISCSI_ERR_INVAL); pid = fork(); if (pid < 0) { log_error("iscsiboot fork failed"); exit(ISCSI_ERR_NOMEM); } else if (pid) { int status, rc, rc2; rc = setup_session(); rc2 = stop_event_loop(); /* * something horrible happened. kill child and get * out of here */ if (rc2) kill(pid, SIGTERM); waitpid(pid, &status, WUNTRACED); if (rc || rc2) exit(ISCSI_ERR); log_debug(1, "iscsi parent done"); exit(0); } mgmt_ipc_fd = mgmt_ipc_listen(); if (mgmt_ipc_fd < 0) { log_error("Could not setup mgmt ipc\n"); exit(ISCSI_ERR_NOMEM); } control_fd = ipc->ctldev_open(); if (control_fd < 0) exit(ISCSI_ERR_NOMEM); memset(&daemon_config, 0, sizeof (daemon_config)); daemon_config.initiator_name = initiatorname; /* optional InitiatorAlias */ memset(&host_info, 0, sizeof (host_info)); if (uname(&host_info) >= 0) daemon_config.initiator_alias = host_info.nodename; log_debug(1, "InitiatorName=%s", daemon_config.initiator_name); log_debug(1, "InitiatorAlias=%s", daemon_config.initiator_alias); log_debug(1, "TargetName=%s", config_rec.name); log_debug(1, "TPGT=%d", config_rec.tpgt); log_debug(1, "IP Address=%s", config_rec.conn[0].address); /* log the version, so that we can tell if the daemon and kernel module * match based on what shows up in the syslog. Tarballs releases * always install both, but Linux distributors may put the kernel module * in a different RPM from the daemon and utils, and users may try to * mix and match in ways that don't work. */ log_error("version %s", ISCSI_VERSION_STR); /* oom-killer will not kill us at the night... */ if (oom_adjust()) log_debug(1, "can not adjust oom-killer's pardon"); /* * Start Main Event Loop */ iscsi_initiator_init(); actor_init(); event_loop(ipc, control_fd, mgmt_ipc_fd); ipc->ctldev_close(); mgmt_ipc_close(mgmt_ipc_fd); free_initiator(); sysfs_cleanup(); log_debug(1, "iscsi child done"); return 0; } open-iscsi-2.0.873/usr/iser.c000066400000000000000000000013501175631155400156720ustar00rootroot00000000000000/* * iser helpers * * Copyright (C) 2012 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include "initiator.h" void iser_create_conn(struct iscsi_conn *conn) { /* header digests not supported in iser */ conn->hdrdgst_en = ISCSI_DIGEST_NONE; } open-iscsi-2.0.873/usr/iser.h000066400000000000000000000002021175631155400156720ustar00rootroot00000000000000#ifndef ISER_TRANSPORT #define ISER_TRANSPORT struct iscsi_conn; extern void iser_create_conn(struct iscsi_conn *conn); #endif open-iscsi-2.0.873/usr/kern_err_table.c000066400000000000000000000060171175631155400177130ustar00rootroot00000000000000/* * Copyright (C) 2011 Aastha Mehta * Copyright (C) 2011 Mike Christie * * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include "iscsi_if.h" #include "kern_err_table.h" const char *kern_err_code_to_string(int err) { switch (err){ case ISCSI_OK: return "ISCSI_OK: operation successful"; case ISCSI_ERR_DATASN: return "ISCSI_ERR_DATASN: Received invalid data sequence " "number from target"; case ISCSI_ERR_DATA_OFFSET: return "ISCSI_ERR_DATA_OFFSET: Seeking offset beyond the size " "of the iSCSI segment"; case ISCSI_ERR_MAX_CMDSN: return "ISCSI_ERR_MAX_CMDSN: Received invalid command sequence " "number from target"; case ISCSI_ERR_EXP_CMDSN: return "ISCSI_ERR_EXP_CMDSN: Received invalid expected command " "sequence number from target"; case ISCSI_ERR_BAD_OPCODE: return "ISCSI_ERR_BAD_OPCODE: Received an invalid iSCSI opcode"; case ISCSI_ERR_DATALEN: return "ISCSI_ERR_DATALEN: Invalid data length value"; case ISCSI_ERR_AHSLEN: return "ISCSI_ERR_AHSLEN: Received an invalid AHS length"; case ISCSI_ERR_PROTO: return "ISCSI_ERR_PROTO: iSCSI protocol violation"; case ISCSI_ERR_LUN: return "ISCSI_ERR_LUN: LUN mismatch"; case ISCSI_ERR_BAD_ITT: return "ISCSI_ERR_BAD_ITT: Received invalid initiator task tag " "from target"; case ISCSI_ERR_CONN_FAILED: return "ISCSI_ERR_CONN_FAILED: iSCSI connection failed"; case ISCSI_ERR_R2TSN: return "ISCSI_ERR_R2TSN: Received invalid R2T (Ready to " "Transfer) data sequence number from target"; case ISCSI_ERR_SESSION_FAILED: return "ISCSI_ERR_SESSION_FAILED: iSCSI session failed"; case ISCSI_ERR_HDR_DGST: return "ISCSI_ERR_HDR_DGST: Header digest mismatch"; case ISCSI_ERR_DATA_DGST: return "ISCSI_ERR_DATA_DGST: Data digest mismatch"; case ISCSI_ERR_PARAM_NOT_FOUND: return "ISCSI_ERR_PARAM_NOT_FOUND: Parameter not found"; case ISCSI_ERR_NO_SCSI_CMD: return "ISCSI_ERR_NO_SCSI_CMD: Could not look up SCSI command"; case ISCSI_ERR_INVALID_HOST: return "ISCSI_ERR_INVALID_HOST: iSCSI host is in an invalid " "state"; case ISCSI_ERR_XMIT_FAILED: return "ISCSI_ERR_XMIT_FAILED: Transmission of iSCSI packet " "failed"; case ISCSI_ERR_TCP_CONN_CLOSE: return "ISCSI_ERR_TCP_CONN_CLOSE: TCP connection closed"; case ISCSI_ERR_SCSI_EH_SESSION_RST: return "ISCSI_ERR_SCSI_EH_SESSION_RST: Session was dropped as " "a result of SCSI error recovery"; default: return "Invalid or unknown error code"; } } open-iscsi-2.0.873/usr/kern_err_table.h000066400000000000000000000014651175631155400177220ustar00rootroot00000000000000/* * Copyright (C) 2011 Aastha Mehta * Copyright (C) 2011 Mike Christie * * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef __KERN_ERR_TABLE_H__ #define __KERN_ERR_TABLE_H__ extern const char *kern_err_code_to_string(int); #endif open-iscsi-2.0.873/usr/log.c000066400000000000000000000227341175631155400155220ustar00rootroot00000000000000/* * Copyright (C) 2002-2003 Ardis Technolgies * * Released under the terms of the GNU GPL v2.0. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "iscsi_util.h" #include "log.h" #define SEMKEY 0xA7L #define LOGDBG 0 #if LOGDBG #define logdbg(file, fmt, args...) fprintf(file, fmt, ##args) #else #define logdbg(file, fmt, args...) do {} while (0) #endif char *log_name; int log_level = 0; static int log_stop_daemon = 0; static void (*log_func)(int prio, void *priv, const char *fmt, va_list ap); static void *log_func_priv; static void free_logarea (void) { int shmid; if (!la) return; if (la->semid != -1) semctl(la->semid, 0, IPC_RMID, la->semarg); if (la->buff) { shmdt(la->buff); shmctl(la->shmid_buff, IPC_RMID, NULL); la->buff = NULL; la->shmid_buff = -1; } if (la->start) { shmdt(la->start); shmctl(la->shmid_msg, IPC_RMID, NULL); la->start = NULL; la->shmid_msg = -1; } shmid = la->shmid; shmdt(la); shmctl(shmid, IPC_RMID, NULL); la = NULL; } static int logarea_init (int size) { int shmid; logdbg(stderr,"enter logarea_init\n"); if ((shmid = shmget(IPC_PRIVATE, sizeof(struct logarea), 0644 | IPC_CREAT | IPC_EXCL)) == -1) { syslog(LOG_ERR, "shmget logarea failed %d", errno); return 1; } la = shmat(shmid, NULL, 0); if (!la) { syslog(LOG_ERR, "shmat logarea failed %d", errno); shmctl(shmid, IPC_RMID, NULL); return 1; } la->shmid = shmid; la->start = NULL; la->buff = NULL; la->semid = -1; if (size < MAX_MSG_SIZE) size = DEFAULT_AREA_SIZE; if ((shmid = shmget(IPC_PRIVATE, size, 0644 | IPC_CREAT | IPC_EXCL)) == -1) { syslog(LOG_ERR, "shmget msg failed %d", errno); free_logarea(); return 1; } la->shmid_msg = shmid; la->start = shmat(la->shmid_msg, NULL, 0); if (!la->start) { syslog(LOG_ERR, "shmat msg failed %d", errno); free_logarea(); return 1; } memset(la->start, 0, size); la->empty = 1; la->end = la->start + size; la->head = la->start; la->tail = la->start; if ((shmid = shmget(IPC_PRIVATE, MAX_MSG_SIZE + sizeof(struct logmsg), 0644 | IPC_CREAT | IPC_EXCL)) == -1) { syslog(LOG_ERR, "shmget logmsg failed %d", errno); free_logarea(); return 1; } la->buff = shmat(shmid, NULL, 0); if (!la->buff) { syslog(LOG_ERR, "shmat logmsgfailed %d", errno); free_logarea(); return 1; } if ((la->semid = semget(SEMKEY, 1, 0600 | IPC_CREAT)) < 0) { syslog(LOG_ERR, "semget failed %d", errno); free_logarea(); return 1; } la->semarg.val=1; if (semctl(la->semid, 0, SETVAL, la->semarg) < 0) { syslog(LOG_ERR, "semctl failed %d", errno); free_logarea(); return 1; } la->shmid_buff = shmid; la->ops[0].sem_num = 0; la->ops[0].sem_flg = 0; return 0; } #if LOGDBG static void dump_logarea (void) { struct logmsg * msg; logdbg(stderr, "\n==== area: start addr = %p, end addr = %p ====\n", la->start, la->end); logdbg(stderr, "|addr |next |prio|msg\n"); for (msg = (struct logmsg *)la->head; (void *)msg != la->tail; msg = msg->next) logdbg(stderr, "|%p |%p |%i |%s\n", (void *)msg, msg->next, msg->prio, (char *)&msg->str); logdbg(stderr, "|%p |%p |%i |%s\n", (void *)msg, msg->next, msg->prio, (char *)&msg->str); logdbg(stderr, "\n\n"); } #endif int log_enqueue (int prio, const char * fmt, va_list ap) { int len, fwd; char buff[MAX_MSG_SIZE]; struct logmsg * msg; struct logmsg * lastmsg; lastmsg = (struct logmsg *)la->tail; if (!la->empty) { fwd = sizeof(struct logmsg) + strlen((char *)&lastmsg->str) * sizeof(char) + 1; la->tail += fwd; } vsnprintf(buff, MAX_MSG_SIZE, fmt, ap); len = strlen(buff) * sizeof(char) + 1; /* not enough space on tail : rewind */ if (la->head <= la->tail && (len + sizeof(struct logmsg)) > (la->end - la->tail)) { logdbg(stderr, "enqueue: rewind tail to %p\n", la->tail); la->tail = la->start; } /* not enough space on head : drop msg */ if (la->head > la->tail && (len + sizeof(struct logmsg)) > (la->head - la->tail)) { logdbg(stderr, "enqueue: log area overrun, drop msg\n"); if (!la->empty) la->tail = lastmsg; return 1; } /* ok, we can stage the msg in the area */ la->empty = 0; msg = (struct logmsg *)la->tail; msg->prio = prio; memcpy((void *)&msg->str, buff, len); lastmsg->next = la->tail; msg->next = la->head; logdbg(stderr, "enqueue: %p, %p, %i, %s\n", (void *)msg, msg->next, msg->prio, (char *)&msg->str); #if LOGDBG dump_logarea(); #endif return 0; } int log_dequeue (void * buff) { struct logmsg * src = (struct logmsg *)la->head; struct logmsg * dst = (struct logmsg *)buff; struct logmsg * lst = (struct logmsg *)la->tail; int len; if (la->empty) return 0; len = strlen((char *)&src->str) * sizeof(char) + sizeof(struct logmsg) + 1; dst->prio = src->prio; memcpy(dst, src, len); if (la->tail == la->head) la->empty = 1; /* purge the last log msg */ else { la->head = src->next; lst->next = la->head; } logdbg(stderr, "dequeue: %p, %p, %i, %s\n", (void *)src, src->next, src->prio, (char *)&src->str); memset((void *)src, 0, len); return len; } /* * this one can block under memory pressure */ static void log_syslog (void * buff) { struct logmsg * msg = (struct logmsg *)buff; syslog(msg->prio, "%s", (char *)&msg->str); } void log_do_log_daemon(int prio, void *priv, const char *fmt, va_list ap) { struct sembuf ops[1]; ops[0].sem_num = la->ops[0].sem_num; ops[0].sem_flg = la->ops[0].sem_flg; ops[0].sem_op = -1; if (semop(la->semid, ops, 1) < 0) { syslog(LOG_ERR, "semop down failed %d", errno); return; } log_enqueue(prio, fmt, ap); ops[0].sem_op = 1; if (semop(la->semid, ops, 1) < 0) syslog(LOG_ERR, "semop up failed"); } void log_do_log_std(int prio, void *priv, const char *fmt, va_list ap) { if (prio == LOG_INFO) { vfprintf(stdout, fmt, ap); fprintf(stdout, "\n"); } else { fprintf(stderr, "%s: ", log_name); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); fflush(stderr); } } void log_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log_func(LOG_WARNING, log_func_priv, fmt, ap); va_end(ap); } void log_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log_func(LOG_ERR, log_func_priv, fmt, ap); va_end(ap); } void log_debug(int level, const char *fmt, ...) { if (log_level > level) { va_list ap; va_start(ap, fmt); log_func(LOG_DEBUG, log_func_priv, fmt, ap); va_end(ap); } } void log_info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log_func(LOG_INFO, log_func_priv, fmt, ap); va_end(ap); } #if 0 /* Unused */ static void __dump_line(int level, unsigned char *buf, int *cp) { char line[16*3+5], *lp = line; int i, cnt; cnt = *cp; if (!cnt) return; for (i = 0; i < 16; i++) { if (i < cnt) lp += sprintf(lp, " %02x", buf[i]); else lp += sprintf(lp, " "); if ((i % 4) == 3) lp += sprintf(lp, " |"); if (i >= cnt || !isprint(buf[i])) buf[i] = ' '; } log_debug(level, "%s %.16s |", line, buf); *cp = 0; } static void __dump_char(int level, unsigned char *buf, int *cp, int ch) { int cnt = (*cp)++; buf[cnt] = ch; if (cnt == 15) __dump_line(level, buf, cp); } #define dump_line() __dump_line(level, char_buf, &char_cnt) #define dump_char(ch) __dump_char(level, char_buf, &char_cnt, ch) #endif /* Unused */ static void log_flush(void) { int msglen; struct sembuf ops[1]; ops[0].sem_num = la->ops[0].sem_num; ops[0].sem_flg = la->ops[0].sem_flg; while (!la->empty) { ops[0].sem_op = -1; if (semop(la->semid, ops, 1) < 0) { syslog(LOG_ERR, "semop down failed %d", errno); exit(1); } msglen = log_dequeue(la->buff); ops[0].sem_op = 1; if (semop(la->semid, ops, 1) < 0) { syslog(LOG_ERR, "semop up failed"); exit(1); } if (msglen) log_syslog(la->buff); } } static void catch_signal(int signo) { switch (signo) { case SIGSEGV: log_flush(); break; case SIGTERM: log_stop_daemon = 1; break; } log_debug(1, "pid %d caught signal -%d", getpid(), signo); } static void __log_close(void) { if (log_func == log_do_log_daemon) { log_flush(); closelog(); free_logarea(); } } int log_init(char *program_name, int size, void (*func)(int prio, void *priv, const char *fmt, va_list ap), void *priv) { logdbg(stderr,"enter log_init\n"); log_name = program_name; log_func = func; log_func_priv = priv; if (log_func == log_do_log_daemon) { struct sigaction sa_old; struct sigaction sa_new; pid_t pid; openlog(log_name, 0, LOG_DAEMON); setlogmask (LOG_UPTO (LOG_DEBUG)); if (logarea_init(size)) { syslog(LOG_ERR, "logarea init failed"); return -1; } pid = fork(); if (pid < 0) { syslog(LOG_ERR, "starting logger failed"); exit(1); } else if (pid) { syslog(LOG_WARNING, "iSCSI logger with pid=%d started!", pid); return pid; } daemon_init(); /* flush on daemon's crash */ sa_new.sa_handler = (void*)catch_signal; sigemptyset(&sa_new.sa_mask); sa_new.sa_flags = 0; sigaction(SIGSEGV, &sa_new, &sa_old ); sigaction(SIGTERM, &sa_new, &sa_old ); while(1) { log_flush(); sleep(1); if (log_stop_daemon) break; } __log_close(); exit(0); } return 0; } void log_close(pid_t pid) { int status; if (log_func != log_do_log_daemon || pid < 0) { __log_close(); return; } if (pid > 0) { kill(pid, SIGTERM); waitpid(pid, &status, 0); } } open-iscsi-2.0.873/usr/log.h000066400000000000000000000043421175631155400155220ustar00rootroot00000000000000/* * iSCSI Safe Logging and Tracing Library * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * circular buffer code based on log.c from dm-multipath project * * heavily based on code from log.c: * Copyright (C) 2002-2003 Ardis Technolgies , * licensed under the terms of the GNU GPL v2.0, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef LOG_H #define LOG_H #include #include #include "iscsid.h" union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; #include #define DEFAULT_AREA_SIZE 16384 #define MAX_MSG_SIZE 256 extern int log_level; struct logmsg { short int prio; void *next; char *str; }; struct logarea { int shmid; int shmid_msg; int shmid_buff; int empty; void *head; void *tail; void *start; void *end; char *buff; struct sembuf ops[1]; int semid; union semun semarg; }; struct logarea *la; extern int log_init(char *program_name, int size, void (*func)(int prio, void *priv, const char *fmt, va_list ap), void *priv); extern void log_close (pid_t pid); extern void dump_logmsg (void *); extern void log_info(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); extern void log_warning(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); extern void log_error(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); extern void log_debug(int level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern void log_do_log_daemon(int prio, void *priv, const char *fmt, va_list ap); extern void log_do_log_std(int prio, void *priv, const char *fmt, va_list ap); #endif /* LOG_H */ open-iscsi-2.0.873/usr/login.c000066400000000000000000001310231175631155400160410ustar00rootroot00000000000000/* * iSCSI Login Library * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * heavily based on code from iscsi-login.c: * Copyright (C) 2001 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. * * Formation of iSCSI login pdu, processing the login response and other * functions are defined here */ #include #include #include #include #include #include #include #include "initiator.h" #include "transport.h" #include "log.h" #include "iscsi_timer.h" /* caller is assumed to be well-behaved and passing NUL terminated strings */ int iscsi_add_text(struct iscsi_hdr *pdu, char *data, int max_data_length, char *param, char *value) { int param_len = strlen(param); int value_len = strlen(value); int length = param_len + 1 + value_len + 1; /* param, separator, * value, and trailing * NULL */ int pdu_length = ntoh24(pdu->dlength); char *text = data; char *end = data + max_data_length; char *pdu_text; /* find the end of the current text */ text += pdu_length; pdu_text = text; pdu_length += length; if (text + length >= end) { log_warning("Failed to add login text " "'%s=%s'\n", param, value); return 0; } /* param */ strncpy(text, param, param_len); text += param_len; /* separator */ *text++ = ISCSI_TEXT_SEPARATOR; /* value */ strncpy(text, value, value_len); text += value_len; /* NUL */ *text++ = '\0'; /* update the length in the PDU header */ hton24(pdu->dlength, pdu_length); return 1; } static int iscsi_find_key_value(char *param, char *pdu, char *pdu_end, char **value_start, char **value_end) { char *str = param; char *text = pdu; char *value; if (value_start) *value_start = NULL; if (value_end) *value_end = NULL; /* make sure they contain the same bytes */ while (*str) { if (text >= pdu_end) return 0; if (*text == '\0') return 0; if (*str != *text) return 0; str++; text++; } if ((text >= pdu_end) || (*text == '\0') || (*text != ISCSI_TEXT_SEPARATOR)) { return 0; } /* find the value */ value = text + 1; /* find the end of the value */ while ((text < pdu_end) && (*text)) text++; if (value_start) *value_start = value; if (value_end) *value_end = text; return 1; } static enum iscsi_login_status get_auth_key_type(struct iscsi_acl *auth_client, char **data, char *end) { char *key; char *value = NULL; char *value_end = NULL; char *text = *data; int keytype = AUTH_KEY_TYPE_NONE; while (acl_get_next_key_type(&keytype) == AUTH_STATUS_NO_ERROR) { key = (char *)acl_get_key_name(keytype); if (key && iscsi_find_key_value(key, text, end, &value, &value_end)) { if (acl_recv_key_value(auth_client, keytype, value) != AUTH_STATUS_NO_ERROR) { log_error("login negotiation failed, can't " "accept %s in security stage", text); return LOGIN_NEGOTIATION_FAILED; } text = value_end; *data = text; return LOGIN_OK; } } log_error("Login negotiation failed, can't accept %s in security " "stage", text); return LOGIN_NEGOTIATION_FAILED; } int resolve_address(char *host, char *port, struct sockaddr_storage *ss) { struct addrinfo hints, *res; int rc; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rc = getaddrinfo(host, port, &hints, &res))) { log_error("Cannot resolve host %s. getaddrinfo error: " "[%s]\n", host, gai_strerror(rc)); return rc; } memcpy(ss, res->ai_addr, res->ai_addrlen); freeaddrinfo(res); return rc; } /* * try to reset the session's IP address and port, based on the TargetAddress * provided */ int iscsi_update_address(iscsi_conn_t *conn, char *address) { char *port, *tag; char default_port[NI_MAXSERV]; iscsi_session_t *session = conn->session; struct sockaddr_storage addr; if ((tag = strrchr(address, ','))) { *tag = '\0'; tag++; } if ((port = strrchr(address, ':'))) { *port = '\0'; port++; } if (!port) { sprintf(default_port, "%d", ISCSI_LISTEN_PORT); port = default_port; } if (*address == '[') { char *end_bracket; if (!(end_bracket = strchr(address, ']'))) { log_error("Invalid IPv6 address with opening bracket, " "but no closing bracket."); return 0; } *end_bracket = '\0'; address++; } if (resolve_address(address, port, &addr)) { log_error("cannot resolve host name %s", address); return 0; } conn->saddr = addr; if (tag) session->portal_group_tag = atoi(tag); return 1; } static enum iscsi_login_status get_security_text_keys(iscsi_session_t *session, int cid, char **data, struct iscsi_acl *auth_client, char *end) { char *text = *data; char *value = NULL; char *value_end = NULL; size_t size; int tag; enum iscsi_login_status ret; /* * a few keys are possible in Security stage * which the auth code doesn't care about, but * which we might want to see, or at least not * choke on. */ if (iscsi_find_key_value("TargetAlias", text, end, &value, &value_end)) { size = value_end - value; session->target_alias = malloc(size + 1); if (!session->target_alias) { /* Alias not critical. So just print an error */ log_error("Login failed to allocate alias"); *data = value_end; return LOGIN_OK; } memcpy(session->target_alias, value, size); session->target_alias[size] = '\0'; text = value_end; } else if (iscsi_find_key_value("TargetAddress", text, end, &value, &value_end)) { /* * if possible, change the session's * ip_address and port to the new TargetAddress for * leading connection */ if (iscsi_update_address(&session->conn[cid], value)) { text = value_end; } else { log_error("Login redirection failed, " "can't handle redirection to %s", value); return LOGIN_REDIRECTION_FAILED; } } else if (iscsi_find_key_value("TargetPortalGroupTag", text, end, &value, &value_end)) { /* * We should have already obtained this * via discovery, but the value could be stale. * If the target was reconfigured it will send us * the updated tpgt. */ tag = strtoul(value, NULL, 0); if (session->portal_group_tag >= 0) { if (tag != session->portal_group_tag) log_debug(2, "Portal group tag " "mismatch, expected %u, " "received %u. Updating", session->portal_group_tag, tag); } /* we now know the tag */ session->portal_group_tag = tag; text = value_end; } else { /* * any key we don't recognize either * goes to the auth code, or we choke * on it */ ret = get_auth_key_type(auth_client, &text, end); if (ret != LOGIN_OK) return ret; } *data = text; return LOGIN_OK; } static enum iscsi_login_status get_op_params_text_keys(iscsi_session_t *session, int cid, char **data, char *end) { char *text = *data; char *value = NULL; char *value_end = NULL; size_t size; iscsi_conn_t *conn = &session->conn[cid]; if (iscsi_find_key_value("TargetAlias", text, end, &value, &value_end)) { size = value_end - value; if (session->target_alias && strlen(session->target_alias) == size && memcmp(session->target_alias, value, size) == 0) { *data = value_end; return LOGIN_OK; } free(session->target_alias); session->target_alias = malloc(size + 1); if (!session->target_alias) { /* Alias not critical. So just print an error */ log_error("Login failed to allocate alias"); *data = value_end; return LOGIN_OK; } memcpy(session->target_alias, value, size); session->target_alias[size] = '\0'; text = value_end; } else if (iscsi_find_key_value("TargetAddress", text, end, &value, &value_end)) { if (iscsi_update_address(conn, value)) text = value_end; else { log_error("Login redirection failed, " "can't handle redirection to %s", value); return LOGIN_REDIRECTION_FAILED; } } else if (iscsi_find_key_value("TargetPortalGroupTag", text, end, &value, &value_end)) { int tag = strtoul(value, NULL, 0); /* * We should have already obtained this * via discovery, but the value could be stale. * If the target was reconfigured it will send us * the updated tpgt. */ if (session->portal_group_tag >= 0) { if (tag != session->portal_group_tag) log_debug(2, "Portal group tag " "mismatch, expected %u, " "received %u. Updating", session->portal_group_tag, tag); } /* we now know the tag */ session->portal_group_tag = tag; text = value_end; } else if (iscsi_find_key_value("InitialR2T", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (value && (strcmp(value, "Yes") == 0)) session->initial_r2t_en = 1; else session->initial_r2t_en = 0; } else session->irrelevant_keys_bitmap |= IRRELEVANT_INITIALR2T; text = value_end; } else if (iscsi_find_key_value("ImmediateData", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (value && (strcmp(value, "Yes") == 0)) session->imm_data_en = 1; else session->imm_data_en = 0; } else session->irrelevant_keys_bitmap |= IRRELEVANT_IMMEDIATEDATA; text = value_end; } else if (iscsi_find_key_value("MaxRecvDataSegmentLength", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_DISCOVERY || !session->t->template->rdma) { int tgt_max_xmit; conn_rec_t *conn_rec = &session->nrec.conn[cid]; tgt_max_xmit = strtoul(value, NULL, 0); /* * if the rec value is zero it means to use * what the target gave us. */ if (!conn_rec->iscsi.MaxXmitDataSegmentLength || tgt_max_xmit < conn->max_xmit_dlength) conn->max_xmit_dlength = tgt_max_xmit; } text = value_end; } else if (iscsi_find_key_value("FirstBurstLength", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) session->first_burst = strtoul(value, NULL, 0); else session->irrelevant_keys_bitmap |= IRRELEVANT_FIRSTBURSTLENGTH; text = value_end; } else if (iscsi_find_key_value("MaxBurstLength", text, end, &value, &value_end)) { /* * we don't really care, since it's a limit on the target's * R2Ts, but record it anwyay */ if (session->type == ISCSI_SESSION_TYPE_NORMAL) session->max_burst = strtoul(value, NULL, 0); else session->irrelevant_keys_bitmap |= IRRELEVANT_MAXBURSTLENGTH; text = value_end; } else if (iscsi_find_key_value("HeaderDigest", text, end, &value, &value_end)) { if (strcmp(value, "None") == 0) { if (conn->hdrdgst_en != ISCSI_DIGEST_CRC32C) conn->hdrdgst_en = ISCSI_DIGEST_NONE; else { log_error("Login negotiation " "failed, HeaderDigest=CRC32C " "is required, can't accept " "%s", text); return LOGIN_NEGOTIATION_FAILED; } } else if (strcmp(value, "CRC32C") == 0) { if (conn->hdrdgst_en != ISCSI_DIGEST_NONE) conn->hdrdgst_en = ISCSI_DIGEST_CRC32C; else { log_error("Login negotiation " "failed, HeaderDigest=None is " "required, can't accept %s", text); return LOGIN_NEGOTIATION_FAILED; } } else { log_error("Login negotiation failed, " "can't accept %s", text); return LOGIN_NEGOTIATION_FAILED; } text = value_end; } else if (iscsi_find_key_value("DataDigest", text, end, &value, &value_end)) { if (strcmp(value, "None") == 0) { if (conn->datadgst_en != ISCSI_DIGEST_CRC32C) conn->datadgst_en = ISCSI_DIGEST_NONE; else { log_error("Login negotiation " "failed, DataDigest=CRC32C " "is required, can't accept %s", text); return LOGIN_NEGOTIATION_FAILED; } } else if (strcmp(value, "CRC32C") == 0) { if (conn->datadgst_en != ISCSI_DIGEST_NONE) conn->datadgst_en = ISCSI_DIGEST_CRC32C; else { log_error("Login negotiation " "failed, DataDigest=None is " "required, can't accept %s", text); return LOGIN_NEGOTIATION_FAILED; } } else { log_error("Login negotiation failed, " "can't accept %s", text); return LOGIN_NEGOTIATION_FAILED; } text = value_end; } else if (iscsi_find_key_value("DefaultTime2Wait", text, end, &value, &value_end)) { session->def_time2wait = strtoul(value, NULL, 0); text = value_end; } else if (iscsi_find_key_value("DefaultTime2Retain", text, end, &value, &value_end)) { session->def_time2retain = strtoul(value, NULL, 0); text = value_end; } else if (iscsi_find_key_value("OFMarker", text, end, &value, &value_end)) /* result function is AND, target must honor our No */ text = value_end; else if (iscsi_find_key_value("OFMarkInt", text, end, &value, &value_end)) /* we don't do markers, so we don't care */ text = value_end; else if (iscsi_find_key_value("IFMarker", text, end, &value, &value_end)) /* result function is AND, target must honor our No */ text = value_end; else if (iscsi_find_key_value("IFMarkInt", text, end, &value, &value_end)) /* we don't do markers, so we don't care */ text = value_end; else if (iscsi_find_key_value("DataPDUInOrder", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (value && strcmp(value, "Yes") == 0) session->pdu_inorder_en = 1; else session->pdu_inorder_en = 0; } else session->irrelevant_keys_bitmap |= IRRELEVANT_DATAPDUINORDER; text = value_end; } else if (iscsi_find_key_value ("DataSequenceInOrder", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) if (value && strcmp(value, "Yes") == 0) session->dataseq_inorder_en = 1; else session->dataseq_inorder_en = 0; else session->irrelevant_keys_bitmap |= IRRELEVANT_DATASEQUENCEINORDER; text = value_end; } else if (iscsi_find_key_value("MaxOutstandingR2T", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (strcmp(value, "1")) { log_error("Login negotiation " "failed, can't accept Max" "OutstandingR2T %s", value); return LOGIN_NEGOTIATION_FAILED; } } else session->irrelevant_keys_bitmap |= IRRELEVANT_MAXOUTSTANDINGR2T; text = value_end; } else if (iscsi_find_key_value("MaxConnections", text, end, &value, &value_end)) { if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (strcmp(value, "1")) { log_error("Login negotiation " "failed, can't accept Max" "Connections %s", value); return LOGIN_NEGOTIATION_FAILED; } } else session->irrelevant_keys_bitmap |= IRRELEVANT_MAXCONNECTIONS; text = value_end; } else if (iscsi_find_key_value("ErrorRecoveryLevel", text, end, &value, &value_end)) { if (strcmp(value, "0")) { log_error("Login negotiation failed, " "can't accept ErrorRecovery %s", value); return LOGIN_NEGOTIATION_FAILED; } text = value_end; } else if (iscsi_find_key_value("RDMAExtensions", text, end, &value, &value_end)) { if (session->t->template->rdma && strcmp(value, "Yes") != 0) { log_error("Login negotiation failed, " "Target must support RDMAExtensions"); return LOGIN_NEGOTIATION_FAILED; } text = value_end; } else if (iscsi_find_key_value("InitiatorRecvDataSegmentLength", text, end, &value, &value_end)) { if (session->t->template->rdma) { conn->max_recv_dlength = MIN(conn->max_recv_dlength, strtoul(value, NULL, 0)); } text = value_end; } else if (iscsi_find_key_value("TargetRecvDataSegmentLength", text, end, &value, &value_end)) { if (session->t->template->rdma) { conn->max_xmit_dlength = MIN(conn->max_xmit_dlength, strtoul(value, NULL, 0)); } text = value_end; } else if (iscsi_find_key_value ("X-com.cisco.protocol", text, end, &value, &value_end)) { if (strcmp(value, "NotUnderstood") && strcmp(value, "Reject") && strcmp(value, "Irrelevant") && strcmp(value, "draft20")) { /* if we didn't get a compatible protocol, fail */ log_error("Login version mismatch, " "can't accept protocol %s", value); return LOGIN_VERSION_MISMATCH; } text = value_end; } else if (iscsi_find_key_value("X-com.cisco.PingTimeout", text, end, &value, &value_end)) /* we don't really care what the target ends up using */ text = value_end; else if (iscsi_find_key_value("X-com.cisco.sendAsyncText", text, end, &value, &value_end)) /* we don't bother for the target response */ text = value_end; else { log_error("Login negotiation failed, couldn't " "recognize text %s", text); return LOGIN_NEGOTIATION_FAILED; } *data = text; return LOGIN_OK; } static enum iscsi_login_status check_security_stage_status(iscsi_session_t *session, struct iscsi_acl *auth_client) { int debug_status = 0; switch (acl_recv_end(auth_client, session)) { case AUTH_STATUS_CONTINUE: /* continue sending PDUs */ break; case AUTH_STATUS_PASS: break; case AUTH_STATUS_NO_ERROR: /* treat this as an error, * since we should get a * different code */ case AUTH_STATUS_ERROR: case AUTH_STATUS_FAIL: default: if (acl_get_dbg_status(auth_client, &debug_status) != AUTH_STATUS_NO_ERROR) log_error("Login authentication failed " "with target %s, %s", session->target_name, acl_dbg_status_to_text(debug_status)); else log_error("Login authentication failed " "with target %s", session->target_name); return LOGIN_AUTHENTICATION_FAILED; } return LOGIN_OK; } /* * this assumes the text data is always NULL terminated. The caller can * always arrange for that by using a slightly larger buffer than the max PDU * size, and then appending a NULL to the PDU. */ static enum iscsi_login_status iscsi_process_login_response(iscsi_session_t *session, int cid, struct iscsi_login_rsp *login_rsp, char *data, int max_data_length) { int transit = login_rsp->flags & ISCSI_FLAG_LOGIN_TRANSIT; char *text = data; char *end; int pdu_current_stage, pdu_next_stage; enum iscsi_login_status ret; struct iscsi_acl *auth_client; iscsi_conn_t *conn = &session->conn[cid]; auth_client = (session->auth_buffers && session->num_auth_buffers) ? (struct iscsi_acl *)session->auth_buffers[0].address : NULL; end = text + ntoh24(login_rsp->dlength) + 1; if (end >= (data + max_data_length)) { log_error("Login failed, process_login_response " "buffer too small to guarantee NULL " "termination"); return LOGIN_FAILED; } /* guarantee a trailing NUL */ *end = '\0'; /* if the response status was success, sanity check the response */ if (login_rsp->status_class == ISCSI_STATUS_CLS_SUCCESS) { /* check the active version */ if (login_rsp->active_version != ISCSI_DRAFT20_VERSION) { log_error("Login version mismatch, " "received incompatible active iSCSI " "version 0x%02x, expected version " "0x%02x", login_rsp->active_version, ISCSI_DRAFT20_VERSION); return LOGIN_VERSION_MISMATCH; } /* make sure the current stage matches */ pdu_current_stage = (login_rsp->flags & ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK) >> 2; if (pdu_current_stage != conn->current_stage) { log_error("Received invalid login PDU, " "current stage mismatch, session %d, " "response %d", conn->current_stage, pdu_current_stage); return LOGIN_INVALID_PDU; } /* * make sure that we're actually advancing if the T-bit is set */ pdu_next_stage = login_rsp->flags & ISCSI_FLAG_LOGIN_NEXT_STAGE_MASK; if (transit && (pdu_next_stage <= conn->current_stage)) return LOGIN_INVALID_PDU; } if (conn->current_stage == ISCSI_SECURITY_NEGOTIATION_STAGE) { if (acl_recv_begin(auth_client) != AUTH_STATUS_NO_ERROR) { log_error("Login failed because " "acl_recv_begin failed"); return LOGIN_FAILED; } if (acl_recv_transit_bit(auth_client, transit) != AUTH_STATUS_NO_ERROR) { log_error("Login failed because " "acl_recv_transit_bit failed"); return LOGIN_FAILED; } } /* scan the text data */ while (text && (text < end)) { /* skip any NULs separating each text key=value pair */ while ((text < end) && (*text == '\0')) text++; if (text >= end) break; /* handle keys appropriate for each stage */ switch (conn->current_stage) { case ISCSI_SECURITY_NEGOTIATION_STAGE:{ ret = get_security_text_keys(session, cid, &text, auth_client, end); if (ret != LOGIN_OK) return ret; break; } case ISCSI_OP_PARMS_NEGOTIATION_STAGE:{ ret = get_op_params_text_keys(session, cid, &text, end); if (ret != LOGIN_OK) return ret; break; } default: return LOGIN_FAILED; } } if (conn->current_stage == ISCSI_SECURITY_NEGOTIATION_STAGE) { ret = check_security_stage_status(session, auth_client); if (ret != LOGIN_OK) return ret; } /* record some of the PDU fields for later use */ session->tsih = ntohs(login_rsp->tsih); session->exp_cmdsn = ntohl(login_rsp->exp_cmdsn); session->max_cmdsn = ntohl(login_rsp->max_cmdsn); if (login_rsp->status_class == ISCSI_STATUS_CLS_SUCCESS) conn->exp_statsn = ntohl(login_rsp->statsn) + 1; if (transit) { /* advance to the next stage */ conn->partial_response = 0; conn->current_stage = login_rsp->flags & ISCSI_FLAG_LOGIN_NEXT_STAGE_MASK; session->irrelevant_keys_bitmap = 0; } else /* * we got a partial response, don't advance, * more negotiation to do */ conn->partial_response = 1; return LOGIN_OK; /* this PDU is ok, though the login process * may not be done yet */ } static int add_params_normal_session(iscsi_session_t *session, struct iscsi_hdr *pdu, char *data, int max_data_length) { char value[AUTH_STR_MAX_LEN]; /* these are only relevant for normal sessions */ if (!iscsi_add_text(pdu, data, max_data_length, "InitialR2T", session->initial_r2t_en ? "Yes" : "No")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "ImmediateData", session->imm_data_en ? "Yes" : "No")) return 0; sprintf(value, "%d", session->max_burst); if (!iscsi_add_text(pdu, data, max_data_length, "MaxBurstLength", value)) return 0; sprintf(value, "%d",session->first_burst); if (!iscsi_add_text(pdu, data, max_data_length, "FirstBurstLength", value)) return 0; /* these we must have */ if (!iscsi_add_text(pdu, data, max_data_length, "MaxOutstandingR2T", "1")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "MaxConnections", "1")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "DataPDUInOrder", "Yes")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "DataSequenceInOrder", "Yes")) return 0; return 1; } static int add_params_transport_specific(iscsi_session_t *session, int cid, struct iscsi_hdr *pdu, char *data, int max_data_length) { char value[AUTH_STR_MAX_LEN]; iscsi_conn_t *conn = &session->conn[cid]; if (session->type == ISCSI_SESSION_TYPE_DISCOVERY || !session->t->template->rdma) { sprintf(value, "%d", conn->max_recv_dlength); if (!iscsi_add_text(pdu, data, max_data_length, "MaxRecvDataSegmentLength", value)) return 0; } else { sprintf(value, "%d", conn->max_recv_dlength); if (!iscsi_add_text(pdu, data, max_data_length, "InitiatorRecvDataSegmentLength", value)) return 0; sprintf(value, "%d", conn->max_xmit_dlength); if (!iscsi_add_text(pdu, data, max_data_length, "TargetRecvDataSegmentLength", value)) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "RDMAExtensions", "Yes")) return 0; } return 1; } static int check_irrelevant_keys(iscsi_session_t *session, struct iscsi_hdr *pdu, char *data, int max_data_length) { /* If you receive irrelevant keys, just check them from the irrelevant * keys bitmap and respond with the key=Irrelevant text */ if (session->irrelevant_keys_bitmap & IRRELEVANT_MAXCONNECTIONS) if (!iscsi_add_text(pdu, data, max_data_length, "MaxConnections", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_INITIALR2T) if (!iscsi_add_text(pdu, data, max_data_length, "InitialR2T", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_IMMEDIATEDATA) if (!iscsi_add_text(pdu, data, max_data_length, "ImmediateData", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_MAXBURSTLENGTH) if (!iscsi_add_text(pdu, data, max_data_length, "MaxBurstLength", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_FIRSTBURSTLENGTH) if (!iscsi_add_text(pdu, data, max_data_length, "FirstBurstLength", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_MAXOUTSTANDINGR2T) if (!iscsi_add_text(pdu, data, max_data_length, "MaxOutstandingR2T", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_DATAPDUINORDER) if (!iscsi_add_text(pdu, data, max_data_length, "DataPDUInOrder", "Irrelevant")) return 0; if (session->irrelevant_keys_bitmap & IRRELEVANT_DATASEQUENCEINORDER ) if (!iscsi_add_text(pdu, data, max_data_length, "DataSequenceInOrder", "Irrelevant")) return 0; return 1; } static int fill_crc_digest_text(iscsi_conn_t *conn, struct iscsi_hdr *pdu, char *data, int max_data_length) { switch (conn->hdrdgst_en) { case ISCSI_DIGEST_NONE: if (!iscsi_add_text(pdu, data, max_data_length, "HeaderDigest", "None")) return 0; break; case ISCSI_DIGEST_CRC32C: if (!iscsi_add_text(pdu, data, max_data_length, "HeaderDigest", "CRC32C")) return 0; break; case ISCSI_DIGEST_CRC32C_NONE: if (!iscsi_add_text(pdu, data, max_data_length, "HeaderDigest", "CRC32C,None")) return 0; break; default: case ISCSI_DIGEST_NONE_CRC32C: if (!iscsi_add_text(pdu, data, max_data_length, "HeaderDigest", "None,CRC32C")) return 0; break; } switch (conn->datadgst_en) { case ISCSI_DIGEST_NONE: if (!iscsi_add_text(pdu, data, max_data_length, "DataDigest", "None")) return 0; break; case ISCSI_DIGEST_CRC32C: if (!iscsi_add_text(pdu, data, max_data_length, "DataDigest", "CRC32C")) return 0; break; case ISCSI_DIGEST_CRC32C_NONE: if (!iscsi_add_text(pdu, data, max_data_length, "DataDigest", "CRC32C,None")) return 0; break; default: case ISCSI_DIGEST_NONE_CRC32C: if (!iscsi_add_text(pdu, data, max_data_length, "DataDigest", "None,CRC32C")) return 0; break; } return 1; } static int fill_op_params_text(iscsi_session_t *session, int cid, struct iscsi_hdr *pdu, char *data, int max_data_length, int *transit) { char value[AUTH_STR_MAX_LEN]; iscsi_conn_t *conn = &session->conn[cid]; int rdma; /* we always try to go from op params to full feature stage */ conn->current_stage = ISCSI_OP_PARMS_NEGOTIATION_STAGE; conn->next_stage = ISCSI_FULL_FEATURE_PHASE; *transit = 1; rdma = (session->type == ISCSI_SESSION_TYPE_NORMAL) && session->t->template->rdma; /* * If we haven't gotten a partial response, then either we shouldn't be * here, or we just switched to this stage, and need to start offering * keys. */ if (!conn->partial_response) { /* * request the desired settings the first time * we are in this stage */ if (!rdma && !fill_crc_digest_text(conn, pdu, data, max_data_length)) return 0; sprintf(value, "%d", session->def_time2wait); if (!iscsi_add_text(pdu, data, max_data_length, "DefaultTime2Wait", value)) return 0; sprintf(value, "%d", session->def_time2retain); if (!iscsi_add_text(pdu, data, max_data_length, "DefaultTime2Retain", value)) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "IFMarker", "No")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "OFMarker", "No")) return 0; if (!iscsi_add_text(pdu, data, max_data_length, "ErrorRecoveryLevel", "0")) return 0; if (session->type == ISCSI_SESSION_TYPE_NORMAL) { if (!add_params_normal_session(session, pdu, data, max_data_length)) return 0; if (!add_params_transport_specific(session, cid, pdu, data, max_data_length)) return 0; } else { sprintf(value, "%d", conn->max_recv_dlength); if (!iscsi_add_text(pdu, data, max_data_length, "MaxRecvDataSegmentLength", value)) return 0; } } else { if (!check_irrelevant_keys(session, pdu, data, max_data_length)) return 0; if (rdma && !fill_crc_digest_text(conn, pdu, data, max_data_length)) return 0; } return 1; } static void enum_auth_keys(struct iscsi_acl *auth_client, struct iscsi_hdr *pdu, char *data, int max_data_length, int keytype) { int present = 0, rc; char *key = (char *)acl_get_key_name(keytype); int key_length = key ? strlen(key) : 0; int pdu_length = ntoh24(pdu->dlength); char *auth_value = data + pdu_length + key_length + 1; unsigned int max_length = max_data_length - (pdu_length + key_length + 1); /* * add the key/value pairs the auth code wants to send * directly to the PDU, since they could in theory be large. */ rc = acl_send_key_val(auth_client, keytype, &present, auth_value, max_length); if ((rc == AUTH_STATUS_NO_ERROR) && present) { /* actually fill in the key */ strncpy(&data[pdu_length], key, key_length); pdu_length += key_length; data[pdu_length] = '='; pdu_length++; /* * adjust the PDU's data segment length * to include the value and trailing NUL */ pdu_length += strlen(auth_value) + 1; hton24(pdu->dlength, pdu_length); } } static int fill_security_params_text(iscsi_session_t *session, int cid, struct iscsi_hdr *pdu, struct iscsi_acl *auth_client, char *data, int max_data_length, int *transit) { int keytype = AUTH_KEY_TYPE_NONE; int rc = acl_send_transit_bit(auth_client, transit); iscsi_conn_t *conn = &session->conn[cid]; /* see if we're ready for a stage change */ if (rc != AUTH_STATUS_NO_ERROR) return 0; if (*transit) { /* * discovery sessions can go right to full-feature phase, * unless they want to non-standard values for the few relevant * keys, or want to offer vendor-specific keys */ if (session->type == ISCSI_SESSION_TYPE_DISCOVERY) if ((conn->hdrdgst_en != ISCSI_DIGEST_NONE) || (conn->datadgst_en != ISCSI_DIGEST_NONE) || (conn->max_recv_dlength != ISCSI_DEF_MAX_RECV_SEG_LEN)) conn->next_stage = ISCSI_OP_PARMS_NEGOTIATION_STAGE; else conn->next_stage = ISCSI_FULL_FEATURE_PHASE; else conn->next_stage = ISCSI_OP_PARMS_NEGOTIATION_STAGE; } else conn->next_stage = ISCSI_SECURITY_NEGOTIATION_STAGE; /* enumerate all the keys the auth code might want to send */ while (acl_get_next_key_type(&keytype) == AUTH_STATUS_NO_ERROR) enum_auth_keys(auth_client, pdu, data, max_data_length, keytype); return 1; } /** * iscsi_make_login_pdu - Prepare the login pdu to be sent to iSCSI target. * @session: session for which login is initiated. * @pdu: login header * @data: contains text keys to be negotiated during login * @max_data_length: data size * * Description: * Based on whether authentication is enabled or not, corresponding text * keys are filled up in login pdu. * **/ static int iscsi_make_login_pdu(iscsi_session_t *session, int cid, struct iscsi_hdr *hdr, char *data, int max_data_length) { int transit = 0; int ret; struct iscsi_login *login_hdr = (struct iscsi_login *)hdr; struct iscsi_acl *auth_client; iscsi_conn_t *conn = &session->conn[cid]; auth_client = (session->auth_buffers && session->num_auth_buffers) ? (struct iscsi_acl *)session->auth_buffers[0].address : NULL; /* initialize the PDU header */ memset(login_hdr, 0, sizeof(*login_hdr)); login_hdr->opcode = ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE; login_hdr->cid = 0; memcpy(login_hdr->isid, session->isid, sizeof(session->isid)); login_hdr->tsih = 0; login_hdr->cmdsn = htonl(session->cmdsn); /* don't increment on immediate */ login_hdr->min_version = ISCSI_DRAFT20_VERSION; login_hdr->max_version = ISCSI_DRAFT20_VERSION; login_hdr->exp_statsn = htonl(conn->exp_statsn); /* * the very first Login PDU has some additional requirements, * and we need to decide what stage to start in. */ if (conn->current_stage == ISCSI_INITIAL_LOGIN_STAGE) { if (session->initiator_name && session->initiator_name[0]) { if (!iscsi_add_text(hdr, data, max_data_length, "InitiatorName", session->initiator_name)) return 0; } else { log_error("InitiatorName is required " "on the first Login PDU"); return 0; } if (session->initiator_alias && session->initiator_alias[0]) { if (!iscsi_add_text(hdr, data, max_data_length, "InitiatorAlias", session->initiator_alias)) return 0; } if ((session->target_name && session->target_name[0]) && (session->type == ISCSI_SESSION_TYPE_NORMAL)) { if (!iscsi_add_text(hdr, data, max_data_length, "TargetName", session->target_name)) return 0; } if (!iscsi_add_text(hdr, data, max_data_length, "SessionType", (session->type == ISCSI_SESSION_TYPE_DISCOVERY) ? "Discovery" : "Normal")) return 0; if (auth_client) /* we're prepared to do authentication */ conn->current_stage = conn->next_stage = ISCSI_SECURITY_NEGOTIATION_STAGE; else /* can't do any authentication, skip that stage */ conn->current_stage = conn->next_stage = ISCSI_OP_PARMS_NEGOTIATION_STAGE; } /* fill in text based on the stage */ switch (conn->current_stage) { case ISCSI_OP_PARMS_NEGOTIATION_STAGE:{ ret = fill_op_params_text(session, cid, hdr, data, max_data_length, &transit); if (!ret) return ret; break; } case ISCSI_SECURITY_NEGOTIATION_STAGE:{ ret = fill_security_params_text(session, cid, hdr, auth_client, data, max_data_length, &transit); if (!ret) return ret; break; } case ISCSI_FULL_FEATURE_PHASE: log_error("Can't send login PDUs in full " "feature phase"); return 0; default: log_error("Can't send login PDUs in unknown " "stage %d", conn->current_stage); return 0; } /* fill in the flags */ login_hdr->flags = 0; login_hdr->flags |= conn->current_stage << 2; if (transit) { /* transit to the next stage */ login_hdr->flags |= conn->next_stage; login_hdr->flags |= ISCSI_FLAG_LOGIN_TRANSIT; } else /* next == current */ login_hdr->flags |= conn->current_stage; return 1; } static enum iscsi_login_status check_for_authentication(iscsi_session_t *session, struct iscsi_acl *auth_client) { enum iscsi_login_status ret = LOGIN_FAILED; auth_client = (struct iscsi_acl *)session->auth_buffers[0].address; /* prepare for authentication */ if (acl_init(TYPE_INITIATOR, session->num_auth_buffers, session->auth_buffers) != AUTH_STATUS_NO_ERROR) { log_error("Couldn't initialize authentication"); return LOGIN_FAILED; } if (session->username && (acl_set_user_name(auth_client, session->username) != AUTH_STATUS_NO_ERROR)) { log_error("Couldn't set username"); goto end; } if (session->password && (acl_set_passwd(auth_client, session->password, session->password_length) != AUTH_STATUS_NO_ERROR)) { log_error("Couldn't set password"); goto end; } if (acl_set_ip_sec(auth_client, 1) != AUTH_STATUS_NO_ERROR) { log_error("Couldn't set IPSec"); goto end; } if (acl_set_auth_rmt(auth_client, session->bidirectional_auth) != AUTH_STATUS_NO_ERROR) { log_error("Couldn't set remote authentication"); goto end; } return LOGIN_OK; end: if (auth_client && acl_finish(auth_client) != AUTH_STATUS_NO_ERROR) { log_error("Login failed, error finishing auth_client"); if (ret == LOGIN_OK) ret = LOGIN_FAILED; } return ret; } static enum iscsi_login_status check_status_login_response(iscsi_session_t *session, int cid, struct iscsi_login_rsp *login_rsp, char *data, int max_data_length, int *final) { enum iscsi_login_status ret; switch (login_rsp->status_class) { case ISCSI_STATUS_CLS_SUCCESS: /* process this response and possibly continue sending PDUs */ ret = iscsi_process_login_response(session, cid, login_rsp, data, max_data_length); if (ret != LOGIN_OK) /* pass back whatever * error we discovered */ *final = 1; break; case ISCSI_STATUS_CLS_REDIRECT: /* * we need to process this response to get the * TargetAddress of the redirect, but we don't care * about the return code. */ iscsi_process_login_response(session, cid, login_rsp, data, max_data_length); ret = LOGIN_REDIRECT; *final = 1; break; case ISCSI_STATUS_CLS_INITIATOR_ERR: if (login_rsp->status_detail == ISCSI_LOGIN_STATUS_AUTH_FAILED) { log_error("Login failed to authenticate " "with target %s", session->target_name); } ret = LOGIN_OK; *final = 1; break; default: /* * some sort of error, login terminated unsuccessfully, * though this function did it's job. * the caller must check the status_class and * status_detail and decide what to do next. */ ret = LOGIN_OK; *final = 1; } return ret; } int iscsi_login_begin(iscsi_session_t *session, iscsi_login_context_t *c) { iscsi_conn_t *conn = &session->conn[c->cid]; c->auth_client = NULL; c->login_rsp = (struct iscsi_login_rsp *)&c->pdu; c->received_pdu = 0; c->timeout = 0; c->final = 0; c->ret = LOGIN_FAILED; /* prepare the session of the connection is leading */ if (c->cid ==0) { session->cmdsn = 1; session->exp_cmdsn = 1; session->max_cmdsn = 1; } conn->current_stage = ISCSI_INITIAL_LOGIN_STAGE; conn->partial_response = 0; if (session->auth_buffers && session->num_auth_buffers) { c->ret = check_for_authentication(session, c->auth_client); if (c->ret != LOGIN_OK) return 1; } return 0; } int iscsi_login_req(iscsi_session_t *session, iscsi_login_context_t *c) { iscsi_conn_t *conn = &session->conn[c->cid]; c->final = 0; c->timeout = 0; c->login_rsp = (struct iscsi_login_rsp *)&c->pdu; c->ret = LOGIN_FAILED; memset(c->buffer, 0, c->bufsize); c->data = c->buffer; c->max_data_length = c->bufsize; /* * pick the appropriate timeout. If we know the target has * responded before, and we're in the security stage, we use a * longer timeout, since the authentication alogorithms can * take a while, especially if the target has to go talk to a * tacacs or RADIUS server (which may or may not be * responding). */ if (c->received_pdu && (conn->current_stage == ISCSI_SECURITY_NEGOTIATION_STAGE)) c->timeout = conn->auth_timeout; else c->timeout = conn->login_timeout; /* * fill in the PDU header and text data based on the login * stage that we're in */ if (!iscsi_make_login_pdu(session, c->cid, &c->pdu, c->data, c->max_data_length)) { log_error("login failed, couldn't make a login PDU"); c->ret = LOGIN_FAILED; goto done; } /* send a PDU to the target */ if (!iscsi_io_send_pdu(conn, &c->pdu, ISCSI_DIGEST_NONE, c->data, ISCSI_DIGEST_NONE, c->timeout)) { /* * FIXME: caller might want us to distinguish I/O * error and timeout. Might want to switch portals on * timeouts, but not I/O errors. */ log_error("Login I/O error, failed to send a PDU"); c->ret = LOGIN_IO_ERROR; goto done; } return 0; done: if (c->auth_client && acl_finish(c->auth_client) != AUTH_STATUS_NO_ERROR) { log_error("Login failed, error finishing c->auth_client"); if (c->ret == LOGIN_OK) c->ret = LOGIN_FAILED; } return 1; } int iscsi_login_rsp(iscsi_session_t *session, iscsi_login_context_t *c) { iscsi_conn_t *conn = &session->conn[c->cid]; int err; /* read the target's response into the same buffer */ err = iscsi_io_recv_pdu(conn, &c->pdu, ISCSI_DIGEST_NONE, c->data, c->max_data_length, ISCSI_DIGEST_NONE, c->timeout); if (err == -EAGAIN) { goto done; } else if (err < 0) { /* * FIXME: caller might want us to distinguish I/O * error and timeout. Might want to switch portals on * timeouts, but not I/O errors. */ log_error("Login I/O error, failed to receive a PDU"); c->ret = LOGIN_IO_ERROR; goto done; } err = -EIO; c->received_pdu = 1; /* check the PDU response type */ if (c->pdu.opcode == (ISCSI_OP_LOGIN_RSP | 0xC0)) { /* * it's probably a draft 8 login response, * which we can't deal with */ log_error("Received iSCSI draft 8 login " "response opcode 0x%x, expected draft " "20 login response 0x%2x", c->pdu.opcode, ISCSI_OP_LOGIN_RSP); c->ret = LOGIN_VERSION_MISMATCH; goto done; } else if (c->pdu.opcode != ISCSI_OP_LOGIN_RSP) { c->ret = LOGIN_INVALID_PDU; goto done; } /* * give the caller the status class and detail from the last * login response PDU received */ c->status_class = c->login_rsp->status_class; c->status_detail = c->login_rsp->status_detail; log_debug(1, "login response status %02d%02d", c->status_class, c->status_detail); c->ret = check_status_login_response(session, c->cid, c->login_rsp, c->data, c->max_data_length, &c->final); if (c->final) goto done; return 0; done: if (c->auth_client && acl_finish(c->auth_client) != AUTH_STATUS_NO_ERROR) { log_error("Login failed, error finishing c->auth_client"); if (c->ret == LOGIN_OK) c->ret = LOGIN_FAILED; } return err; } /** * iscsi_login - attempt to login to the target. * @session: login is initiated over this session * @buffer: holds login pdu * @bufsize: size of login pdu * @status_class: holds either success or failure as status of login * @status_detail: contains details based on the login status * * Description: * The caller must check the status class to determine if the login * succeeded. A return of 1 does not mean the login succeeded, it just * means this function worked, and the status class is valid info. * This allows the caller to decide whether or not to retry logins, so * that we don't have any policy logic here. **/ enum iscsi_login_status iscsi_login(iscsi_session_t *session, int cid, char *buffer, size_t bufsize, uint8_t *status_class, uint8_t *status_detail) { iscsi_conn_t *conn = &session->conn[cid]; iscsi_login_context_t *c = &conn->login_context; struct timeval connection_timer; struct pollfd pfd; int ret, timeout; /* * assume iscsi_login is only called from discovery, so it is * safe to always set to zero */ conn->exp_statsn = 0; c->cid = cid; c->buffer = buffer; c->bufsize = bufsize; if (iscsi_login_begin(session, c)) return c->ret; do { if (iscsi_login_req(session, c)) return c->ret; /* * TODO: merge the poll and req/rsp code with the discovery * poll and text req/rsp. */ iscsi_timer_set(&connection_timer, session->conn[0].active_timeout); timeout = iscsi_timer_msecs_until(&connection_timer); memset(&pfd, 0, sizeof (pfd)); pfd.fd = conn->socket_fd; pfd.events = POLLIN | POLLPRI; repoll: pfd.revents = 0; ret = poll(&pfd, 1, timeout); log_debug(7, "%s: Poll return %d\n", __FUNCTION__, ret); if (iscsi_timer_expired(&connection_timer)) { log_warning("Login response timeout. Waited %d " "seconds and did not get reponse PDU.\n", session->conn[0].active_timeout); c->ret = LOGIN_FAILED; return c->ret; } if (ret > 0) { if (pfd.revents & (POLLIN | POLLPRI)) { ret = iscsi_login_rsp(session, c); if (ret == -EAGAIN) goto repoll; if (status_class) *status_class = c->status_class; if (status_detail) *status_detail = c->status_detail; if (ret) return c->ret; } else if (pfd.revents & POLLHUP) { log_warning("Login POLLHUP"); c->ret = LOGIN_FAILED; return c->ret; } else if (pfd.revents & POLLNVAL) { log_warning("Login POLLNVAL"); c->ret = LOGIN_IO_ERROR; return c->ret; } else if (pfd.revents & POLLERR) { log_warning("Login POLLERR"); c->ret = LOGIN_IO_ERROR; return c->ret; } } else if (ret < 0) { log_error("Login poll error.\n"); c->ret = LOGIN_FAILED; return c->ret; } } while (conn->current_stage != ISCSI_FULL_FEATURE_PHASE); c->ret = LOGIN_OK; if (c->auth_client && acl_finish(c->auth_client) != AUTH_STATUS_NO_ERROR) { log_error("Login failed, error finishing c->auth_client"); if (c->ret == LOGIN_OK) c->ret = LOGIN_FAILED; } return c->ret; } open-iscsi-2.0.873/usr/md5.c000066400000000000000000000163041175631155400154220ustar00rootroot00000000000000/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' header * definitions; now uses stuff from dpkg's config.h. * - Ian Jackson . * Still in the public domain. */ #include "md5.h" #ifdef WORDS_BIGENDIAN void byteSwap(UWORD32 *buf, unsigned words) { md5byte *p = (md5byte *)buf; do { *buf++ = (UWORD32)((unsigned)p[3] << 8 | p[2]) << 16 | ((unsigned)p[1] << 8 | p[0]); p += 4; } while (--words); } #else #define byteSwap(buf,words) #endif /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bytes[0] = 0; ctx->bytes[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *ctx, md5byte const *buf, unsigned len) { UWORD32 t; /* Update byte count */ t = ctx->bytes[0]; if ((ctx->bytes[0] = t + len) < t) ctx->bytes[1]++; /* Carry from low to high */ t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ if (t > len) { memcpy((md5byte *)ctx->in + 64 - t, buf, len); return; } /* First chunk is an odd size */ memcpy((md5byte *)ctx->in + 64 - t, buf, t); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += t; len -= t; /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(md5byte digest[16], struct MD5Context *ctx) { int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */ md5byte *p = (md5byte *)ctx->in + count; /* Set the first char of padding to 0x80. There is always room. */ *p++ = 0x80; /* Bytes of padding needed to make 56 bytes (-8..55) */ count = 56 - 1 - count; if (count < 0) { /* Padding forces an extra block */ memset(p, 0, count + 8); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); p = (md5byte *)ctx->in; count = 56; } memset(p, 0, count); byteSwap(ctx->in, 14); /* Append length in bits and transform */ ctx->in[14] = ctx->bytes[0] << 3; ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29; MD5Transform(ctx->buf, ctx->in); byteSwap(ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f,w,x,y,z,in,s) \ (w += f(x,y,z) + in, w = (w<>(32-s)) + x) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void MD5Transform(UWORD32 buf[4], UWORD32 const in[16]) { register UWORD32 a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #endif open-iscsi-2.0.873/usr/md5.h000066400000000000000000000030461175631155400154260ustar00rootroot00000000000000/* * This is the header file for the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' * header definitions; now uses stuff from dpkg's config.h * - Ian Jackson . * Still in the public domain. */ #ifndef MD5_H #define MD5_H #include #include #include #include #if (__BYTE_ORDER == __BIG_ENDIAN) # define WORDS_BIGENDIAN 1 #endif typedef uint32_t UWORD32; #ifdef __cplusplus extern "C" { #endif #define md5byte unsigned char struct MD5Context { UWORD32 buf[4]; UWORD32 bytes[2]; UWORD32 in[16]; }; void MD5Init(struct MD5Context *context); void MD5Update(struct MD5Context *context, md5byte const *buf, unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *context); void MD5Transform(UWORD32 buf[4], UWORD32 const in[16]); #ifdef __cplusplus } #endif #endif /* !MD5_H */ open-iscsi-2.0.873/usr/mgmt_ipc.c000066400000000000000000000301551175631155400165340ustar00rootroot00000000000000/* * iSCSI Administrator Utility Socket Interface * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * Originally based on: * (C) 2004 FUJITA Tomonori * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include "iscsid.h" #include "idbm.h" #include "mgmt_ipc.h" #include "event_poll.h" #include "log.h" #include "transport.h" #include "sysdeps.h" #include "iscsi_ipc.h" #include "iscsi_err.h" #define PEERUSER_MAX 64 #define EXTMSG_MAX (64 * 1024) int mgmt_ipc_listen(void) { int fd, err; struct sockaddr_un addr; fd = socket(AF_LOCAL, SOCK_STREAM, 0); if (fd < 0) { log_error("Can not create IPC socket"); return fd; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_LOCAL; memcpy((char *) &addr.sun_path + 1, ISCSIADM_NAMESPACE, strlen(ISCSIADM_NAMESPACE)); if ((err = bind(fd, (struct sockaddr *) &addr, sizeof(addr))) < 0) { log_error("Can not bind IPC socket"); close(fd); return err; } if ((err = listen(fd, 32)) < 0) { log_error("Can not listen IPC socket"); close(fd); return err; } return fd; } void mgmt_ipc_close(int fd) { event_loop_exit(NULL); if (fd >= 0) close(fd); } static int mgmt_ipc_session_login(queue_task_t *qtask) { return session_login_task(&qtask->req.u.session.rec, qtask); } static int mgmt_ipc_session_getstats(queue_task_t *qtask) { int sid = qtask->req.u.session.sid; iscsi_session_t *session; int rc; if (!(session = session_find_by_sid(sid))) return ISCSI_ERR_SESS_NOT_FOUND; rc = ipc->get_stats(session->t->handle, session->id, session->conn[0].id, (void *)&qtask->rsp.u.getstats, MGMT_IPC_GETSTATS_BUF_MAX); if (rc) { log_error("get_stats(): IPC error %d " "session [%02d]", rc, sid); return ISCSI_ERR_INTERNAL; } mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); return ISCSI_SUCCESS; } static int mgmt_ipc_send_targets(queue_task_t *qtask) { iscsiadm_req_t *req = &qtask->req; int err; err = iscsi_host_send_targets(qtask, req->u.st.host_no, req->u.st.do_login, &req->u.st.ss); mgmt_ipc_write_rsp(qtask, err); return ISCSI_SUCCESS; } static int mgmt_ipc_session_logout(queue_task_t *qtask) { return session_logout_task(qtask->req.u.session.sid, qtask); } static int mgmt_ipc_session_sync(queue_task_t *qtask) { struct ipc_msg_session *session= &qtask->req.u.session; return iscsi_sync_session(&session->rec, qtask, session->sid); } static int mgmt_ipc_cfg_initiatorname(queue_task_t *qtask) { if (dconfig->initiator_name) strcpy(qtask->rsp.u.config.var, dconfig->initiator_name); mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); return ISCSI_SUCCESS; } static int mgmt_ipc_session_info(queue_task_t *qtask) { int sid = qtask->req.u.session.sid; iscsi_session_t *session; struct ipc_msg_session_state *info; if (!(session = session_find_by_sid(sid))) { log_debug(1, "session with sid %d not found!", sid); return ISCSI_ERR_SESS_NOT_FOUND; } info = &qtask->rsp.u.session_state; info->conn_state = session->conn[0].state; info->session_state = session->r_stage; mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); return ISCSI_SUCCESS; } static int mgmt_ipc_cfg_initiatoralias(queue_task_t *qtask) { strcpy(qtask->rsp.u.config.var, dconfig->initiator_alias); mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); return ISCSI_SUCCESS; } static int mgmt_ipc_cfg_filename(queue_task_t *qtask) { strcpy(qtask->rsp.u.config.var, dconfig->config_file); mgmt_ipc_write_rsp(qtask, ISCSI_SUCCESS); return ISCSI_SUCCESS; } static int mgmt_ipc_conn_add(queue_task_t *qtask) { return ISCSI_ERR; } static int mgmt_ipc_immediate_stop(queue_task_t *qtask) { event_loop_exit(qtask); return ISCSI_SUCCESS; } static int mgmt_ipc_conn_remove(queue_task_t *qtask) { return ISCSI_ERR; } /* * Parse a list of strings, encoded as a 32bit * length followed by the string itself (not necessarily * NUL-terminated). */ static int mgmt_ipc_parse_strings(queue_task_t *qtask, char ***result) { char *data, *endp, **argv = NULL; unsigned int left, argc; again: data = qtask->payload; left = qtask->req.payload_len; endp = NULL; argc = 0; while (left) { uint32_t len; if (left < 4) return -1; memcpy(&len, data, 4); data += 4; if (endp) *endp = '\0'; if (len > left) return -1; if (argv) { argv[argc] = (char *) data; endp = data + len; } data += len; argc++; } if (endp) *endp = '\0'; if (argv == NULL) { argv = malloc((argc + 1) * sizeof(char *)); *result = argv; goto again; } argv[argc] = NULL; return argc; } static int mgmt_ipc_notify_common(queue_task_t *qtask, int (*handler)(int, char **)) { char **argv = NULL; int argc, err = ISCSI_ERR; argc = mgmt_ipc_parse_strings(qtask, &argv); if (argc > 0) err = handler(argc, argv); if (argv) free(argv); mgmt_ipc_write_rsp(qtask, err); return ISCSI_SUCCESS; } /* Replace these dummies as you implement them elsewhere */ static int iscsi_discovery_add_node(int argc, char **argv) { return ISCSI_SUCCESS; } static int iscsi_discovery_del_node(int argc, char **argv) { return ISCSI_SUCCESS; } static int iscsi_discovery_add_portal(int argc, char **argv) { return ISCSI_SUCCESS; } static int iscsi_discovery_del_portal(int argc, char **argv) { return ISCSI_SUCCESS; } static int mgmt_ipc_notify_add_node(queue_task_t *qtask) { return mgmt_ipc_notify_common(qtask, iscsi_discovery_add_node); } static int mgmt_ipc_notify_del_node(queue_task_t *qtask) { return mgmt_ipc_notify_common(qtask, iscsi_discovery_del_node); } static int mgmt_ipc_notify_add_portal(queue_task_t *qtask) { return mgmt_ipc_notify_common(qtask, iscsi_discovery_add_portal); } static int mgmt_ipc_notify_del_portal(queue_task_t *qtask) { return mgmt_ipc_notify_common(qtask, iscsi_discovery_del_portal); } static int mgmt_peeruser(int sock, char *user) { #if defined(SO_PEERCRED) /* Linux style: use getsockopt(SO_PEERCRED) */ struct ucred peercred; socklen_t so_len = sizeof(peercred); struct passwd *pass; errno = 0; if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 || so_len != sizeof(peercred)) { /* We didn't get a valid credentials struct. */ log_error("peeruser_unux: error receiving credentials: %m"); return 0; } pass = getpwuid(peercred.uid); if (pass == NULL) { log_error("peeruser_unix: unknown local user with uid %d", (int) peercred.uid); return 0; } strlcpy(user, pass->pw_name, PEERUSER_MAX); return 1; #elif defined(SCM_CREDS) struct msghdr msg; typedef struct cmsgcred Cred; #define cruid cmcred_uid Cred *cred; /* Compute size without padding */ /* for NetBSD */ char cmsgmem[_ALIGN(sizeof(struct cmsghdr)) + _ALIGN(sizeof(Cred))]; /* Point to start of first structure */ struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem; struct iovec iov; char buf; struct passwd *pw; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (char *) cmsg; msg.msg_controllen = sizeof(cmsgmem); memset(cmsg, 0, sizeof(cmsgmem)); /* * The one character which is received here is not meaningful; its * purposes is only to make sure that recvmsg() blocks long enough for * the other side to send its credentials. */ iov.iov_base = &buf; iov.iov_len = 1; if (recvmsg(sock, &msg, 0) < 0 || cmsg->cmsg_len < sizeof(cmsgmem) || cmsg->cmsg_type != SCM_CREDS) { log_error("ident_unix: error receiving credentials: %m"); return 0; } cred = (Cred *) CMSG_DATA(cmsg); pw = getpwuid(cred->cruid); if (pw == NULL) { log_error("ident_unix: unknown local user with uid %d", (int) cred->cruid); return 0; } strlcpy(user, pw->pw_name, PEERUSER_MAX); return 1; #else log_error("'mgmg_ipc' auth is not supported on local connections " "on this platform"); return 0; #endif } static void mgmt_ipc_destroy_queue_task(queue_task_t *qtask) { if (qtask->mgmt_ipc_fd >= 0) close(qtask->mgmt_ipc_fd); if (qtask->payload) free(qtask->payload); if (qtask->allocated) free(qtask); } /* * Send the IPC response and destroy the queue_task. * The recovery code uses a qtask which is allocated as * part of a larger structure, and we don't want it to * get freed when we come here. This is what qtask->allocated * is for. */ void mgmt_ipc_write_rsp(queue_task_t *qtask, int err) { if (!qtask) return; log_debug(4, "%s: rsp to fd %d", __FUNCTION__, qtask->mgmt_ipc_fd); if (qtask->mgmt_ipc_fd < 0) { mgmt_ipc_destroy_queue_task(qtask); return; } qtask->rsp.err = err; if (write(qtask->mgmt_ipc_fd, &qtask->rsp, sizeof(qtask->rsp)) < 0) log_error("IPC qtask write failed: %s", strerror(errno)); close(qtask->mgmt_ipc_fd); mgmt_ipc_destroy_queue_task(qtask); } static int mgmt_ipc_read_data(int fd, void *ptr, size_t len) { int n; while (len) { n = read(fd, ptr, len); if (n < 0) { if (errno == EINTR) continue; return -EIO; } if (n == 0) { /* Client closed connection */ return -EIO; } ptr += n; len -= n; } return 0; } static int mgmt_ipc_read_req(queue_task_t *qtask) { iscsiadm_req_t *req = &qtask->req; int rc; rc = mgmt_ipc_read_data(qtask->mgmt_ipc_fd, req, sizeof(*req)); if (rc >= 0 && req->payload_len > 0) { /* Limit what we accept */ if (req->payload_len > EXTMSG_MAX) return -EIO; /* Remember the allocated pointer in the * qtask - it will be freed by write_rsp. * Note: we allocate one byte in excess * so we can append a NUL byte. */ qtask->payload = malloc(req->payload_len + 1); rc = mgmt_ipc_read_data(qtask->mgmt_ipc_fd, qtask->payload, req->payload_len); } return rc; } static mgmt_ipc_fn_t * mgmt_ipc_functions[__MGMT_IPC_MAX_COMMAND] = { [MGMT_IPC_SESSION_LOGIN] = mgmt_ipc_session_login, [MGMT_IPC_SESSION_LOGOUT] = mgmt_ipc_session_logout, [MGMT_IPC_SESSION_SYNC] = mgmt_ipc_session_sync, [MGMT_IPC_SESSION_STATS] = mgmt_ipc_session_getstats, [MGMT_IPC_SEND_TARGETS] = mgmt_ipc_send_targets, [MGMT_IPC_SESSION_INFO] = mgmt_ipc_session_info, [MGMT_IPC_CONN_ADD] = mgmt_ipc_conn_add, [MGMT_IPC_CONN_REMOVE] = mgmt_ipc_conn_remove, [MGMT_IPC_CONFIG_INAME] = mgmt_ipc_cfg_initiatorname, [MGMT_IPC_CONFIG_IALIAS] = mgmt_ipc_cfg_initiatoralias, [MGMT_IPC_CONFIG_FILE] = mgmt_ipc_cfg_filename, [MGMT_IPC_IMMEDIATE_STOP] = mgmt_ipc_immediate_stop, [MGMT_IPC_NOTIFY_ADD_NODE] = mgmt_ipc_notify_add_node, [MGMT_IPC_NOTIFY_DEL_NODE] = mgmt_ipc_notify_del_node, [MGMT_IPC_NOTIFY_ADD_PORTAL] = mgmt_ipc_notify_add_portal, [MGMT_IPC_NOTIFY_DEL_PORTAL] = mgmt_ipc_notify_del_portal, }; void mgmt_ipc_handle(int accept_fd) { unsigned int command; int fd, err; queue_task_t *qtask = NULL; mgmt_ipc_fn_t *handler = NULL; char user[PEERUSER_MAX]; qtask = calloc(1, sizeof(queue_task_t)); if (!qtask) return; if ((fd = accept(accept_fd, NULL, NULL)) < 0) { free(qtask); return; } qtask->allocated = 1; qtask->mgmt_ipc_fd = fd; if (!mgmt_peeruser(fd, user) || strncmp(user, "root", PEERUSER_MAX)) { err = ISCSI_ERR_ACCESS; goto err; } if (mgmt_ipc_read_req(qtask) < 0) { mgmt_ipc_destroy_queue_task(qtask); return; } command = qtask->req.command; qtask->rsp.command = command; if (0 <= command && command < __MGMT_IPC_MAX_COMMAND) handler = mgmt_ipc_functions[command]; if (handler != NULL) { /* If the handler returns OK, this means it * already sent the reply. */ err = handler(qtask); if (err == ISCSI_SUCCESS) return; } else { log_error("unknown request: %s(%d) %u", __FUNCTION__, __LINE__, command); err = ISCSI_ERR_INVALID_MGMT_REQ; } err: /* This will send the response, close the * connection and free the qtask */ mgmt_ipc_write_rsp(qtask, err); } open-iscsi-2.0.873/usr/mgmt_ipc.h000066400000000000000000000057151175631155400165450ustar00rootroot00000000000000/* * iSCSI Daemon/Admin Management IPC * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef MGMT_IPC_H #define MGMT_IPC_H #include "types.h" #include "iscsi_if.h" #include "config.h" #define ISCSIADM_NAMESPACE "ISCSIADM_ABSTRACT_NAMESPACE" #define PEERUSER_MAX 64 typedef enum iscsiadm_cmd { MGMT_IPC_UNKNOWN = 0, MGMT_IPC_SESSION_LOGIN = 1, MGMT_IPC_SESSION_LOGOUT = 2, MGMT_IPC_SESSION_ACTIVESTAT = 4, MGMT_IPC_CONN_ADD = 5, MGMT_IPC_CONN_REMOVE = 6, MGMT_IPC_SESSION_STATS = 7, MGMT_IPC_CONFIG_INAME = 8, MGMT_IPC_CONFIG_IALIAS = 9, MGMT_IPC_CONFIG_FILE = 10, MGMT_IPC_IMMEDIATE_STOP = 11, MGMT_IPC_SESSION_SYNC = 12, MGMT_IPC_SESSION_INFO = 13, MGMT_IPC_ISNS_DEV_ATTR_QUERY = 14, MGMT_IPC_SEND_TARGETS = 15, MGMT_IPC_NOTIFY_ADD_NODE = 16, MGMT_IPC_NOTIFY_DEL_NODE = 17, MGMT_IPC_NOTIFY_ADD_PORTAL = 18, MGMT_IPC_NOTIFY_DEL_PORTAL = 19, __MGMT_IPC_MAX_COMMAND } iscsiadm_cmd_e; /* IPC Request */ typedef struct iscsiadm_req { iscsiadm_cmd_e command; uint32_t payload_len; union { /* messages */ struct ipc_msg_session { int sid; node_rec_t rec; } session; struct ipc_msg_conn { int sid; int cid; } conn; struct ipc_msg_send_targets { int host_no; int do_login; struct sockaddr_storage ss; } st; struct ipc_msg_set_host_param { int host_no; int param; /* TODO: make this variable len to support */ char value[IFNAMSIZ + 1]; } set_host_param; } u; } iscsiadm_req_t; /* IPC Response */ typedef struct iscsiadm_rsp { iscsiadm_cmd_e command; int err; /* ISCSI_ERR value */ union { #define MGMT_IPC_GETSTATS_BUF_MAX (sizeof(struct iscsi_uevent) + \ sizeof(struct iscsi_stats) + \ sizeof(struct iscsi_stats_custom) * \ ISCSI_STATS_CUSTOM_MAX) struct ipc_msg_getstats { struct iscsi_uevent ev; struct iscsi_stats stats; char custom[sizeof(struct iscsi_stats_custom) * ISCSI_STATS_CUSTOM_MAX]; } getstats; struct ipc_msg_config { char var[VALUE_MAXLEN]; } config; struct ipc_msg_session_state { int session_state; int conn_state; } session_state; } u; } iscsiadm_rsp_t; struct queue_task; typedef int mgmt_ipc_fn_t(struct queue_task *); struct queue_task; void mgmt_ipc_write_rsp(struct queue_task *qtask, int err); int mgmt_ipc_listen(void); void mgmt_ipc_close(int fd); void mgmt_ipc_handle(int accept_fd); #endif /* MGMT_IPC_H */ open-iscsi-2.0.873/usr/netlink.c000066400000000000000000001065301175631155400164020ustar00rootroot00000000000000/* * iSCSI Netlink/Linux Interface * * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "types.h" #include "iscsi_if.h" #include "log.h" #include "iscsi_ipc.h" #include "initiator.h" #include "iscsi_sysfs.h" #include "transport.h" #include "iscsi_netlink.h" #include "iscsi_err.h" #include "iscsi_timer.h" static int ctrl_fd; static struct sockaddr_nl src_addr, dest_addr; static void *xmitbuf = NULL; static int xmitlen = 0; static void *recvbuf = NULL; static int recvlen = 0; static void *nlm_sendbuf; static void *nlm_recvbuf; static void *pdu_sendbuf; static void *setparam_buf; static struct iscsi_ipc_ev_clbk *ipc_ev_clbk; static int ctldev_handle(void); #define NLM_BUF_DEFAULT_MAX (NLMSG_SPACE(ISCSI_DEF_MAX_RECV_SEG_LEN + \ sizeof(struct iscsi_uevent) + \ sizeof(struct iscsi_hdr))) #define PDU_SENDBUF_DEFAULT_MAX (ISCSI_DEF_MAX_RECV_SEG_LEN + \ sizeof(struct iscsi_uevent) + \ sizeof(struct iscsi_hdr)) #define NLM_SETPARAM_DEFAULT_MAX (NI_MAXHOST + 1 + sizeof(struct iscsi_uevent)) struct iscsi_ping_event { uint32_t host_no; uint32_t pid; int32_t status; int active; }; struct iscsi_ping_event ping_event; struct nlattr *iscsi_nla_alloc(uint16_t type, uint16_t len) { struct nlattr *attr; attr = calloc(1, ISCSI_NLA_TOTAL_LEN(len)); if (!attr) return NULL; attr->nla_len = ISCSI_NLA_LEN(len); attr->nla_type = type; return attr; } static int kread(char *data, int count) { log_debug(7, "in %s %u %u %p %p", __FUNCTION__, recvlen, count, data, recvbuf); memcpy(data, recvbuf + recvlen, count); recvlen += count; return count; } static int nl_read(int ctrl_fd, char *data, int size, int flags) { int rc; struct iovec iov; struct msghdr msg; log_debug(7, "in %s", __FUNCTION__); iov.iov_base = data; iov.iov_len = size; memset(&msg, 0, sizeof(msg)); msg.msg_name= (void*)&src_addr; msg.msg_namelen = sizeof(src_addr); msg.msg_iov = &iov; msg.msg_iovlen = 1; rc = recvmsg(ctrl_fd, &msg, flags); return rc; } static int nlpayload_read(int ctrl_fd, char *data, int count, int flags) { int rc; struct iovec iov; struct msghdr msg; log_debug(7, "in %s", __FUNCTION__); iov.iov_base = nlm_recvbuf; iov.iov_len = NLMSG_SPACE(count); if (iov.iov_len > NLM_BUF_DEFAULT_MAX) { log_error("Cannot read %lu bytes. nlm_recvbuf too small.", iov.iov_len); return -1; } memset(iov.iov_base, 0, iov.iov_len); memset(&msg, 0, sizeof(msg)); msg.msg_name= (void*)&src_addr; msg.msg_namelen = sizeof(src_addr); msg.msg_iov = &iov; msg.msg_iovlen = 1; /* * Netlink recvmsg call path: * * - transport api callback * - iscsi_control_conn_error (should succeed) * - iscsi_unicast_skb (must succeed) * - netlink_unicast (must succeed) * - netlink_data_ready (must succeed) * - netlink_sendskb (must succeed) * - netlink_recvmsg (must succeed) * - sock_recvmsg (must succeed) * - sys_recvmsg (must succeed) * - sys_socketcall (must succeed) * - syscall_call (must succeed) * * Note1: "must succeed" means succeed unless bug in daemon. * It also means - no sleep and memory allocation on * the path. * * Note2: "should succeed" means will succeed in most of cases * because of mempool preallocation. * * FIXME: if "Note2" than interface should generate iSCSI error * level 0 on its own. Interface must always succeed on this. */ rc = recvmsg(ctrl_fd, &msg, flags); if (data) memcpy(data, NLMSG_DATA(iov.iov_base), count); return rc; } static int kwritev(enum iscsi_uevent_e type, struct iovec *iovp, int count) { int i, rc; struct nlmsghdr *nlh; struct msghdr msg; int datalen = 0; log_debug(7, "in %s", __FUNCTION__); for (i = 0; i < count; i++) { datalen += iovp[i].iov_len; } if (xmitbuf && type != ISCSI_UEVENT_SEND_PDU) { for (i = 0; i < count; i++) { memcpy(xmitbuf + xmitlen, iovp[i].iov_base, iovp[i].iov_len); xmitlen += iovp[i].iov_len; } return datalen; } nlh = nlm_sendbuf; memset(nlh, 0, NLMSG_SPACE(0)); datalen = 0; for (i = 1; i < count; i++) datalen += iovp[i].iov_len; nlh->nlmsg_len = datalen + sizeof(*nlh); nlh->nlmsg_pid = getpid(); nlh->nlmsg_flags = 0; nlh->nlmsg_type = type; iovp[0].iov_base = (void *)nlh; iovp[0].iov_len = sizeof(*nlh); memset(&msg, 0, sizeof(msg)); msg.msg_name= (void*)&dest_addr; msg.msg_namelen = sizeof(dest_addr); msg.msg_iov = iovp; msg.msg_iovlen = count; do { /* * Netlink down call path: * * - transport api call * - iscsi_if_recv_msg (must succeed) * - iscsi_if_rx (must succeed) * - netlink_data_ready (must succeed) * - netlink_sendskb (must succeed) * - netlink_sendmsg (alloc_skb() might fail) * - sock_sendmsg (must succeed) * - sys_sendmsg (must succeed) * - sys_socketcall (must succeed) * - syscall_call (must succeed) * * Note1: "must succeed" means succeed unless bug in daemon. * It also means - no sleep and memory allocation on * the path. * * Note2: netlink_sendmsg() might fail because of OOM. Since * we are in user-space, we will sleep until we succeed. */ rc = sendmsg(ctrl_fd, &msg, 0); if (rc == -ENOMEM) { log_debug(1, "sendmsg: alloc_skb() failed"); sleep(1); } else if (rc < 0) { log_error("sendmsg: bug? ctrl_fd %d", ctrl_fd); exit(rc); } } while (rc < 0); return rc; } /* * __kipc_call() should never block. Therefore * Netlink's xmit logic is serialized. This means we do not allocate on * xmit path. Instead we reuse nlm_sendbuf buffer. * * Transport must assure non-blocking operations for: * * - session_create() * - conn_create() * - conn_bind() * _ set_param() * - conn_start() * - conn_stop() * * Its OK to block for cleanup for short period of time in operatations for: * * - conn_destroy() * - session_destroy() * * FIXME: interface needs to be extended to allow longer blocking on * cleanup. (Dima) */ static int __kipc_call(struct iovec *iovp, int count) { int rc, iferr; struct iscsi_uevent *ev = iovp[1].iov_base; enum iscsi_uevent_e type = ev->type; log_debug(7, "in %s", __FUNCTION__); rc = kwritev(type, iovp, count); do { if ((rc = nlpayload_read(ctrl_fd, (void*)ev, sizeof(*ev), MSG_PEEK)) < 0) { return rc; } if (ev->type != type) { log_debug(1, "expecting event %d, got %d, handling...", type, ev->type); if (ev->type == ISCSI_KEVENT_IF_ERROR) { if ((rc = nlpayload_read(ctrl_fd, (void*)ev, sizeof(*ev), 0)) < 0) { return rc; } /* * iferror is u32, but the kernel returns * negative errno values for errors. */ iferr = ev->iferror; if (iferr == -ENOSYS) /* not fatal so let caller handle log */ log_debug(1, "Received iferror %d: %s.", iferr, strerror(-iferr)); else if (iferr < 0) log_error("Received iferror %d: %s.", iferr, strerror(-iferr)); else log_error("Received iferror %d.", iferr); return ev->iferror; } /* * receive and queue async. event which as of * today could be: * - CONN_ERROR * - RECV_PDU */ ctldev_handle(); } else if (ev->type == ISCSI_UEVENT_GET_STATS) { /* kget_stats() will read */ return 0; } else if (ev->type == ISCSI_UEVENT_GET_CHAP) { /* kget_chap() will read */ return 0; } else { if ((rc = nlpayload_read(ctrl_fd, (void*)ev, sizeof(*ev), 0)) < 0) { return rc; } break; } } while (ev->type != type); return rc; } static int ksendtargets(uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr) { int rc, addrlen; struct iscsi_uevent *ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX); ev = (struct iscsi_uevent *)setparam_buf; ev->type = ISCSI_UEVENT_TGT_DSCVR; ev->transport_handle = transport_handle; ev->u.tgt_dscvr.type = ISCSI_TGT_DSCVR_SEND_TARGETS; ev->u.tgt_dscvr.host_no = host_no; if (addr->sa_family == PF_INET) addrlen = sizeof(struct sockaddr_in); else if (addr->sa_family == PF_INET6) addrlen = sizeof(struct sockaddr_in6); else { log_error("%s unknown addr family %d\n", __FUNCTION__, addr->sa_family); return -EINVAL; } memcpy(setparam_buf + sizeof(*ev), addr, addrlen); iov[1].iov_base = ev; iov[1].iov_len = sizeof(*ev) + addrlen; rc = __kipc_call(iov, 2); if (rc < 0) { log_error("sendtargets failed rc%d\n", rc); return rc; } return 0; } static int kcreate_session(uint64_t transport_handle, uint64_t ep_handle, uint32_t initial_cmdsn, uint16_t cmds_max, uint16_t qdepth, uint32_t *out_sid, uint32_t *hostno) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); if (ep_handle == 0) { ev.type = ISCSI_UEVENT_CREATE_SESSION; ev.transport_handle = transport_handle; ev.u.c_session.initial_cmdsn = initial_cmdsn; ev.u.c_session.cmds_max = cmds_max; ev.u.c_session.queue_depth = qdepth; } else { ev.type = ISCSI_UEVENT_CREATE_BOUND_SESSION; ev.transport_handle = transport_handle; ev.u.c_bound_session.initial_cmdsn = initial_cmdsn; ev.u.c_bound_session.cmds_max = cmds_max; ev.u.c_bound_session.queue_depth = qdepth; ev.u.c_bound_session.ep_handle = ep_handle; } iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; *hostno = ev.r.c_session_ret.host_no; *out_sid = ev.r.c_session_ret.sid; return 0; } static int kdestroy_session(uint64_t transport_handle, uint32_t sid) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_DESTROY_SESSION; ev.transport_handle = transport_handle; ev.u.d_session.sid = sid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kunbind_session(uint64_t transport_handle, uint32_t sid) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_UNBIND_SESSION; ev.transport_handle = transport_handle; ev.u.d_session.sid = sid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kcreate_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid, uint32_t *out_cid) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_CREATE_CONN; ev.transport_handle = transport_handle; ev.u.c_conn.cid = cid; ev.u.c_conn.sid = sid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) { log_debug(7, "returned %d", rc); return rc; } if ((int)ev.r.c_conn_ret.cid == -1) return -EIO; *out_cid = ev.r.c_conn_ret.cid; return 0; } static int kdestroy_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_DESTROY_CONN; ev.transport_handle = transport_handle; ev.u.d_conn.sid = sid; ev.u.d_conn.cid = cid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kbind_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid, uint64_t transport_eph, int is_leading, int *retcode) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_BIND_CONN; ev.transport_handle = transport_handle; ev.u.b_conn.sid = sid; ev.u.b_conn.cid = cid; ev.u.b_conn.transport_eph = transport_eph; ev.u.b_conn.is_leading = is_leading; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; *retcode = ev.r.retcode; return 0; } static void ksend_pdu_begin(uint64_t transport_handle, uint32_t sid, uint32_t cid, int hdr_size, int data_size) { struct iscsi_uevent *ev; int total_xmitlen = sizeof(*ev) + hdr_size + data_size; log_debug(7, "in %s", __FUNCTION__); if (xmitbuf) { log_error("send's begin state machine bug?"); exit(-EIO); } if (total_xmitlen > PDU_SENDBUF_DEFAULT_MAX) { log_error("BUG: Cannot send %d bytes.", total_xmitlen); exit(-EINVAL); } xmitbuf = pdu_sendbuf; memset(xmitbuf, 0, total_xmitlen); xmitlen = sizeof(*ev); ev = xmitbuf; memset(ev, 0, sizeof(*ev)); ev->type = ISCSI_UEVENT_SEND_PDU; ev->transport_handle = transport_handle; ev->u.send_pdu.sid = sid; ev->u.send_pdu.cid = cid; ev->u.send_pdu.hdr_size = hdr_size; ev->u.send_pdu.data_size = data_size; log_debug(3, "send PDU began for hdr %d bytes and data %d bytes", hdr_size, data_size); } static int ksend_pdu_end(uint64_t transport_handle, uint32_t sid, uint32_t cid, int *retcode) { int rc; struct iscsi_uevent *ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); if (!xmitbuf) { log_error("send's end state machine bug?"); exit(-EIO); } ev = xmitbuf; if (ev->u.send_pdu.sid != sid || ev->u.send_pdu.cid != cid) { log_error("send's end state machine corruption?"); exit(-EIO); } iov[1].iov_base = xmitbuf; iov[1].iov_len = xmitlen; rc = __kipc_call(iov, 2); if (rc < 0) goto err; if (ev->r.retcode) { *retcode = ev->r.retcode; goto err; } if (ev->type != ISCSI_UEVENT_SEND_PDU) { log_error("bad event: bug on send_pdu_end?"); exit(-EIO); } log_debug(3, "send PDU finished for conn %d:%d", sid, cid); xmitbuf = NULL; return 0; err: xmitbuf = NULL; xmitlen = 0; return rc; } static int kset_host_param(uint64_t transport_handle, uint32_t host_no, enum iscsi_host_param param, void *value, int type) { struct iscsi_uevent *ev; char *param_str; int rc, len; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX); ev = (struct iscsi_uevent *)setparam_buf; ev->type = ISCSI_UEVENT_SET_HOST_PARAM; ev->transport_handle = transport_handle; ev->u.set_host_param.host_no = host_no; ev->u.set_host_param.param = param; param_str = setparam_buf + sizeof(*ev); switch (type) { case ISCSI_INT: sprintf(param_str, "%d", *((int *)value)); break; case ISCSI_STRING: if (!strlen(value)) return 0; sprintf(param_str, "%s", (char *)value); break; default: log_error("invalid type %d\n", type); return -EINVAL; } ev->u.set_host_param.len = len = strlen(param_str) + 1; iov[1].iov_base = ev; iov[1].iov_len = sizeof(*ev) + len; rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kset_param(uint64_t transport_handle, uint32_t sid, uint32_t cid, enum iscsi_param param, void *value, int type) { struct iscsi_uevent *ev; char *param_str; int rc, len; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX); ev = (struct iscsi_uevent *)setparam_buf; ev->type = ISCSI_UEVENT_SET_PARAM; ev->transport_handle = transport_handle; ev->u.set_param.sid = sid; ev->u.set_param.cid = cid; ev->u.set_param.param = param; param_str = setparam_buf + sizeof(*ev); switch (type) { case ISCSI_INT: sprintf(param_str, "%d", *((int *)value)); break; case ISCSI_STRING: if (!strlen(value)) return 0; sprintf(param_str, "%s", (char *)value); break; default: log_error("invalid type %d\n", type); return -EINVAL; } ev->u.set_param.len = len = strlen(param_str) + 1; iov[1].iov_base = ev; iov[1].iov_len = sizeof(*ev) + len; rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kstop_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid, int flag) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_STOP_CONN; ev.transport_handle = transport_handle; ev.u.stop_conn.sid = sid; ev.u.stop_conn.cid = cid; ev.u.stop_conn.flag = flag; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kstart_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid, int *retcode) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_START_CONN; ev.transport_handle = transport_handle; ev.u.start_conn.sid = sid; ev.u.start_conn.cid = cid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; *retcode = ev.r.retcode; return 0; } static int krecv_pdu_begin(struct iscsi_conn *conn) { int rc; log_debug(7, "in %s", __FUNCTION__); if (recvbuf) { log_error("recv's begin state machine bug?"); return -EIO; } if (!conn->recv_context) { rc = ipc->ctldev_handle(); if (rc == -ENXIO) /* event for some other conn */ return -EAGAIN; else if (rc < 0) /* fatal handling error or conn error */ return rc; /* * Session create/destroy event for another conn */ if (!conn->recv_context) return -EAGAIN; } recvbuf = conn->recv_context->data + sizeof(struct iscsi_uevent); recvlen = 0; log_debug(3, "recv PDU began, pdu handle %p", recvbuf); return 0; } static int krecv_pdu_end(struct iscsi_conn *conn) { log_debug(7, "in %s", __FUNCTION__); if (!recvbuf) { log_error("recv's end state machine bug?"); return -EIO; } log_debug(3, "recv PDU finished for pdu handle 0x%p", recvbuf); ipc_ev_clbk->put_ev_context(conn->recv_context); conn->recv_context = NULL; recvbuf = NULL; return 0; } int ktransport_ep_connect(iscsi_conn_t *conn, int non_blocking) { int rc, addrlen; struct iscsi_uevent *ev; struct sockaddr *dst_addr = (struct sockaddr *)&conn->saddr; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX); ev = (struct iscsi_uevent *)setparam_buf; ev->transport_handle = conn->session->t->handle; if (conn->bind_ep) { ev->type = ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST; ev->u.ep_connect_through_host.non_blocking = non_blocking; ev->u.ep_connect_through_host.host_no = conn->session->hostno; } else { ev->type = ISCSI_UEVENT_TRANSPORT_EP_CONNECT; ev->u.ep_connect.non_blocking = non_blocking; } if (dst_addr->sa_family == PF_INET) addrlen = sizeof(struct sockaddr_in); else if (dst_addr->sa_family == PF_INET6) addrlen = sizeof(struct sockaddr_in6); else { log_error("%s unknown addr family %d\n", __FUNCTION__, dst_addr->sa_family); return -EINVAL; } memcpy(setparam_buf + sizeof(*ev), dst_addr, addrlen); iov[1].iov_base = ev; iov[1].iov_len = sizeof(*ev) + addrlen; rc = __kipc_call(iov, 2); if (rc < 0) return rc; if (!ev->r.ep_connect_ret.handle) return -EIO; conn->transport_ep_handle = ev->r.ep_connect_ret.handle; log_debug(6, "%s got handle %llx", __FUNCTION__, (unsigned long long)conn->transport_ep_handle); return 0; } int ktransport_ep_poll(iscsi_conn_t *conn, int timeout_ms) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_TRANSPORT_EP_POLL; ev.transport_handle = conn->session->t->handle; ev.u.ep_poll.ep_handle = conn->transport_ep_handle; ev.u.ep_poll.timeout_ms = timeout_ms; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return ev.r.retcode; } void ktransport_ep_disconnect(iscsi_conn_t *conn) { int rc; struct iscsi_uevent ev; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); if (conn->transport_ep_handle == -1) return; memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT; ev.transport_handle = conn->session->t->handle; ev.u.ep_disconnect.ep_handle = conn->transport_ep_handle; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) { log_error("connnection %d:%d transport disconnect failed for " "ep %" PRIu64 " with error %d.", conn->session->id, conn->id, conn->transport_ep_handle, rc); } else conn->transport_ep_handle = -1; } static int kget_stats(uint64_t transport_handle, uint32_t sid, uint32_t cid, char *statsbuf, int statsbuf_max) { int rc; int ev_size; struct iscsi_uevent ev; char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))]; struct nlmsghdr *nlh; struct iovec iov[2]; log_debug(7, "in %s", __FUNCTION__); memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_GET_STATS; ev.transport_handle = transport_handle; ev.u.get_stats.sid = sid; ev.u.get_stats.cid = cid; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; if ((rc = nl_read(ctrl_fd, nlm_ev, NLMSG_SPACE(sizeof(struct iscsi_uevent)), MSG_PEEK)) < 0) { log_error("can not read nlm_ev, error %d", rc); return rc; } nlh = (struct nlmsghdr *)nlm_ev; ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr)); log_debug(6, "message real length is %d bytes", nlh->nlmsg_len); if (ev_size > statsbuf_max) { log_error("destanation buffer for statistics is " "not big enough to fit %d bytes", statsbuf_max); ev_size = statsbuf_max; } if ((rc = nlpayload_read(ctrl_fd, (void*)statsbuf, ev_size, 0)) < 0) { log_error("can not read from NL socket, error %d", rc); return rc; } return 0; } static int kset_net_config(uint64_t transport_handle, uint32_t host_no, struct iovec *iovs, uint32_t param_count) { struct iscsi_uevent ev; int rc, ev_len; struct iovec *iov = iovs + 1; log_debug(8, "in %s", __FUNCTION__); ev_len = sizeof(ev); ev.type = ISCSI_UEVENT_SET_IFACE_PARAMS; ev.transport_handle = transport_handle; ev.u.set_iface_params.host_no = host_no; /* first two iovs for nlmsg hdr and ev */ ev.u.set_iface_params.count = param_count - 2; iov->iov_base = &ev; iov->iov_len = ev_len; rc = __kipc_call(iovs, param_count); if (rc < 0) return rc; return 0; } static int krecv_conn_state(struct iscsi_conn *conn, uint32_t *state) { int rc; rc = ipc->ctldev_handle(); if (rc == -ENXIO) { /* event for some other conn */ rc = -EAGAIN; goto exit; } else if (rc < 0) /* fatal handling error or conn error */ goto exit; *state = *(enum iscsi_conn_state *)conn->recv_context->data; ipc_ev_clbk->put_ev_context(conn->recv_context); conn->recv_context = NULL; exit: return rc; } static int ksend_ping(uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr, uint32_t iface_num, uint32_t iface_type, uint32_t pid, uint32_t size) { int rc, addrlen; struct iscsi_uevent *ev; struct iovec iov[2]; log_debug(8, "in %s", __FUNCTION__); memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX); ev = (struct iscsi_uevent *)setparam_buf; ev->type = ISCSI_UEVENT_PING; ev->transport_handle = transport_handle; ev->u.iscsi_ping.host_no = host_no; ev->u.iscsi_ping.iface_num = iface_num; ev->u.iscsi_ping.iface_type = iface_type; ev->u.iscsi_ping.payload_size = size; ev->u.iscsi_ping.pid = pid; if (addr->sa_family == PF_INET) addrlen = sizeof(struct sockaddr_in); else if (addr->sa_family == PF_INET6) addrlen = sizeof(struct sockaddr_in6); else { log_error("%s unknown addr family %d\n", __FUNCTION__, addr->sa_family); return -EINVAL; } memcpy(setparam_buf + sizeof(*ev), addr, addrlen); iov[1].iov_base = ev; iov[1].iov_len = sizeof(*ev) + addrlen; rc = __kipc_call(iov, 2); if (rc < 0) return rc; return 0; } static int kexec_ping(uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr, uint32_t iface_num, uint32_t iface_type, uint32_t size, uint32_t *status) { struct pollfd pfd; struct timeval ping_timer; int timeout, fd, rc; uint32_t pid; *status = 0; fd = ipc->ctldev_open(); if (fd < 0) { log_error("Could not open netlink socket."); return ISCSI_ERR; } /* prepare to poll */ memset(&pfd, 0, sizeof(pfd)); pfd.fd = fd; pfd.events = POLLIN | POLLPRI; /* get unique ping id */ pid = rand(); rc = ksend_ping(transport_handle, host_no, addr, iface_num, iface_type, pid, size); if (rc != 0) { switch (rc) { case -ENOSYS: rc = ISCSI_ERR_OP_NOT_SUPP; break; case -EINVAL: rc = ISCSI_ERR_INVAL; break; default: rc = ISCSI_ERR; } goto close_nl; } ping_event.host_no = -1; ping_event.pid = -1; ping_event.status = -1; ping_event.active = -1; iscsi_timer_set(&ping_timer, 30); timeout = iscsi_timer_msecs_until(&ping_timer); while (1) { pfd.revents = 0; rc = poll(&pfd, 1, timeout); if (iscsi_timer_expired(&ping_timer)) { rc = ISCSI_ERR_TRANS_TIMEOUT; break; } if (rc > 0) { if (pfd.revents & (POLLIN | POLLPRI)) { timeout = iscsi_timer_msecs_until(&ping_timer); rc = ipc->ctldev_handle(); if (ping_event.active != 1) continue; if (pid != ping_event.pid) continue; rc = 0; *status = ping_event.status; break; } if (pfd.revents & POLLHUP) { rc = ISCSI_ERR_TRANS; break; } if (pfd.revents & POLLNVAL) { rc = ISCSI_ERR_INTERNAL; break; } if (pfd.revents & POLLERR) { rc = ISCSI_ERR_INTERNAL; break; } } else if (rc < 0) { rc = ISCSI_ERR_INTERNAL; break; } } close_nl: ipc->ctldev_close(); return rc; } static int kget_chap(uint64_t transport_handle, uint32_t host_no, uint16_t chap_tbl_idx, uint32_t num_entries, char *chap_buf, uint32_t *valid_chap_entries) { int rc = 0; int ev_size; struct iscsi_uevent ev; struct iovec iov[2]; char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))]; struct nlmsghdr *nlh; memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_GET_CHAP; ev.transport_handle = transport_handle; ev.u.get_chap.host_no = host_no; ev.u.get_chap.chap_tbl_idx = chap_tbl_idx; ev.u.get_chap.num_entries = num_entries; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; if ((rc = nl_read(ctrl_fd, nlm_ev, NLMSG_SPACE(sizeof(struct iscsi_uevent)), MSG_PEEK)) < 0) { log_error("can not read nlm_ev, error %d", rc); return rc; } nlh = (struct nlmsghdr *)nlm_ev; ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr)); if ((rc = nlpayload_read(ctrl_fd, (void *)chap_buf, ev_size, 0)) < 0) { log_error("can not read from NL socket, error %d", rc); return rc; } *valid_chap_entries = ev.u.get_chap.num_entries; return rc; } static int kdelete_chap(uint64_t transport_handle, uint32_t host_no, uint16_t chap_tbl_idx) { int rc = 0; struct iscsi_uevent ev; struct iovec iov[2]; memset(&ev, 0, sizeof(struct iscsi_uevent)); ev.type = ISCSI_UEVENT_DELETE_CHAP; ev.transport_handle = transport_handle; ev.u.delete_chap.host_no = host_no; ev.u.delete_chap.chap_tbl_idx = chap_tbl_idx; iov[1].iov_base = &ev; iov[1].iov_len = sizeof(ev); rc = __kipc_call(iov, 2); if (rc < 0) return rc; return rc; } static void drop_data(struct nlmsghdr *nlh) { int ev_size; ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr)); nlpayload_read(ctrl_fd, NULL, ev_size, 0); } static int ctldev_handle(void) { int rc, ev_size; struct iscsi_uevent *ev; iscsi_session_t *session = NULL; iscsi_conn_t *conn = NULL; char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))]; struct nlmsghdr *nlh; struct iscsi_ev_context *ev_context; uint32_t sid = 0, cid = 0; log_debug(7, "in %s", __FUNCTION__); if ((rc = nl_read(ctrl_fd, nlm_ev, NLMSG_SPACE(sizeof(struct iscsi_uevent)), MSG_PEEK)) < 0) { log_error("can not read nlm_ev, error %d", rc); return rc; } nlh = (struct nlmsghdr *)nlm_ev; ev = (struct iscsi_uevent *)NLMSG_DATA(nlm_ev); log_debug(7, "%s got event type %u\n", __FUNCTION__, ev->type); /* drivers like qla4xxx can be inserted after iscsid is started */ switch (ev->type) { case ISCSI_KEVENT_CREATE_SESSION: /* old kernels sent ISCSI_UEVENT_CREATE_SESSION on creation */ case ISCSI_UEVENT_CREATE_SESSION: drop_data(nlh); if (!ipc_ev_clbk) return 0; if (ipc_ev_clbk->create_session) ipc_ev_clbk->create_session(ev->r.c_session_ret.host_no, ev->r.c_session_ret.sid); return 0; case ISCSI_KEVENT_DESTROY_SESSION: if (!ipc_ev_clbk) return 0; drop_data(nlh); if (ipc_ev_clbk->destroy_session) ipc_ev_clbk->destroy_session(ev->r.d_session.host_no, ev->r.d_session.sid); return 0; case ISCSI_KEVENT_RECV_PDU: sid = ev->r.recv_req.sid; cid = ev->r.recv_req.cid; break; case ISCSI_KEVENT_CONN_ERROR: sid = ev->r.connerror.sid; cid = ev->r.connerror.cid; break; case ISCSI_KEVENT_CONN_LOGIN_STATE: sid = ev->r.conn_login.sid; cid = ev->r.conn_login.cid; break; case ISCSI_KEVENT_UNBIND_SESSION: sid = ev->r.unbind_session.sid; /* session wide event so cid is 0 */ cid = 0; break; case ISCSI_KEVENT_HOST_EVENT: switch (ev->r.host_event.code) { case ISCSI_EVENT_LINKUP: log_warning("Host%u: Link Up.\n", ev->r.host_event.host_no); break; case ISCSI_EVENT_LINKDOWN: log_warning("Host%u: Link Down.\n", ev->r.host_event.host_no); break; default: log_debug(7, "Host%u: Unknwon host event: %u.\n", ev->r.host_event.host_no, ev->r.host_event.code); } drop_data(nlh); return 0; case ISCSI_KEVENT_PING_COMP: ping_event.host_no = ev->r.ping_comp.host_no; ping_event.pid = ev->r.ping_comp.pid; ping_event.status = ev->r.ping_comp.status; ping_event.active = 1; drop_data(nlh); return 0; default: if ((ev->type > ISCSI_UEVENT_MAX && ev->type < KEVENT_BASE) || (ev->type > ISCSI_KEVENT_MAX)) log_error("Unknown kernel event %d. You may want to " " upgrade your iscsi tools.", ev->type); else /* * If another app is using the interface we might * see their * stuff. Just drop it. */ log_debug(7, "Got unknwon event %d. Dropping.", ev->type); drop_data(nlh); return 0; } /* verify connection */ session = session_find_by_sid(sid); if (!session) { /* * this can happen normally when other apps are using the * nl interface. */ log_debug(1, "Could not verify connection %d:%d. Dropping " "event.\n", sid, cid); drop_data(nlh); return -ENXIO; } conn = &session->conn[0]; ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr)); ev_context = ipc_ev_clbk->get_ev_context(conn, ev_size); if (!ev_context) { /* retry later */ log_error("Can not allocate memory for receive context."); return -ENOMEM; } log_debug(6, "message real length is %d bytes, recv_handle %p", nlh->nlmsg_len, ev_context->data); if ((rc = nlpayload_read(ctrl_fd, ev_context->data, ev_size, 0)) < 0) { ipc_ev_clbk->put_ev_context(ev_context); log_error("can not read from NL socket, error %d", rc); /* retry later */ return rc; } /* * we sched these events because the handlers could call back * into ctldev_handle */ switch (ev->type) { case ISCSI_KEVENT_RECV_PDU: rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0, EV_CONN_RECV_PDU); break; case ISCSI_KEVENT_CONN_ERROR: memcpy(ev_context->data, &ev->r.connerror.error, sizeof(ev->r.connerror.error)); rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0, EV_CONN_ERROR); break; case ISCSI_KEVENT_CONN_LOGIN_STATE: memcpy(ev_context->data, &ev->r.conn_login.state, sizeof(ev->r.conn_login.state)); rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0, EV_CONN_LOGIN); break; case ISCSI_KEVENT_UNBIND_SESSION: rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0, EV_CONN_STOP); break; default: ipc_ev_clbk->put_ev_context(ev_context); log_error("unknown kernel event %d", ev->type); return -EEXIST; } if (rc) ipc_ev_clbk->put_ev_context(ev_context); return rc; } static int ctldev_open(void) { log_debug(7, "in %s", __FUNCTION__); nlm_sendbuf = calloc(1, NLM_BUF_DEFAULT_MAX); if (!nlm_sendbuf) { log_error("can not allocate nlm_sendbuf"); return -1; } nlm_recvbuf = calloc(1, NLM_BUF_DEFAULT_MAX); if (!nlm_recvbuf) { log_error("can not allocate nlm_recvbuf"); goto free_nlm_sendbuf; } pdu_sendbuf = calloc(1, PDU_SENDBUF_DEFAULT_MAX); if (!pdu_sendbuf) { log_error("can not allocate nlm_sendbuf"); goto free_nlm_recvbuf; } setparam_buf = calloc(1, NLM_SETPARAM_DEFAULT_MAX); if (!setparam_buf) { log_error("can not allocate setparam_buf"); goto free_pdu_sendbuf; } ctrl_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ISCSI); if (ctrl_fd < 0) { log_error("can not create NETLINK_ISCSI socket"); goto free_setparam_buf; } memset(&src_addr, 0, sizeof(src_addr)); src_addr.nl_family = AF_NETLINK; src_addr.nl_pid = getpid(); src_addr.nl_groups = 1; if (bind(ctrl_fd, (struct sockaddr *)&src_addr, sizeof(src_addr))) { log_error("can not bind NETLINK_ISCSI socket"); goto close_socket; } memset(&dest_addr, 0, sizeof(dest_addr)); dest_addr.nl_family = AF_NETLINK; dest_addr.nl_pid = 0; /* kernel */ dest_addr.nl_groups = 0; /* unicast */ log_debug(7, "created NETLINK_ISCSI socket..."); return ctrl_fd; close_socket: close(ctrl_fd); free_setparam_buf: free(setparam_buf); free_pdu_sendbuf: free(pdu_sendbuf); free_nlm_recvbuf: free(nlm_recvbuf); free_nlm_sendbuf: free(nlm_sendbuf); return -1; } static void ctldev_close(void) { log_debug(7, "in %s", __FUNCTION__); if (ctrl_fd >= 0) close(ctrl_fd); free(setparam_buf); free(pdu_sendbuf); free(nlm_recvbuf); free(nlm_sendbuf); } struct iscsi_ipc nl_ipc = { .name = "Open-iSCSI Kernel IPC/NETLINK v.1", .ctldev_bufmax = NLM_BUF_DEFAULT_MAX, .ctldev_open = ctldev_open, .ctldev_close = ctldev_close, .ctldev_handle = ctldev_handle, .sendtargets = ksendtargets, .create_session = kcreate_session, .destroy_session = kdestroy_session, .unbind_session = kunbind_session, .create_conn = kcreate_conn, .destroy_conn = kdestroy_conn, .bind_conn = kbind_conn, .set_param = kset_param, .set_host_param = kset_host_param, .get_param = NULL, .start_conn = kstart_conn, .stop_conn = kstop_conn, .get_stats = kget_stats, .writev = kwritev, .send_pdu_begin = ksend_pdu_begin, .send_pdu_end = ksend_pdu_end, .read = kread, .recv_pdu_begin = krecv_pdu_begin, .recv_pdu_end = krecv_pdu_end, .set_net_config = kset_net_config, .recv_conn_state = krecv_conn_state, .exec_ping = kexec_ping, .get_chap = kget_chap, .delete_chap = kdelete_chap, }; struct iscsi_ipc *ipc = &nl_ipc; void ipc_register_ev_callback(struct iscsi_ipc_ev_clbk *ev_clbk) { ipc_ev_clbk = ev_clbk; } open-iscsi-2.0.873/usr/scsi.c000066400000000000000000000044271175631155400157010ustar00rootroot00000000000000/* * The following is from the linux kernel scsi_error.c * * scsi_error.c Copyright (C) 1997 Eric Youngdale * * SCSI error/timeout handling * Initial versions: Eric Youngdale. Based upon conversations with * Leonard Zubkoff and David Miller at Linux Expo, * ideas originating from all over the place. * * Restructured scsi_unjam_host and associated functions. * September 04, 2002 Mike Anderson (andmike@us.ibm.com) * * Forward port of Russell King's (rmk@arm.linux.org.uk) changes and * minor cleanups. * September 30, 2002 Mike Anderson (andmike@us.ibm.com) */ #include #include "scsi.h" /** * scsi_normalize_sense - normalize main elements from either fixed or * descriptor sense data format into a common format. * * @sense_buffer: byte array containing sense data returned by device * @sb_len: number of valid bytes in sense_buffer * @sshdr: pointer to instance of structure that common * elements are written to. * * Notes: * The "main elements" from sense data are: response_code, sense_key, * asc, ascq and additional_length (only for descriptor format). * * Typically this function can be called after a device has * responded to a SCSI command with the CHECK_CONDITION status. * * Return value: * 1 if valid sense data information found, else 0; **/ int scsi_normalize_sense(const uint8_t *sense_buffer, int sb_len, struct scsi_sense_hdr *sshdr) { if (!sense_buffer || !sb_len) return 0; memset(sshdr, 0, sizeof(struct scsi_sense_hdr)); sshdr->response_code = (sense_buffer[0] & 0x7f); if (!scsi_sense_valid(sshdr)) return 0; if (sshdr->response_code >= 0x72) { /* * descriptor format */ if (sb_len > 1) sshdr->sense_key = (sense_buffer[1] & 0xf); if (sb_len > 2) sshdr->asc = sense_buffer[2]; if (sb_len > 3) sshdr->ascq = sense_buffer[3]; if (sb_len > 7) sshdr->additional_length = sense_buffer[7]; } else { /* * fixed format */ if (sb_len > 2) sshdr->sense_key = (sense_buffer[2] & 0xf); if (sb_len > 7) { sb_len = (sb_len < (sense_buffer[7] + 8)) ? sb_len : (sense_buffer[7] + 8); if (sb_len > 12) sshdr->asc = sense_buffer[12]; if (sb_len > 13) sshdr->ascq = sense_buffer[13]; } } return 1; } open-iscsi-2.0.873/usr/scsi.h000066400000000000000000000020771175631155400157050ustar00rootroot00000000000000/* * this is from the linux kernel scsi_eh.h */ #ifndef _SCSI_SCSI_H #define _SCSI_SCSI_H #include /* * This is a slightly modified SCSI sense "descriptor" format header. * The addition is to allow the 0x70 and 0x71 response codes. The idea * is to place the salient data from either "fixed" or "descriptor" sense * format into one structure to ease application processing. * * The original sense buffer should be kept around for those cases * in which more information is required (e.g. the LBA of a MEDIUM ERROR). */ struct scsi_sense_hdr { /* See SPC-3 section 4.5 */ uint8_t response_code; /* permit: 0x0, 0x70, 0x71, 0x72, 0x73 */ uint8_t sense_key; uint8_t asc; uint8_t ascq; uint8_t byte4; uint8_t byte5; uint8_t byte6; uint8_t additional_length; /* always 0 for fixed sense format */ }; static inline int scsi_sense_valid(struct scsi_sense_hdr *sshdr) { if (!sshdr) return 0; return (sshdr->response_code & 0x70) == 0x70; } extern int scsi_normalize_sense(const uint8_t *sense_buffer, int sb_len, struct scsi_sense_hdr *sshdr); #endif open-iscsi-2.0.873/usr/session_info.c000066400000000000000000000274221175631155400174360ustar00rootroot00000000000000#include #include #include #include "list.h" #include "log.h" #include "iscsi_sysfs.h" #include "version.h" #include "iscsi_settings.h" #include "mgmt_ipc.h" #include "session_info.h" #include "transport.h" #include "initiator.h" #include "iface.h" #include "iscsid_req.h" #include "iscsi_err.h" int session_info_create_list(void *data, struct session_info *info) { struct session_link_info *link_info = data; struct list_head *list = link_info->list; struct session_info *new, *curr, *match = NULL; if (link_info->match_fn && !link_info->match_fn(link_info->data, info)) return -1; new = calloc(1, sizeof(*new)); if (!new) return ISCSI_ERR_NOMEM; memcpy(new, info, sizeof(*new)); INIT_LIST_HEAD(&new->list); if (list_empty(list)) { list_add_tail(&new->list, list); return 0; } list_for_each_entry(curr, list, list) { if (!strcmp(curr->targetname, info->targetname)) { match = curr; if (!strcmp(curr->address, info->address)) { match = curr; if (curr->port == info->port) { match = curr; break; } } } } list_add_tail(&new->list, match ? match->list.next : list); return 0; } void session_info_free_list(struct list_head *list) { struct session_info *curr, *tmp; list_for_each_entry_safe(curr, tmp, list, list) { list_del(&curr->list); free(curr); } } static int session_info_print_flat(void *data, struct session_info *info) { struct iscsi_transport *t = iscsi_sysfs_get_transport_by_sid(info->sid); if (strchr(info->persistent_address, '.')) printf("%s: [%d] %s:%d,%d %s\n", t ? t->name : UNKNOWN_VALUE, info->sid, info->persistent_address, info->persistent_port, info->tpgt, info->targetname); else printf("%s: [%d] [%s]:%d,%d %s\n", t ? t->name : UNKNOWN_VALUE, info->sid, info->persistent_address, info->persistent_port, info->tpgt, info->targetname); return 0; } static int print_iscsi_state(int sid, char *prefix) { iscsiadm_req_t req; iscsiadm_rsp_t rsp; int err; char *state = NULL; char state_buff[SCSI_MAX_STATE_VALUE]; static char *conn_state[] = { "FREE", "TRANSPORT WAIT", "IN LOGIN", "LOGGED IN", "IN LOGOUT", "LOGOUT REQUESTED", "CLEANUP WAIT", }; static char *session_state[] = { "NO CHANGE", "CLEANUP", "REOPEN", "REDIRECT", }; memset(&req, 0, sizeof(iscsiadm_req_t)); req.command = MGMT_IPC_SESSION_INFO; req.u.session.sid = sid; err = iscsid_exec_req(&req, &rsp, 1); /* * for drivers like qla4xxx, iscsid does not display * anything here since it does not know about it. */ if (!err && rsp.u.session_state.conn_state >= 0 && rsp.u.session_state.conn_state <= ISCSI_CONN_STATE_CLEANUP_WAIT) state = conn_state[rsp.u.session_state.conn_state]; printf("%s\t\tiSCSI Connection State: %s\n", prefix, state ? state : "Unknown"); state = NULL; memset(state_buff, 0, SCSI_MAX_STATE_VALUE); if (!iscsi_sysfs_get_session_state(state_buff, sid)) printf("%s\t\tiSCSI Session State: %s\n", prefix, state_buff); else printf("%s\t\tiSCSI Session State: Unknown\n", prefix); if (!err && rsp.u.session_state.session_state >= 0 && rsp.u.session_state.session_state <= R_STAGE_SESSION_REDIRECT) state = session_state[rsp.u.session_state.session_state]; printf("%s\t\tInternal iscsid Session State: %s\n", prefix, state ? state : "Unknown"); return 0; } static void print_iscsi_params(int sid, char *prefix) { struct iscsi_session_operational_config session_conf; struct iscsi_conn_operational_config conn_conf; iscsi_sysfs_get_negotiated_session_conf(sid, &session_conf); iscsi_sysfs_get_negotiated_conn_conf(sid, &conn_conf); printf("%s\t\t************************\n", prefix); printf("%s\t\tNegotiated iSCSI params:\n", prefix); printf("%s\t\t************************\n", prefix); if (is_valid_operational_value(conn_conf.HeaderDigest)) printf("%s\t\tHeaderDigest: %s\n", prefix, conn_conf.HeaderDigest ? "CRC32C" : "None"); if (is_valid_operational_value(conn_conf.DataDigest)) printf("%s\t\tDataDigest: %s\n", prefix, conn_conf.DataDigest ? "CRC32C" : "None"); if (is_valid_operational_value(conn_conf.MaxRecvDataSegmentLength)) printf("%s\t\tMaxRecvDataSegmentLength: %d\n", prefix, conn_conf.MaxRecvDataSegmentLength); if (is_valid_operational_value(conn_conf.MaxXmitDataSegmentLength)) printf("%s\t\tMaxXmitDataSegmentLength: %d\n", prefix, conn_conf.MaxXmitDataSegmentLength); if (is_valid_operational_value(session_conf.FirstBurstLength)) printf("%s\t\tFirstBurstLength: %d\n", prefix, session_conf.FirstBurstLength); if (is_valid_operational_value(session_conf.MaxBurstLength)) printf("%s\t\tMaxBurstLength: %d\n", prefix, session_conf.MaxBurstLength); if (is_valid_operational_value(session_conf.ImmediateData)) printf("%s\t\tImmediateData: %s\n", prefix, session_conf.ImmediateData ? "Yes" : "No"); if (is_valid_operational_value(session_conf.InitialR2T)) printf("%s\t\tInitialR2T: %s\n", prefix, session_conf.InitialR2T ? "Yes" : "No"); if (is_valid_operational_value(session_conf.MaxOutstandingR2T)) printf("%s\t\tMaxOutstandingR2T: %d\n", prefix, session_conf.MaxOutstandingR2T); } static void print_scsi_device_info(void *data, int host_no, int target, int lun) { char *prefix = data; char *blockdev, state[SCSI_MAX_STATE_VALUE]; printf("%s\t\tscsi%d Channel 00 Id %d Lun: %d\n", prefix, host_no, target, lun); blockdev = iscsi_sysfs_get_blockdev_from_lun(host_no, target, lun); if (blockdev) { printf("%s\t\t\tAttached scsi disk %s\t\t", prefix, blockdev); free(blockdev); if (!iscsi_sysfs_get_device_state(state, host_no, target, lun)) printf("State: %s\n", state); else printf("State: Unknown\n"); } } static int print_scsi_state(int sid, char *prefix, unsigned int flags) { int host_no = -1, err = 0; char state[SCSI_MAX_STATE_VALUE]; printf("%s\t\t************************\n", prefix); printf("%s\t\tAttached SCSI devices:\n", prefix); printf("%s\t\t************************\n", prefix); host_no = iscsi_sysfs_get_host_no_from_sid(sid, &err); if (err) { printf("%s\t\tUnavailable\n", prefix); return err; } if (flags & SESSION_INFO_HOST_DEVS) { printf("%s\t\tHost Number: %d\t", prefix, host_no); if (!iscsi_sysfs_get_host_state(state, host_no)) printf("State: %s\n", state); else printf("State: Unknown\n"); } if (flags & SESSION_INFO_SCSI_DEVS) iscsi_sysfs_for_each_device(prefix, host_no, sid, print_scsi_device_info); return 0; } void session_info_print_tree(struct list_head *list, char *prefix, unsigned int flags, int do_show) { struct session_info *curr, *prev = NULL; list_for_each_entry(curr, list, list) { if (!prev || strcmp(prev->targetname, curr->targetname)) { printf("%sTarget: %s\n", prefix, curr->targetname); prev = NULL; } if (!prev || (strcmp(prev->address, curr->address) || prev->port != curr->port)) { if (strchr(curr->address, '.')) printf("%s\tCurrent Portal: %s:%d,%d\n", prefix, curr->address, curr->port, curr->tpgt); else printf("%s\tCurrent Portal: [%s]:%d,%d\n", prefix, curr->address, curr->port, curr->tpgt); if (strchr(curr->persistent_address, '.')) printf("%s\tPersistent Portal: %s:%d,%d\n", prefix, curr->persistent_address, curr->persistent_port, curr->tpgt); else printf("%s\tPersistent Portal: [%s]:%d,%d\n", prefix, curr->persistent_address, curr->persistent_port, curr->tpgt); } else printf("\n"); if (flags & SESSION_INFO_IFACE) { char *new_prefix; printf("%s\t\t**********\n", prefix); printf("%s\t\tInterface:\n", prefix); printf("%s\t\t**********\n", prefix); new_prefix = calloc(1, 1 + strlen(prefix) + strlen("\t\t")); if (!new_prefix) printf("Could not print interface info. " "Out of Memory.\n"); else { sprintf(new_prefix, "%s%s", prefix, "\t\t"); iface_print(&curr->iface, new_prefix); } } if (flags & SESSION_INFO_ISCSI_STATE) { printf("%s\t\tSID: %d\n", prefix, curr->sid); print_iscsi_state(curr->sid, prefix); } if (flags & SESSION_INFO_ISCSI_TIM) { printf("%s\t\t*********\n", prefix); printf("%s\t\tTimeouts:\n", prefix); printf("%s\t\t*********\n", prefix); printf("%s\t\tRecovery Timeout: %d\n", prefix, ((curr->tmo).recovery_tmo)); if ((curr->tmo).tgt_reset_tmo >= 0) printf("%s\t\tTarget Reset Timeout: %d\n", prefix, ((curr->tmo).tgt_reset_tmo)); else printf("%s\t\tTarget Reset Timeout: %s\n", prefix, UNKNOWN_VALUE); if ((curr->tmo).lu_reset_tmo >= 0) printf("%s\t\tLUN Reset Timeout: %d\n", prefix, ((curr->tmo).lu_reset_tmo)); else printf("%s\t\tLUN Reset Timeout: %s\n", prefix, UNKNOWN_VALUE); if ((curr->tmo).lu_reset_tmo >= 0) printf("%s\t\tAbort Timeout: %d\n", prefix, ((curr->tmo).abort_tmo)); else printf("%s\t\tAbort Timeout: %s\n", prefix, UNKNOWN_VALUE); } if (flags & SESSION_INFO_ISCSI_AUTH) { printf("%s\t\t*****\n", prefix); printf("%s\t\tCHAP:\n", prefix); printf("%s\t\t*****\n", prefix); if (!do_show) { strcpy(curr->chap.password, "********"); strcpy(curr->chap.password_in, "********"); } if (strlen((curr->chap).username)) printf("%s\t\tusername: %s\n", prefix, (curr->chap).username); else printf("%s\t\tusername: %s\n", prefix, UNKNOWN_VALUE); if (strlen((curr->chap).password)) printf("%s\t\tpassword: %s\n", prefix, (curr->chap).password); else printf("%s\t\tpassword: %s\n", prefix, UNKNOWN_VALUE); if (strlen((curr->chap).username_in)) printf("%s\t\tusername_in: %s\n", prefix, (curr->chap).username_in); else printf("%s\t\tusername_in: %s\n", prefix, UNKNOWN_VALUE); if (strlen((curr->chap).password_in)) printf("%s\t\tpassword_in: %s\n", prefix, (curr->chap).password_in); else printf("%s\t\tpassword_in: %s\n", prefix, UNKNOWN_VALUE); } if (flags & SESSION_INFO_ISCSI_PARAMS) print_iscsi_params(curr->sid, prefix); if (flags & (SESSION_INFO_SCSI_DEVS | SESSION_INFO_HOST_DEVS)) print_scsi_state(curr->sid, prefix, flags); prev = curr; } } int session_info_print(int info_level, struct session_info *info, int do_show) { struct list_head list; int num_found = 0, err = 0; char *version; unsigned int flags = 0; switch (info_level) { case 0: case -1: if (info) { session_info_print_flat(NULL, info); num_found = 1; } else err = iscsi_sysfs_for_each_session(info, &num_found, session_info_print_flat); break; case 3: version = iscsi_sysfs_get_iscsi_kernel_version(); if (version) { printf("iSCSI Transport Class version %s\n", version); printf("version %s\n", ISCSI_VERSION_STR); } flags |= (SESSION_INFO_SCSI_DEVS | SESSION_INFO_HOST_DEVS); /* fall through */ case 2: flags |= (SESSION_INFO_ISCSI_PARAMS | SESSION_INFO_ISCSI_TIM | SESSION_INFO_ISCSI_AUTH); /* fall through */ case 1: INIT_LIST_HEAD(&list); struct session_link_info link_info; flags |= (SESSION_INFO_ISCSI_STATE | SESSION_INFO_IFACE); if (info) { INIT_LIST_HEAD(&info->list); list_add_tail(&list, &info->list); session_info_print_tree(&list, "", flags, do_show); num_found = 1; break; } memset(&link_info, 0, sizeof(link_info)); link_info.list = &list; link_info.data = NULL; link_info.match_fn = NULL; err = iscsi_sysfs_for_each_session(&link_info, &num_found, session_info_create_list); if (err || !num_found) break; session_info_print_tree(&list, "", flags, do_show); session_info_free_list(&list); break; default: log_error("Invalid info level %d. Try 0 - 3.", info_level); return ISCSI_ERR_INVAL; } if (err) { log_error("Can not get list of active sessions (%d)", err); return err; } else if (!num_found) { log_error("No active sessions."); return ISCSI_ERR_NO_OBJS_FOUND; } return 0; } open-iscsi-2.0.873/usr/session_info.h000066400000000000000000000030661175631155400174410ustar00rootroot00000000000000#ifndef SESSION_INFO_H #define SESSION_INFO_H #include #include "sysfs.h" #include "types.h" #include "iscsi_proto.h" #include "config.h" struct list; struct session_timeout { int abort_tmo; int lu_reset_tmo; int recovery_tmo; int tgt_reset_tmo; }; struct session_CHAP { char username[AUTH_STR_MAX_LEN]; char password[AUTH_STR_MAX_LEN]; char username_in[AUTH_STR_MAX_LEN]; char password_in[AUTH_STR_MAX_LEN]; }; struct session_info { struct list_head list; /* local info */ struct iface_rec iface; int sid; struct session_timeout tmo; struct session_CHAP chap; /* remote info */ char targetname[TARGET_NAME_MAXLEN + 1]; int tpgt; char address[NI_MAXHOST + 1]; int port; char persistent_address[NI_MAXHOST + 1]; int persistent_port; }; typedef int (session_match_info_fn_t)(void *data, struct session_info *info); struct session_link_info { struct list_head *list; session_match_info_fn_t *match_fn; void *data; }; #define SESSION_INFO_IFACE 0x1 #define SESSION_INFO_ISCSI_PARAMS 0x2 #define SESSION_INFO_ISCSI_STATE 0x4 #define SESSION_INFO_SCSI_DEVS 0x8 #define SESSION_INFO_HOST_DEVS 0x10 #define SESSION_INFO_ISCSI_TIM 0x20 #define SESSION_INFO_ISCSI_AUTH 0x40 extern int session_info_create_list(void *data, struct session_info *info); extern void session_info_free_list(struct list_head *list); extern int session_info_print(int info_level, struct session_info *match_info, int do_show); extern void session_info_print_tree(struct list_head *list, char *prefix, unsigned int flags, int do_show); #endif open-iscsi-2.0.873/usr/session_mgmt.c000066400000000000000000000301221175631155400174360ustar00rootroot00000000000000/* * iSCSI session management helpers * * Copyright (C) 2010 Mike Christie * Copyright (C) 2010 Red Hat, Inc. All rights reserved. * Copyright (C) 2011 Dell Inc. * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include "idbm.h" #include "list.h" #include "iscsi_util.h" #include "mgmt_ipc.h" #include "session_info.h" #include "iscsi_sysfs.h" #include "log.h" #include "iscsid_req.h" #include "iscsi_err.h" static void log_login_msg(struct node_rec *rec, int rc) { if (rc) { log_error("Could not login to [iface: %s, target: %s, " "portal: %s,%d].", rec->iface.name, rec->name, rec->conn[0].address, rec->conn[0].port); iscsi_err_print_msg(rc); } else log_info("Login to [iface: %s, target: %s, portal: " "%s,%d] successful.", rec->iface.name, rec->name, rec->conn[0].address, rec->conn[0].port); } struct iscsid_async_req { struct list_head list; void *data; int fd; }; /** * iscsid_reqs_close - close open async requests * @list: list of async reqs * * This just closes the socket to the daemon. */ static void iscsid_reqs_close(struct list_head *list) { struct iscsid_async_req *tmp, *curr; list_for_each_entry_safe(curr, tmp, list, list) { close(curr->fd); list_del(&curr->list); free(curr); } } static int iscsid_login_reqs_wait(struct list_head *list) { struct iscsid_async_req *tmp, *curr; struct node_rec *rec; int ret = 0; list_for_each_entry_safe(curr, tmp, list, list) { int err; rec = curr->data; err = iscsid_req_wait(MGMT_IPC_SESSION_LOGIN, curr->fd); if (err && !ret) ret = err; log_login_msg(rec, err); list_del(&curr->list); free(curr); } return ret; } /** * __iscsi_login_portal - request iscsid to login to portal * @data: If set, copies the session.multiple value to the portal record * so it is propagated to iscsid. * @list: If async, list to add session to * @rec: portal rec to log into */ static int __iscsi_login_portal(void *data, struct list_head *list, struct node_rec *rec) { struct iscsid_async_req *async_req = NULL; int rc = 0, fd; if (data && !rec->session.multiple) { struct node_rec *pattern_rec = data; rec->session.multiple = pattern_rec->session.multiple; } log_info("Logging in to [iface: %s, target: %s, portal: %s,%d]%s", rec->iface.name, rec->name, rec->conn[0].address, rec->conn[0].port, (rec->session.multiple ? " (multiple)" : "")); if (list) { async_req = calloc(1, sizeof(*async_req)); if (!async_req) log_info("Could not allocate memory for async login " "handling. Using sequential login instead."); else INIT_LIST_HEAD(&async_req->list); } if (async_req) rc = iscsid_req_by_rec_async(MGMT_IPC_SESSION_LOGIN, rec, &fd); else rc = iscsid_req_by_rec(MGMT_IPC_SESSION_LOGIN, rec); if (rc) { log_login_msg(rec, rc); if (async_req) free(async_req); return rc; } if (async_req) { list_add_tail(&async_req->list, list); async_req->fd = fd; async_req->data = rec; } else log_login_msg(rec, rc); return 0; } /** * iscsi_login_portal - request iscsid to login to portal multiple * times, based on the session.nr_sessions in the portal record. * @data: If set, session.multiple will cause an additional session to * be created regardless of the value of session.nr_sessions * @list: If async, list to add session to * @rec: portal rec to log into */ int iscsi_login_portal(void *data, struct list_head *list, struct node_rec *rec) { struct node_rec *pattern_rec = data; int rc = 0, session_count = 0, i; /* * If pattern_rec->session.multiple is set, just add a single new * session by passing things along to __iscsi_login_portal */ if (pattern_rec && pattern_rec->session.multiple) return __iscsi_login_portal(data, list, rec); /* * Count the current number of sessions, and only create those * that are missing. */ rc = iscsi_sysfs_for_each_session(rec, &session_count, iscsi_match_session_count); if (rc) { log_error("Could not count current number of sessions"); goto done; } if (session_count >= rec->session.nr_sessions) { log_debug(1, "%s: %d session%s requested, but %d " "already present.", rec->iface.name, rec->session.nr_sessions, rec->session.nr_sessions == 1 ? "" : "s", session_count); rc = 0; goto done; } /* * Ensure the record's 'multiple' flag is set so __iscsi_login_portal * will allow multiple logins. */ rec->session.multiple = 1; for (i = session_count; i < rec->session.nr_sessions; ++i) { log_debug(1, "%s: Creating session %d/%d", rec->iface.name, i + 1, rec->session.nr_sessions); int err = __iscsi_login_portal(pattern_rec, list, rec); if (err && !rc) rc = err; } done: return rc; } /** * iscsi_login_portal_nowait - request iscsid to login to portal * @rec: portal rec to log into * * This sends the login request, but does not wait for the result. */ int iscsi_login_portal_nowait(struct node_rec *rec) { struct list_head list; int err; INIT_LIST_HEAD(&list); err = iscsi_login_portal(NULL, &list, rec); if (err > 0) return err; iscsid_reqs_close(&list); return 0; } /** * __iscsi_login_portals - login into portals on @rec_list, * @data: data to pass to login_fn * @nr_found: returned with number of portals logged into * @wait: bool indicating if the fn should wait for the result * @rec_list: list of portals to log into * @clear_list: If set, delete and free rec_list after iterating through. * @login_fn: list iter function * * This will loop over the list of portals and login. It * will attempt to login asynchronously, and then wait for * them to complete if wait is set. */ static int __iscsi_login_portals(void *data, int *nr_found, int wait, struct list_head *rec_list, int clear_list, int (*login_fn)(void *, struct list_head *, struct node_rec *)) { struct node_rec *curr_rec, *tmp; struct list_head login_list; int ret = 0, err; *nr_found = 0; INIT_LIST_HEAD(&login_list); list_for_each_entry(curr_rec, rec_list, list) { err = login_fn(data, &login_list, curr_rec); if (err > 0 && !ret) ret = err; if (!err) (*nr_found)++; } if (wait) { err = iscsid_login_reqs_wait(&login_list); if (err && !ret) ret = err; } else iscsid_reqs_close(&login_list); if (clear_list) { list_for_each_entry_safe(curr_rec, tmp, rec_list, list) { list_del(&curr_rec->list); free(curr_rec); } } return ret; } /** * iscsi_login_portals - login into portals on @rec_list, * @data: data to pass to login_fn * @nr_found: returned with number of portals logged into * @wait: bool indicating if the fn should wait for the result * @rec_list: list of portals to log into. This list is deleted after * iterating through it. * @login_fn: list iter function * * This will loop over the list of portals and login. It * will attempt to login asynchronously, and then wait for * them to complete if wait is set. */ int iscsi_login_portals(void *data, int *nr_found, int wait, struct list_head *rec_list, int (*login_fn)(void *, struct list_head *, struct node_rec *)) { return __iscsi_login_portals(data, nr_found, wait, rec_list, 1, login_fn); } /** * iscsi_login_portals_safe - login into portals on @rec_list, but do not * clear out rec_list. */ int iscsi_login_portals_safe(void *data, int *nr_found, int wait, struct list_head *rec_list, int (*login_fn)(void *, struct list_head *, struct node_rec *)) { return __iscsi_login_portals(data, nr_found, wait, rec_list, 0, login_fn); } static void log_logout_msg(struct session_info *info, int rc) { if (rc) { log_error("Could not logout of [sid: %d, target: %s, " "portal: %s,%d].", info->sid, info->targetname, info->persistent_address, info->port); iscsi_err_print_msg(rc); } else log_info("Logout of [sid: %d, target: %s, " "portal: %s,%d] successful.", info->sid, info->targetname, info->persistent_address, info->port); } static int iscsid_logout_reqs_wait(struct list_head *list) { struct iscsid_async_req *tmp, *curr; struct session_info *info; int ret = 0; list_for_each_entry_safe(curr, tmp, list, list) { int err; info = curr->data; err = iscsid_req_wait(MGMT_IPC_SESSION_LOGOUT, curr->fd); log_logout_msg(info, err); if (err) ret = err; list_del(&curr->list); free(curr); } return ret; } /** * iscsi_logout_portal - logou tof portal * @info: session to log out of * @list: if async, this is the list to add the logout req to */ int iscsi_logout_portal(struct session_info *info, struct list_head *list) { struct iscsid_async_req *async_req = NULL; int fd, rc; /* TODO: add fn to add session prefix info like dev_printk */ log_info("Logging out of session [sid: %d, target: %s, portal: " "%s,%d]", info->sid, info->targetname, info->persistent_address, info->port); if (list) { async_req = calloc(1, sizeof(*async_req)); if (!async_req) log_info("Could not allocate memory for async logout " "handling. Using sequential logout instead."); } if (!async_req) rc = iscsid_req_by_sid(MGMT_IPC_SESSION_LOGOUT, info->sid); else { INIT_LIST_HEAD(&async_req->list); rc = iscsid_req_by_sid_async(MGMT_IPC_SESSION_LOGOUT, info->sid, &fd); } /* we raced with another app or instance of iscsiadm */ if (rc) { log_logout_msg(info, rc); if (async_req) free(async_req); return rc; } if (async_req) { list_add_tail(&async_req->list, list); async_req->fd = fd; async_req->data = info; } else log_logout_msg(info, rc); return 0; } /** * iscsi_logout_portals - logout portals * @data: data to pass to iter logout_fn * @nr_found: number of sessions logged out * @wait: bool indicating if the fn should wait for the result * @logout_fn: logout iter function * * This will loop over the list of sessions and run the logout fn * on them. It will attempt to logout asynchronously, and then wait for * them to complete if wait is set. */ int iscsi_logout_portals(void *data, int *nr_found, int wait, int (*logout_fn)(void *, struct list_head *, struct session_info *)) { struct session_info *curr_info; struct session_link_info link_info; struct list_head session_list, logout_list; int ret = 0, err; INIT_LIST_HEAD(&session_list); INIT_LIST_HEAD(&logout_list); memset(&link_info, 0, sizeof(link_info)); link_info.list = &session_list; link_info.data = NULL; link_info.match_fn = NULL; *nr_found = 0; err = iscsi_sysfs_for_each_session(&link_info, nr_found, session_info_create_list); if (err && !list_empty(&session_list)) log_error("Could not read in all sessions: %s", iscsi_err_to_str(err)); else if (err && list_empty(&session_list)) { log_error("Could not read session info."); return err; } else if (list_empty(&session_list)) return ISCSI_ERR_NO_OBJS_FOUND; ret = err; *nr_found = 0; list_for_each_entry(curr_info, &session_list, list) { err = logout_fn(data, &logout_list, curr_info); if (err > 0 && !ret) ret = err; if (!err) (*nr_found)++; } if (!*nr_found) { ret = ISCSI_ERR_NO_OBJS_FOUND; goto free_list; } if (wait) { err = iscsid_logout_reqs_wait(&logout_list); if (err && !ret) ret = err; } else iscsid_reqs_close(&logout_list); if (ret) log_error("Could not logout of all requested sessions"); free_list: session_info_free_list(&session_list); return ret; } /* TODO merge with initiator.c implementation */ /* And add locking */ int iscsi_check_for_running_session(struct node_rec *rec) { int nr_found = 0; if (iscsi_sysfs_for_each_session(rec, &nr_found, iscsi_match_session)) return 1; return 0; } open-iscsi-2.0.873/usr/session_mgmt.h000066400000000000000000000017021175631155400174450ustar00rootroot00000000000000#ifndef _SESSION_MGMT_H_ #define _SESSION_MGMT_H_ struct node_rec; struct list_head; struct session_info; extern int iscsi_login_portal(void *data, struct list_head *list, struct node_rec *rec); extern int iscsi_login_portal_nowait(struct node_rec *rec); extern int iscsi_login_portals(void *data, int *nr_found, int wait, struct list_head *rec_list, int (*login_fn)(void *, struct list_head *, struct node_rec *)); extern int iscsi_login_portals_safe(void *data, int *nr_found, int wait, struct list_head *rec_list, int (*login_fn)(void *, struct list_head *, struct node_rec *)); extern int iscsi_logout_portal(struct session_info *info, struct list_head *list); extern int iscsi_logout_portals(void *data, int *nr_found, int wait, int (*logout_fn)(void *, struct list_head *, struct session_info *)); extern int iscsi_check_for_running_session(struct node_rec *rec); #endif open-iscsi-2.0.873/usr/sha1.c000066400000000000000000000125571175631155400155770ustar00rootroot00000000000000/* * Cryptographic API. * * SHA1 Secure Hash Algorithm. * * Derived from cryptoapi implementation, adapted for in-place * scatterlist interface. Originally based on the public domain * implementation written by Steve Reid. * * Copyright (c) Alan Smithee. * Copyright (c) Andrew McDonald * Copyright (c) Jean-Francois Dive * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include "sha1.h" #define SHA1_DIGEST_SIZE 20 #define SHA1_HMAC_BLOCK_SIZE 64 static inline uint32_t rol(uint32_t value, uint32_t bits) { return (((value) << (bits)) | ((value) >> (32 - (bits)))); } /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ # define blk0(i) block32[i] #define blk(i) (block32[i&15] = rol(block32[(i+13)&15]^block32[(i+8)&15] \ ^block32[(i+2)&15]^block32[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5); \ w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5); \ w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5); \ w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); /* Hash a single 512-bit block. This is the core of the algorithm. */ static void sha1_transform(uint32_t *state, const uint8_t *in) { uint32_t a, b, c, d, e; uint32_t block32[16]; /* convert/copy data to workspace */ for (a = 0; a < sizeof(block32)/sizeof(uint32_t); a++) block32[a] = ntohl (((const uint32_t *)in)[a]); /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; memset (block32, 0x00, sizeof block32); } void sha1_init(void *ctx) { struct sha1_ctx *sctx = ctx; static const struct sha1_ctx initstate = { 0, { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }, { 0, } }; *sctx = initstate; } void sha1_update(void *ctx, const uint8_t *data, unsigned int len) { struct sha1_ctx *sctx = ctx; unsigned int i, j; j = (sctx->count >> 3) & 0x3f; sctx->count += len << 3; if ((j + len) > 63) { memcpy(&sctx->buffer[j], data, (i = 64-j)); sha1_transform(sctx->state, sctx->buffer); for ( ; i + 63 < len; i += 64) { sha1_transform(sctx->state, &data[i]); } j = 0; } else i = 0; memcpy(&sctx->buffer[j], &data[i], len - i); } /* Add padding and return the message digest. */ void sha1_final(void* ctx, uint8_t *out) { struct sha1_ctx *sctx = ctx; uint32_t i, j, index, padlen; uint64_t t; uint8_t bits[8] = { 0, }; static const uint8_t padding[64] = { 0x80, }; t = sctx->count; bits[7] = 0xff & t; t>>=8; bits[6] = 0xff & t; t>>=8; bits[5] = 0xff & t; t>>=8; bits[4] = 0xff & t; t>>=8; bits[3] = 0xff & t; t>>=8; bits[2] = 0xff & t; t>>=8; bits[1] = 0xff & t; t>>=8; bits[0] = 0xff & t; /* Pad out to 56 mod 64 */ index = (sctx->count >> 3) & 0x3f; padlen = (index < 56) ? (56 - index) : ((64+56) - index); sha1_update(sctx, padding, padlen); /* Append length */ sha1_update(sctx, bits, sizeof bits); /* Store state in digest */ for (i = j = 0; i < 5; i++, j += 4) { uint32_t t2 = sctx->state[i]; out[j+3] = t2 & 0xff; t2>>=8; out[j+2] = t2 & 0xff; t2>>=8; out[j+1] = t2 & 0xff; t2>>=8; out[j ] = t2 & 0xff; } /* Wipe context */ memset(sctx, 0, sizeof *sctx); } open-iscsi-2.0.873/usr/sha1.h000066400000000000000000000011631175631155400155730ustar00rootroot00000000000000/* * sha1.h - SHA1 Secure Hash Algorithm used for CHAP authentication. * copied from the Linux kernel's Cryptographic API and slightly adjusted to * fit IET's needs * * This file is (c) 2004 Xiranet Communications GmbH * and licensed under the GPL. */ #ifndef SHA1_H #define SHA1_H #include #include #include "types.h" struct sha1_ctx { uint64_t count; uint32_t state[5]; uint8_t buffer[64]; }; void sha1_init(void *ctx); void sha1_update(void *ctx, const uint8_t *data, unsigned int len); void sha1_final(void* ctx, uint8_t *out); #endif open-iscsi-2.0.873/usr/statics.c000066400000000000000000000004001175631155400163750ustar00rootroot00000000000000#include #include #include #include static struct passwd root_pw = { .pw_name = "root", }; struct passwd* getpwuid(uid_t uid) { if (uid == 0) return &root_pw; else { errno = ENOENT; return 0; } } open-iscsi-2.0.873/usr/strings.c000066400000000000000000000070321175631155400164240ustar00rootroot00000000000000/* * Copyright (C) 2002 Cisco Systems, Inc. * maintained by linux-iscsi-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #include #include #include #include #include #include #include #include "strings.h" #include "log.h" int str_init_buffer(struct str_buffer *s, size_t initial_allocation) { if (s) { memset(s, 0, sizeof (*s)); s->buffer = NULL; if (initial_allocation) { s->buffer = malloc(initial_allocation); if (s->buffer) { s->allocated_length = initial_allocation; memset(s->buffer, 0, initial_allocation); } } s->data_length = 0; return 1; } return 0; } struct str_buffer *str_alloc_buffer(size_t initial_allocation) { struct str_buffer *s = calloc(1, sizeof (*s)); if (s) str_init_buffer(s, initial_allocation); return s; } void str_free_buffer(struct str_buffer *s) { if (s) { if (s->buffer) { free(s->buffer); s->buffer = NULL; } s->allocated_length = 0; s->data_length = 0; } } int str_enlarge_data(struct str_buffer *s, int length) { void *new_buf; if (s) { s->data_length += length; if (s->data_length > s->allocated_length) { log_debug(7, "enlarge buffer from %lu to %lu\n", s->allocated_length, s->data_length); new_buf = realloc(s->buffer, s->data_length); if (!new_buf) { /* too big */ log_error("enlarged buffer %p to %d data " "bytes, with only %d bytes of buffer " "space", s, (int)s->data_length, (int)s->allocated_length); return ENOMEM; } s->buffer = new_buf; memset(s->buffer + s->allocated_length, 0, s->data_length - s->allocated_length); s->allocated_length = s->data_length; } } return 0; } void str_remove_initial(struct str_buffer *s, int length) { char *remaining; int amount; if (s && length) { remaining = s->buffer + length; amount = s->data_length - length; if (amount < 0) amount = 0; if (amount) memmove(s->buffer, remaining, amount); s->data_length = amount; s->buffer[amount] = '\0'; } } /* truncate the data length down */ void str_truncate_buffer(struct str_buffer *s, size_t length) { if (s) { if (!s->data_length) return; if (length <= s->data_length) { s->data_length = length; s->buffer[s->data_length] = '\0'; } else if (length <= s->allocated_length) { /* clear the data, and declare the * data length to be larger */ memset(s->buffer + s->data_length, 0, length - s->data_length); s->data_length = length; } else { log_error( "couldn't truncate data buffer to length %d, " "only allocated %d", (int)length, (int)s->allocated_length); } } } char *str_buffer_data(struct str_buffer *s) { if (s) return s->buffer; else return NULL; } size_t str_data_length(struct str_buffer * s) { if (s) return s->data_length; else return 0; } size_t str_unused_length(struct str_buffer * s) { if (s) return s->allocated_length - s->data_length; else return 0; } open-iscsi-2.0.873/usr/strings.h000066400000000000000000000027011175631155400164270ustar00rootroot00000000000000/* * iSCSI variable-sized string buffers * * Copyright (C) 2002 Cisco Systems, Inc. * maintained by linux-iscsi-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. */ #ifndef STRINGS_H #define STRINGS_H struct str_buffer { size_t allocated_length; size_t data_length; /* not including the trailing NUL */ char *buffer; }; extern int str_init_buffer(struct str_buffer *s, size_t initial_allocation); extern struct str_buffer *str_alloc_buffer(size_t initial_allocation); extern void str_free_buffer(struct str_buffer *s); extern int str_enlarge_data(struct str_buffer *s, int length); extern void str_remove_initial(struct str_buffer *s, int length); extern void str_truncate_buffer(struct str_buffer *s, size_t length); extern char *str_buffer_data(struct str_buffer *s); extern size_t str_data_length(struct str_buffer *s); extern size_t str_unused_length(struct str_buffer *s); #endif /* STRINGS_H */ open-iscsi-2.0.873/usr/sysfs.c000066400000000000000000000455201175631155400161060ustar00rootroot00000000000000/* * This is from udev-121's udev_sysfs.c * * Copyright (C) 2005-2006 Kay Sievers * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "sysdeps.h" #include "sysfs.h" /* * We take this file from udev so we want to make as few changes are possible, * so we can maintain patches. * * This is from udev_utils_string.c */ static void remove_trailing_chars(char *path, char c) { size_t len; len = strlen(path); while (len > 0 && path[len-1] == c) path[--len] = '\0'; } /* this converts udevs logging to ours. */ #define dbg(format, arg...) \ do { \ log_debug(3, "%s: " format, __FUNCTION__,## arg); \ } while (0) /* * Begin udev_sysfs.c code */ char sysfs_path[PATH_SIZE]; /* device cache */ static LIST_HEAD(dev_list); /* attribute value cache */ static LIST_HEAD(attr_list); struct sysfs_attr { struct list_head node; char path[PATH_SIZE]; char *value; /* points to value_local if value is cached */ char value_local[NAME_SIZE]; }; int sysfs_init(void) { const char *env; env = getenv("SYSFS_PATH"); if (env) { strlcpy(sysfs_path, env, sizeof(sysfs_path)); remove_trailing_chars(sysfs_path, '/'); } else strlcpy(sysfs_path, "/sys", sizeof(sysfs_path)); dbg("sysfs_path='%s'\n", sysfs_path); INIT_LIST_HEAD(&dev_list); INIT_LIST_HEAD(&attr_list); return 0; } void sysfs_cleanup(void) { struct sysfs_attr *attr_loop; struct sysfs_attr *attr_temp; struct sysfs_device *dev_loop; struct sysfs_device *dev_temp; list_for_each_entry_safe(attr_loop, attr_temp, &attr_list, node) { list_del_init(&attr_loop->node); free(attr_loop); } list_for_each_entry_safe(dev_loop, dev_temp, &dev_list, node) { list_del_init(&dev_loop->node); free(dev_loop); } } void sysfs_device_set_values(struct sysfs_device *dev, const char *devpath, const char *subsystem, const char *driver) { char *pos; strlcpy(dev->devpath, devpath, sizeof(dev->devpath)); if (subsystem != NULL) strlcpy(dev->subsystem, subsystem, sizeof(dev->subsystem)); if (driver != NULL) strlcpy(dev->driver, driver, sizeof(dev->driver)); /* set kernel name */ pos = strrchr(dev->devpath, '/'); if (pos == NULL) return; strlcpy(dev->kernel, &pos[1], sizeof(dev->kernel)); dbg("kernel='%s'\n", dev->kernel); /* some devices have '!' in their name, change that to '/' */ pos = dev->kernel; while (pos[0] != '\0') { if (pos[0] == '!') pos[0] = '/'; pos++; } /* get kernel number */ pos = &dev->kernel[strlen(dev->kernel)]; while (isdigit(pos[-1])) pos--; strlcpy(dev->kernel_number, pos, sizeof(dev->kernel_number)); dbg("kernel_number='%s'\n", dev->kernel_number); } int sysfs_resolve_link(char *devpath, size_t size) { char link_path[PATH_SIZE]; char link_target[PATH_SIZE]; int len; int i; int back; strlcpy(link_path, sysfs_path, sizeof(link_path)); strlcat(link_path, devpath, sizeof(link_path)); len = readlink(link_path, link_target, sizeof(link_target)); if (len <= 0) return -1; link_target[len] = '\0'; dbg("path link '%s' points to '%s'\n", devpath, link_target); for (back = 0; strncmp(&link_target[back * 3], "../", 3) == 0; back++) ; dbg("base '%s', tail '%s', back %i\n", devpath, &link_target[back * 3], back); for (i = 0; i <= back; i++) { char *pos = strrchr(devpath, '/'); if (pos == NULL) return -1; pos[0] = '\0'; } dbg("after moving back '%s'\n", devpath); strlcat(devpath, "/", size); strlcat(devpath, &link_target[back * 3], size); return 0; } struct sysfs_device *sysfs_device_get(const char *devpath) { char path[PATH_SIZE]; char devpath_real[PATH_SIZE]; struct sysfs_device *dev; struct sysfs_device *dev_loop; struct stat statbuf; char link_path[PATH_SIZE]; char link_target[PATH_SIZE]; int len; char *pos; /* we handle only these devpathes */ if (devpath != NULL && strncmp(devpath, "/devices/", 9) != 0 && strncmp(devpath, "/subsystem/", 11) != 0 && strncmp(devpath, "/module/", 8) != 0 && strncmp(devpath, "/bus/", 5) != 0 && strncmp(devpath, "/class/", 7) != 0 && strncmp(devpath, "/block/", 7) != 0) return NULL; dbg("open '%s'\n", devpath); strlcpy(devpath_real, devpath, sizeof(devpath_real)); remove_trailing_chars(devpath_real, '/'); if (devpath[0] == '\0' ) return NULL; /* look for device already in cache (we never put an untranslated path in the cache) */ list_for_each_entry(dev_loop, &dev_list, node) { if (strcmp(dev_loop->devpath, devpath_real) == 0) { dbg("found in cache '%s'\n", dev_loop->devpath); return dev_loop; } } /* if we got a link, resolve it to the real device */ strlcpy(path, sysfs_path, sizeof(path)); strlcat(path, devpath_real, sizeof(path)); if (lstat(path, &statbuf) != 0) { dbg("stat '%s' failed: %s\n", path, strerror(errno)); return NULL; } if (S_ISLNK(statbuf.st_mode)) { if (sysfs_resolve_link(devpath_real, sizeof(devpath_real)) != 0) return NULL; /* now look for device in cache after path translation */ list_for_each_entry(dev_loop, &dev_list, node) { if (strcmp(dev_loop->devpath, devpath_real) == 0) { dbg("found in cache '%s'\n", dev_loop->devpath); return dev_loop; } } } /* it is a new device */ dbg("new uncached device '%s'\n", devpath_real); dev = malloc(sizeof(struct sysfs_device)); if (dev == NULL) return NULL; memset(dev, 0x00, sizeof(struct sysfs_device)); sysfs_device_set_values(dev, devpath_real, NULL, NULL); /* get subsystem name */ strlcpy(link_path, sysfs_path, sizeof(link_path)); strlcat(link_path, dev->devpath, sizeof(link_path)); strlcat(link_path, "/subsystem", sizeof(link_path)); len = readlink(link_path, link_target, sizeof(link_target)); if (len > 0) { /* get subsystem from "subsystem" link */ link_target[len] = '\0'; dbg("subsystem link '%s' points to '%s'\n", link_path, link_target); pos = strrchr(link_target, '/'); if (pos != NULL) strlcpy(dev->subsystem, &pos[1], sizeof(dev->subsystem)); } else if (strstr(dev->devpath, "/drivers/") != NULL) { strlcpy(dev->subsystem, "drivers", sizeof(dev->subsystem)); } else if (strncmp(dev->devpath, "/module/", 8) == 0) { strlcpy(dev->subsystem, "module", sizeof(dev->subsystem)); } else if (strncmp(dev->devpath, "/subsystem/", 11) == 0) { pos = strrchr(dev->devpath, '/'); if (pos == &dev->devpath[10]) strlcpy(dev->subsystem, "subsystem", sizeof(dev->subsystem)); } else if (strncmp(dev->devpath, "/class/", 7) == 0) { pos = strrchr(dev->devpath, '/'); if (pos == &dev->devpath[6]) strlcpy(dev->subsystem, "subsystem", sizeof(dev->subsystem)); } else if (strncmp(dev->devpath, "/bus/", 5) == 0) { pos = strrchr(dev->devpath, '/'); if (pos == &dev->devpath[4]) strlcpy(dev->subsystem, "subsystem", sizeof(dev->subsystem)); } /* get driver name */ strlcpy(link_path, sysfs_path, sizeof(link_path)); strlcat(link_path, dev->devpath, sizeof(link_path)); strlcat(link_path, "/driver", sizeof(link_path)); len = readlink(link_path, link_target, sizeof(link_target)); if (len > 0) { link_target[len] = '\0'; dbg("driver link '%s' points to '%s'\n", link_path, link_target); pos = strrchr(link_target, '/'); if (pos != NULL) strlcpy(dev->driver, &pos[1], sizeof(dev->driver)); } dbg("add to cache 'devpath=%s', subsystem='%s', driver='%s'\n", dev->devpath, dev->subsystem, dev->driver); list_add(&dev->node, &dev_list); return dev; } struct sysfs_device *sysfs_device_get_parent(struct sysfs_device *dev) { char parent_devpath[PATH_SIZE]; char *pos; dbg("open '%s'\n", dev->devpath); /* look if we already know the parent */ if (dev->parent != NULL) return dev->parent; strlcpy(parent_devpath, dev->devpath, sizeof(parent_devpath)); dbg("'%s'\n", parent_devpath); /* strip last element */ pos = strrchr(parent_devpath, '/'); if (pos == NULL || pos == parent_devpath) return NULL; pos[0] = '\0'; if (strncmp(parent_devpath, "/class", 6) == 0) { pos = strrchr(parent_devpath, '/'); if (pos == &parent_devpath[6] || pos == parent_devpath) { dbg("/class top level, look for device link\n"); goto device_link; } } if (strcmp(parent_devpath, "/block") == 0) { dbg("/block top level, look for device link\n"); goto device_link; } /* are we at the top level? */ pos = strrchr(parent_devpath, '/'); if (pos == NULL || pos == parent_devpath) return NULL; /* get parent and remember it */ dev->parent = sysfs_device_get(parent_devpath); return dev->parent; device_link: strlcpy(parent_devpath, dev->devpath, sizeof(parent_devpath)); strlcat(parent_devpath, "/device", sizeof(parent_devpath)); if (sysfs_resolve_link(parent_devpath, sizeof(parent_devpath)) != 0) return NULL; /* get parent and remember it */ dev->parent = sysfs_device_get(parent_devpath); return dev->parent; } struct sysfs_device *sysfs_device_get_parent_with_subsystem(struct sysfs_device *dev, const char *subsystem) { struct sysfs_device *dev_parent; dev_parent = sysfs_device_get_parent(dev); while (dev_parent != NULL) { if (strcmp(dev_parent->subsystem, subsystem) == 0) return dev_parent; dev_parent = sysfs_device_get_parent(dev_parent); } return NULL; } char *sysfs_attr_get_value(const char *devpath, const char *attr_name) { char path_full[PATH_SIZE]; const char *path; char value[NAME_SIZE]; struct sysfs_attr *attr_loop; struct sysfs_attr *attr; struct stat statbuf; int fd; ssize_t size; size_t sysfs_len; dbg("open '%s'/'%s'\n", devpath, attr_name); sysfs_len = strlcpy(path_full, sysfs_path, sizeof(path_full)); if(sysfs_len >= sizeof(path_full)) sysfs_len = sizeof(path_full) - 1; path = &path_full[sysfs_len]; strlcat(path_full, devpath, sizeof(path_full)); strlcat(path_full, "/", sizeof(path_full)); strlcat(path_full, attr_name, sizeof(path_full)); /* look for attribute in cache */ list_for_each_entry(attr_loop, &attr_list, node) { if (strcmp(attr_loop->path, path) == 0) { dbg("found in cache '%s'\n", attr_loop->path); return attr_loop->value; } } /* store attribute in cache (also negatives are kept in cache) */ dbg("new uncached attribute '%s'\n", path_full); attr = malloc(sizeof(struct sysfs_attr)); if (attr == NULL) return NULL; memset(attr, 0x00, sizeof(struct sysfs_attr)); strlcpy(attr->path, path, sizeof(attr->path)); dbg("add to cache '%s'\n", path_full); list_add(&attr->node, &attr_list); if (lstat(path_full, &statbuf) != 0) { dbg("stat '%s' failed: %s\n", path_full, strerror(errno)); goto out; } if (S_ISLNK(statbuf.st_mode)) { /* links return the last element of the target path */ char link_target[PATH_SIZE]; int len; const char *pos; len = readlink(path_full, link_target, sizeof(link_target)); if (len > 0) { link_target[len] = '\0'; pos = strrchr(link_target, '/'); if (pos != NULL) { dbg("cache '%s' with link value '%s'\n", path_full, value); strlcpy(attr->value_local, &pos[1], sizeof(attr->value_local)); attr->value = attr->value_local; } } goto out; } /* skip directories */ if (S_ISDIR(statbuf.st_mode)) goto out; /* skip non-readable files */ if ((statbuf.st_mode & S_IRUSR) == 0) goto out; /* read attribute value */ fd = open(path_full, O_RDONLY); if (fd < 0) { dbg("attribute '%s' can not be opened\n", path_full); goto out; } size = read(fd, value, sizeof(value)); close(fd); if (size < 0) goto out; if (size == sizeof(value)) goto out; /* got a valid value, store and return it */ value[size] = '\0'; remove_trailing_chars(value, '\n'); dbg("cache '%s' with attribute value '%s'\n", path_full, value); strlcpy(attr->value_local, value, sizeof(attr->value_local)); attr->value = attr->value_local; out: return attr->value; } int sysfs_lookup_devpath_by_subsys_id(char *devpath_full, size_t len, const char *subsystem, const char *id) { size_t sysfs_len; char path_full[PATH_SIZE]; char *path; struct stat statbuf; sysfs_len = strlcpy(path_full, sysfs_path, sizeof(path_full)); path = &path_full[sysfs_len]; if (strcmp(subsystem, "subsystem") == 0) { strlcpy(path, "/subsystem/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; strlcpy(path, "/bus/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; goto out; strlcpy(path, "/class/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; } if (strcmp(subsystem, "module") == 0) { strlcpy(path, "/module/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; goto out; } if (strcmp(subsystem, "drivers") == 0) { char subsys[NAME_SIZE]; char *driver; strlcpy(subsys, id, sizeof(subsys)); driver = strchr(subsys, ':'); if (driver != NULL) { driver[0] = '\0'; driver = &driver[1]; strlcpy(path, "/subsystem/", sizeof(path_full) - sysfs_len); strlcat(path, subsys, sizeof(path_full) - sysfs_len); strlcat(path, "/drivers/", sizeof(path_full) - sysfs_len); strlcat(path, driver, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; strlcpy(path, "/bus/", sizeof(path_full) - sysfs_len); strlcat(path, subsys, sizeof(path_full) - sysfs_len); strlcat(path, "/drivers/", sizeof(path_full) - sysfs_len); strlcat(path, driver, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; } goto out; } strlcpy(path, "/subsystem/", sizeof(path_full) - sysfs_len); strlcat(path, subsystem, sizeof(path_full) - sysfs_len); strlcat(path, "/devices/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; strlcpy(path, "/bus/", sizeof(path_full) - sysfs_len); strlcat(path, subsystem, sizeof(path_full) - sysfs_len); strlcat(path, "/devices/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; strlcpy(path, "/class/", sizeof(path_full) - sysfs_len); strlcat(path, subsystem, sizeof(path_full) - sysfs_len); strlcat(path, "/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; strlcpy(path, "/firmware/", sizeof(path_full) - sysfs_len); strlcat(path, subsystem, sizeof(path_full) - sysfs_len); strlcat(path, "/", sizeof(path_full) - sysfs_len); strlcat(path, id, sizeof(path_full) - sysfs_len); if (stat(path_full, &statbuf) == 0) goto found; out: return 0; found: if (S_ISLNK(statbuf.st_mode)) sysfs_resolve_link(path, sizeof(path_full) - sysfs_len); strlcpy(devpath_full, path, len); return 1; } char *sysfs_get_value(const char *id, char *subsys, char *param) { char devpath[PATH_SIZE]; char *sysfs_value; if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), subsys, id)) { log_debug(3, "Could not lookup devpath for %s %s\n", subsys, id); return NULL; } sysfs_value = sysfs_attr_get_value(devpath, param); if (!sysfs_value) { log_debug(3, "Could not read attr %s on path %s\n", param, devpath); return NULL; } if (!strncmp(sysfs_value, "", 6) || !strncmp(sysfs_value, "(null)", 6)) return NULL; return sysfs_value; } int sysfs_get_uint(char *id, char *subsys, char *param, unsigned int *value) { char *sysfs_value; *value = -1; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value) return EIO; errno = 0; *value = strtoul(sysfs_value, NULL, 0); if (errno) return errno; return 0; } int sysfs_get_int(const char *id, char *subsys, char *param, int *value) { char *sysfs_value; *value = -1; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value) return EIO; *value = atoi(sysfs_value); return 0; } int sysfs_get_str(char *id, char *subsys, char *param, char *value, int value_size) { char *sysfs_value; int len; value[0] = '\0'; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value || !strlen(sysfs_value)) return EIO; len = strlen(sysfs_value); if (len && (sysfs_value[len - 1] == '\n')) sysfs_value[len - 1] = '\0'; strncpy(value, sysfs_value, value_size); value[value_size - 1] = '\0'; return 0; } int sysfs_get_uint64(char *id, char *subsys, char *param, uint64_t *value) { char *sysfs_value; *value = -1; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value) return EIO; if (sscanf(sysfs_value, "%" PRIu64 "\n", value) != 1) return EINVAL; return 0; } int sysfs_get_uint8(char *id, char *subsys, char *param, uint8_t *value) { char *sysfs_value; *value = -1; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value) return EIO; *value = (uint8_t)atoi(sysfs_value); return 0; } int sysfs_get_uint16(char *id, char *subsys, char *param, uint16_t *value) { char *sysfs_value; *value = -1; sysfs_value = sysfs_get_value(id, subsys, param); if (!sysfs_value) return EIO; *value = (uint16_t)atoi(sysfs_value); return 0; } int sysfs_set_param(char *id, char *subsys, char *attr_name, char *write_buf, ssize_t buf_size) { struct stat statbuf; char devpath[PATH_SIZE]; size_t sysfs_len; char path_full[PATH_SIZE]; const char *path; int rc = 0, fd; if (!sysfs_lookup_devpath_by_subsys_id(devpath, sizeof(devpath), subsys, id)) { log_debug(3, "Could not lookup devpath for %s %s\n", subsys, id); return EIO; } sysfs_len = strlcpy(path_full, sysfs_path, sizeof(path_full)); if(sysfs_len >= sizeof(path_full)) sysfs_len = sizeof(path_full) - 1; path = &path_full[sysfs_len]; strlcat(path_full, devpath, sizeof(path_full)); strlcat(path_full, "/", sizeof(path_full)); strlcat(path_full, attr_name, sizeof(path_full)); if (lstat(path_full, &statbuf)) { log_debug(3, "Could not stat %s\n", path_full); return errno; } if ((statbuf.st_mode & S_IWUSR) == 0) { log_error("Could not write to %s. Invalid permissions.\n", path_full); return EACCES; } fd = open(path_full, O_WRONLY); if (fd < 0) { log_error("Could not open %s err %d\n", path_full, errno); return errno; } if (write(fd, write_buf, buf_size) == -1) rc = errno; close(fd); return rc; } open-iscsi-2.0.873/usr/sysfs.h000066400000000000000000000053731175631155400161150ustar00rootroot00000000000000/* * This is from udev-121 udev.h * * Copyright (C) 2003 Greg Kroah-Hartman * Copyright (C) 2003-2006 Kay Sievers * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef _SYSFS_ #define _SYSFS_ #include #include "list.h" #include "string.h" #define PATH_SIZE 512 #define NAME_SIZE 256 struct sysfs_device { struct list_head node; /* for device cache */ struct sysfs_device *parent; /* already cached parent*/ char devpath[PATH_SIZE]; char subsystem[NAME_SIZE]; /* $class, $bus, drivers, module */ char kernel[NAME_SIZE]; /* device instance name */ char kernel_number[NAME_SIZE]; char driver[NAME_SIZE]; /* device driver name */ }; extern char sysfs_path[PATH_SIZE]; extern int sysfs_init(void); extern void sysfs_cleanup(void); extern void sysfs_device_set_values(struct sysfs_device *dev, const char *devpath, const char *subsystem, const char *driver); extern struct sysfs_device *sysfs_device_get(const char *devpath); extern struct sysfs_device *sysfs_device_get_parent(struct sysfs_device *dev); extern struct sysfs_device *sysfs_device_get_parent_with_subsystem(struct sysfs_device *dev, const char *subsystem); extern char *sysfs_attr_get_value(const char *devpath, const char *attr_name); extern int sysfs_resolve_link(char *path, size_t size); extern int sysfs_lookup_devpath_by_subsys_id(char *devpath, size_t len, const char *subsystem, const char *id); extern char *sysfs_get_value(const char *id, char *subsys, char *param); extern int sysfs_get_uint(char *id, char *subsys, char *param, unsigned int *value); extern int sysfs_get_int(const char *id, char *subsys, char *param, int *value); extern int sysfs_get_str(char *id, char *subsys, char *param, char *value, int value_size); extern int sysfs_get_uint64(char *id, char *subsys, char *param, uint64_t *value); extern int sysfs_get_uint8(char *id, char *subsys, char *param, uint8_t *value); extern int sysfs_get_uint16(char *id, char *subsys, char *param, uint16_t *value); extern int sysfs_set_param(char *id, char *subsys, char *attr_name, char *write_buf, ssize_t buf_size); #endif open-iscsi-2.0.873/usr/transport.c000066400000000000000000000144731175631155400167760ustar00rootroot00000000000000/* * iSCSI transport * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include #include #include #include #include #ifdef USE_KMOD #include #endif #include #include #include #include #include #include "sysdeps.h" #include "iscsi_err.h" #include "initiator.h" #include "transport.h" #include "log.h" #include "iscsi_util.h" #include "iscsi_sysfs.h" #include "cxgbi.h" #include "be2iscsi.h" #include "iser.h" struct iscsi_transport_template iscsi_tcp = { .name = "tcp", .ep_connect = iscsi_io_tcp_connect, .ep_poll = iscsi_io_tcp_poll, .ep_disconnect = iscsi_io_tcp_disconnect, }; struct iscsi_transport_template iscsi_iser = { .name = "iser", .rdma = 1, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, .create_conn = iser_create_conn, }; struct iscsi_transport_template cxgb3i = { .name = "cxgb3i", .set_host_ip = 1, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, .create_conn = cxgbi_create_conn, }; struct iscsi_transport_template cxgb4i = { .name = "cxgb4i", .set_host_ip = 1, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, .create_conn = cxgbi_create_conn, }; struct iscsi_transport_template bnx2i = { .name = "bnx2i", .set_host_ip = 1, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, }; struct iscsi_transport_template be2iscsi = { .name = "be2iscsi", .create_conn = be2iscsi_create_conn, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, }; struct iscsi_transport_template qla4xxx = { .name = "qla4xxx", .set_host_ip = 0, .ep_connect = ktransport_ep_connect, .ep_poll = ktransport_ep_poll, .ep_disconnect = ktransport_ep_disconnect, }; static struct iscsi_transport_template *iscsi_transport_templates[] = { &iscsi_tcp, &iscsi_iser, &cxgb3i, &cxgb4i, &bnx2i, &qla4xxx, &be2iscsi, NULL }; int transport_probe_for_offload(void) { struct if_nameindex *ifni; char transport_name[ISCSI_TRANSPORT_NAME_MAXLEN]; int i, sockfd; struct ifreq if_hwaddr; ifni = if_nameindex(); if (!ifni) { log_error("Could not search for transport modules: %s", strerror(errno)); return ISCSI_ERR_TRANS_NOT_FOUND; } sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { log_error("Could not open socket for ioctl: %s", strerror(errno)); goto free_ifni; } for (i = 0; ifni[i].if_index && ifni[i].if_name; i++) { struct if_nameindex *n = &ifni[i]; log_debug(6, "kmod probe found %s\n", n->if_name); strlcpy(if_hwaddr.ifr_name, n->if_name, IFNAMSIZ); if (ioctl(sockfd, SIOCGIFHWADDR, &if_hwaddr) < 0) continue; /* check for ARPHRD_ETHER (ethernet) */ if (if_hwaddr.ifr_hwaddr.sa_family != 1) continue; if (net_get_transport_name_from_netdev(n->if_name, transport_name)) continue; transport_load_kmod(transport_name); } close(sockfd); free_ifni: if_freenameindex(ifni); return 0; } /* * Most distros still do not have wide libkmod use, so * use modprobe for now */ #ifdef USE_KMOD int transport_load_kmod(char *transport_name) { struct kmod_ctx *ctx; struct kmod_module *mod; int rc; ctx = kmod_new(NULL, NULL); if (!ctx) { log_error("Could not load transport module %s. Out of " "memory.", transport_name); return ISCSI_ERR_NOMEM; } kmod_load_resources(ctx); /* * dumb dumb dumb - named iscsi_tcp and ib_iser differently from * transport name */ if (!strcmp(transport_name, "tcp")) rc = kmod_module_new_from_name(ctx, "iscsi_tcp", &mod); else if (!strcmp(transport_name, "iser")) rc = kmod_module_new_from_name(ctx, "ib_iser", &mod); else rc = kmod_module_new_from_name(ctx, transport_name, &mod); if (rc) { log_error("Failed to load module %s.", transport_name); rc = ISCSI_ERR_TRANS_NOT_FOUND; goto unref_mod; } rc = kmod_module_probe_insert_module(mod, KMOD_PROBE_APPLY_BLACKLIST, NULL, NULL, NULL, NULL); if (rc) { log_error("Could not insert module %s. Kmod error %d", transport_name, rc); rc = ISCSI_ERR_TRANS_NOT_FOUND; } kmod_module_unref(mod); unref_mod: kmod_unref(ctx); return rc; } #else int transport_load_kmod(char *transport_name) { char *cmdline[4]; pid_t pid; cmdline[0] = "/sbin/modprobe"; cmdline[1] = "-qb"; cmdline[3] = NULL; /* * dumb dumb mistake - named iscsi_tcp and ib_iser differently from * transport name */ if (!strcmp(transport_name, "tcp")) cmdline[2] = "iscsi_tcp"; else if (!strcmp(transport_name, "iser")) cmdline[2] = "ib_iser"; else cmdline[2] = transport_name; if (iscsi_sysfs_is_transport_loaded(cmdline[2])) return 0; pid = fork(); if (pid == 0) { if (execv("/sbin/modprobe", cmdline) < 0) { log_error("Failed to load module %s: %s", transport_name, strerror(errno)); exit(-errno); } exit(0); } else if (pid < 0) { log_error("Failed to fork process to load module %s: %s", transport_name, strerror(errno)); return ISCSI_ERR_TRANS_NOT_FOUND; } if (waitpid(pid, NULL, 0) < 0) { log_error("Failed to load module %s", transport_name); return ISCSI_ERR_TRANS_NOT_FOUND; } return 0; } #endif int set_transport_template(struct iscsi_transport *t) { struct iscsi_transport_template *tmpl; int j; for (j = 0; iscsi_transport_templates[j] != NULL; j++) { tmpl = iscsi_transport_templates[j]; if (!strcmp(tmpl->name, t->name)) { t->template = tmpl; log_debug(3, "Matched transport %s\n", t->name); return 0; } } log_error("Could not find template for %s. An updated iscsiadm " "is probably needed.\n", t->name); return ENOSYS; } open-iscsi-2.0.873/usr/transport.h000066400000000000000000000030511175631155400167710ustar00rootroot00000000000000/* * iSCSI transport * * Copyright (C) 2006 Mike Christie * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef ISCSI_TRANSPORT_H #define ISCSI_TRANSPORT_H #include "types.h" #include "config.h" struct iscsi_transport; struct iscsi_conn; struct iscsi_transport_template { const char *name; uint8_t rdma; /* * Drivers should set this if they require iscsid to set * the host's ip address. */ uint8_t set_host_ip; int (*ep_connect) (struct iscsi_conn *conn, int non_blocking); int (*ep_poll) (struct iscsi_conn *conn, int timeout_ms); void (*ep_disconnect) (struct iscsi_conn *conn); void (*create_conn) (struct iscsi_conn *conn); }; /* represents data path provider */ struct iscsi_transport { struct list_head list; uint64_t handle; uint32_t caps; char name[ISCSI_TRANSPORT_NAME_MAXLEN]; struct list_head sessions; struct iscsi_transport_template *template; }; extern int set_transport_template(struct iscsi_transport *t); extern int transport_load_kmod(char *transport_name); extern int transport_probe_for_offload(void); #endif open-iscsi-2.0.873/usr/types.h000066400000000000000000000006151175631155400161040ustar00rootroot00000000000000/* * Copyright (C) 2002-2003 Ardis Technolgies * * Released under the terms of the GNU GPL v2.0. */ #ifndef TYPES_H #define TYPES_H #include #include #include /* * using the __be types allows stricter static * typechecking in the kernel using sparse */ typedef uint16_t __be16; typedef uint32_t __be32; #endif /* TYPES_H */ open-iscsi-2.0.873/usr/version.h000066400000000000000000000005151175631155400164240ustar00rootroot00000000000000#ifndef ISCSI_VERSION_DEF #define ISCSI_VERSION_DEF /* * iSCSI tools version. * This may not be the same value as the kernel versions because * some other maintainer could merge a patch without going through us */ #define ISCSI_VERSION_STR "2.0-873" #define ISCSI_VERSION_FILE "/sys/module/scsi_transport_iscsi/version" #endif open-iscsi-2.0.873/utils/000077500000000000000000000000001175631155400151145ustar00rootroot00000000000000open-iscsi-2.0.873/utils/.gitignore000066400000000000000000000000141175631155400170770ustar00rootroot00000000000000iscsi-iname open-iscsi-2.0.873/utils/Makefile000066400000000000000000000005111175631155400165510ustar00rootroot00000000000000# This Makefile will work only with GNU make. CFLAGS += $(OPTFLAGS) -O2 -fno-inline -Wall -Wstrict-prototypes -g PROGRAMS = iscsi-iname all: $(PROGRAMS) iscsi-iname: md5.o iscsi-iname.o $(CC) $(CFLAGS) $^ $(DBM_LIB) -o $@ clean: rm -f *.o $(PROGRAMS) .depend depend: gcc $(CFLAGS) -M `ls *.c` > .depend -include .depend open-iscsi-2.0.873/utils/fwparam_ibft/000077500000000000000000000000001175631155400175555ustar00rootroot00000000000000open-iscsi-2.0.873/utils/fwparam_ibft/Makefile000066400000000000000000000026341175631155400212220ustar00rootroot00000000000000# # Copyright (C) IBM Corporation. 2007 # Author: Doug Maxey # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authors: Patrick Mansfield # Mike Anderson # Doug Maxey # "Prasanna Mumbai" # SYSDEPS_OBJS = $(wildcard ../sysdeps/*.o) OBJS := fw_entry.o fwparam_sysfs.o $(SYSDEPS_OBJS) ../../usr/iscsi_net_util.o OBJS += prom_lex.o prom_parse.tab.o fwparam_ppc.o CLEANFILES = $(OBJS) *.output *~ OPTFLAGS ?= -O2 -g -fPIC WARNFLAGS ?= -Wall -Wstrict-prototypes CFLAGS += $(OPTFLAGS) $(WARNFLAGS) -I../../include -I../../usr -D_GNU_SOURCE all: $(OBJS) clean: rm -f *.o $(CLEANFILES) .depend $(OBJS): prom_parse.tab.h prom_parse.h fwparam_ibft.h depend: gcc $(CFLAGS) -M `ls *.c` > .depend -include .depend open-iscsi-2.0.873/utils/fwparam_ibft/fw_entry.c000066400000000000000000000144261175631155400215650ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * based on code written by "Prasanna Mumbai" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include #include #include #include #include #include #include #include #include #include #include #include #include "fw_context.h" #include "fwparam.h" #include "idbm_fields.h" #include "iscsi_net_util.h" #include "iscsi_err.h" #include "config.h" #include "iface.h" /** * fw_setup_nics - setup nics (ethXs) based on ibft net info * * Currently does not support vlans. * * If this is a offload card, this function does nothing. The * net info is used by the iscsi iface settings for the iscsi * function. */ int fw_setup_nics(void) { struct boot_context *context; struct list_head targets; char *iface_prev = NULL, transport[16]; int needs_bringup = 0, ret = 0, err; INIT_LIST_HEAD(&targets); ret = fw_get_targets(&targets); if (ret || list_empty(&targets)) { printf("Could not setup fw entries.\n"); return ISCSI_ERR_NO_OBJS_FOUND; } /* * For each target in iBFT bring up required NIC and use routing * to force iSCSI traffic through correct NIC */ list_for_each_entry(context, &targets, list) { /* if it is a offload nic ignore it */ if (!net_get_transport_name_from_netdev(context->iface, transport)) continue; if (iface_prev == NULL || strcmp(context->iface, iface_prev)) { /* Note: test above works because there is a * maximum of two targets in the iBFT */ iface_prev = context->iface; needs_bringup = 1; } err = net_setup_netdev(context->iface, context->ipaddr, context->mask, context->gateway, context->target_ipaddr, needs_bringup); if (err) ret = err; } fw_free_targets(&targets); if (ret) return ISCSI_ERR; else return 0; } /** * fw_get_entry - return boot context of portal used for boot * @context: firmware info of portal * * Returns non-zero if no portal was used for boot. * * This function is not thread safe. */ int fw_get_entry(struct boot_context *context) { int ret; ret = fwparam_ppc_boot_info(context); if (ret) ret = fwparam_sysfs_boot_info(context); return ret; } /** * fw_get_targets - get a boot_context struct for each target * @list: list to add entires on. * * Returns zero if entries were found that can be traversed with the * list.h helpers, or non-zero if no entries are found. * * fw_free_targets should be called to free the list. * * This function is not thread safe. */ int fw_get_targets(struct list_head *list) { int ret; ret = fwparam_ppc_get_targets(list); if (ret) ret = fwparam_sysfs_get_targets(list); return ret; } void fw_free_targets(struct list_head *list) { struct boot_context *curr, *tmp; if (!list || list_empty(list)) return; list_for_each_entry_safe(curr, tmp, list, list) { list_del(&curr->list); free(curr); } } static void dump_initiator(struct boot_context *context) { struct iface_rec iface; memset(&iface, 0, sizeof(iface)); iface_setup_defaults(&iface); iface_setup_from_boot_context(&iface, context); if (strlen(context->initiatorname)) printf("%s = %s\n", IFACE_INAME, context->initiatorname); if (strlen(context->isid)) printf("%s = %s\n", IFACE_ISID, context->isid); printf("%s = %s\n", IFACE_TRANSPORTNAME, iface.transport_name); } static void dump_target(struct boot_context *context) { if (strlen(context->targetname)) printf("%s = %s\n", NODE_NAME, context->targetname); if (strlen(context->target_ipaddr)) printf(CONN_ADDR" = %s\n", 0, context->target_ipaddr); printf(CONN_PORT" = %d\n", 0, context->target_port); if (strlen(context->chap_name)) printf("%s = %s\n", SESSION_USERNAME, context->chap_name); if (strlen(context->chap_password)) printf("%s = %s\n", SESSION_PASSWORD, context->chap_password); if (strlen(context->chap_name_in)) printf("%s = %s\n", SESSION_USERNAME_IN, context->chap_name_in); if (strlen(context->chap_password_in)) printf("%s = %s\n", SESSION_PASSWORD_IN, context->chap_password_in); if (strlen(context->lun)) printf("%s = %s\n", NODE_BOOT_LUN, context->lun); } static void dump_network(struct boot_context *context) { /* Dump the 8 byte mac address (not iser support) */ if (strlen(context->mac)) printf("%s = %s\n", IFACE_HWADDR, context->mac); /* * If this has a valid address then DHCP was used (broadcom sends * 0.0.0.0). */ if (strlen(context->dhcp) && strcmp(context->dhcp, "0.0.0.0")) printf("%s = DHCP\n", IFACE_BOOT_PROTO); else printf("%s = STATIC\n", IFACE_BOOT_PROTO); if (strlen(context->ipaddr)) printf("%s = %s\n", IFACE_IPADDR, context->ipaddr); if (strlen(context->mask)) printf("%s = %s\n", IFACE_SUBNET_MASK, context->mask); if (strlen(context->gateway)) printf("%s = %s\n", IFACE_GATEWAY, context->gateway); if (strlen(context->primary_dns)) printf("%s = %s\n", IFACE_PRIMARY_DNS, context->primary_dns); if (strlen(context->secondary_dns)) printf("%s = %s\n", IFACE_SEC_DNS, context->secondary_dns); if (strlen(context->vlan)) printf("%s = %s\n", IFACE_VLAN_ID, context->vlan); if (strlen(context->iface)) printf("%s = %s\n", IFACE_NETNAME, context->iface); } /** * fw_print_entry - print boot context info of portal used for boot * @context: firmware info of portal * * Does not print anything if no portal was used for boot. * * TODO: Merge this in with idbm.c helpers. */ void fw_print_entry(struct boot_context *context) { printf("%s\n", ISCSI_BEGIN_REC); dump_initiator(context); dump_network(context); dump_target(context); printf("%s\n", ISCSI_END_REC); } open-iscsi-2.0.873/utils/fwparam_ibft/fwparam.h000066400000000000000000000021241175631155400213620ustar00rootroot00000000000000/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifndef FWPARAM_H_ #define FWPARAM_H_ #include #include "fw_context.h" #define FILENAMESZ (256) struct boot_context; int fwparam_sysfs_boot_info(struct boot_context *context); int fwparam_sysfs_get_targets(struct list_head *list); int fwparam_ppc_boot_info(struct boot_context *context); int fwparam_ppc_get_targets(struct list_head *list); #endif /* FWPARAM_IBFT_H_ */ open-iscsi-2.0.873/utils/fwparam_ibft/fwparam_ibft.c000066400000000000000000000311711175631155400223650ustar00rootroot00000000000000/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * Copyright (C) IBM Corporation, 2006 * * Authors: Patrick Mansfield * Mike Anderson * */ #include #include #include #include #include #include #include #include #include #include "fwparam_ibft.h" #include "fw_context.h" char *progname = "fwparam_ibft"; int debug; int dev_count; char filename[FILENAMESZ]; const char nulls[16]; /* defaults to zero */ int verify_hdr(char *name, struct ibft_hdr *hdr, int id, int version, int length) { #define VERIFY_HDR_FIELD(val) \ if (hdr->val != val) { \ fprintf(stderr, \ "%s: error, %s structure expected %s %d but" \ " got %d\n", \ progname, name, #val, hdr->val, val); \ return -1; \ } if (debug > 1) fprintf(stderr, "%s: verifying %s header\n", __FUNCTION__, name); VERIFY_HDR_FIELD(id); VERIFY_HDR_FIELD(version); VERIFY_HDR_FIELD(length); #undef VERIFY_HDR_FIELD return 0; } #define CHECK_HDR(ident, name) \ verify_hdr(#name, &ident->hdr, id_##name, version_##name, \ sizeof(*ident)) /* * Format 8 byte scsi LUN. Just format 8 bytes of hex, we could also * format in the format as specified in rfc4173 (1-2-3-4, or 1-2), that is * a nice format for humans :) */ void format_lun(char *buf, size_t size, uint8_t *lun) { int i; for (i = 0; i < 8; i++) snprintf(buf++, size--, "%x", lun[i]); } void dump_lun(char *prefix, char *id, uint8_t *lun) { char buf[32]; format_lun(buf, sizeof(buf), lun); if (prefix) printf("%s%s=%s\n", prefix, id, buf); else printf("%s=%s\n", id, buf); } void dump_word(char *prefix, char *id, unsigned short value) { if (prefix) printf("%s%s=%d\n", prefix, id, value); else printf("%s=%d\n", id, value); } void dump_string(char *prefix, char *id, char *value, int len) { if (len == 0) return; /* * Not checking if the offset is non-zero, it is not even passed * in, else we need to pass a start and offset rather than value. */ /* * prints the string in "value" that has "len" characters (the * printf "*" * means use the next argument as the length). */ if (prefix) printf("%s%s=%.*s\n", prefix, id, len, value); else printf("%s=%.*s\n", id, len, value); } void format_ipaddr(char *buf, size_t size, uint8_t *ip) { if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0 && ip[4] == 0 && ip[5] == 0 && ip[6] == 0 && ip[7] == 0 && ip[8] == 0 && ip[9] == 0 && ip[10] == 0xff && ip[11] == 0xff) { /* * IPV4 */ snprintf(buf, size, "%d.%d.%d.%d", ip[12], ip[13], ip[14], ip[15]); } else { /* XXX ... */ fprintf(stderr, "%s: warning no IPV6 support.\n", progname); buf[0] = '\0'; return; } } /* * Dump the 16 byte ipaddr, as IPV6 or IPV4. */ void dump_ipaddr(char *prefix, char *id, uint8_t *ip) { char buf[32]; /* * Assumes all zero means no IP address. */ if (!memcmp(ip, nulls, sizeof(nulls))) return; format_ipaddr(buf, sizeof(buf), ip); if (prefix) printf("%s%s=%s\n", prefix, id, buf); else printf("%s=%s\n", id, buf); } /* * Dump the 8 byte mac address */ void dump_mac(char *prefix, char *id, uint8_t *mac) { int i; if (prefix) printf("%s%s=", prefix, id); else printf("%s=", id); for (i = 0; i < 5; i++) printf("%02x:", mac[i]); printf("%02x\n", mac[i]); } void dump_initiator_prefix(void *ibft_loc, struct ibft_initiator *initiator, char *prefix) { if (!initiator) return; /* * Not all fields are (or were) supported by open-iscsi. Plus, * some of these are for discovery. */ dump_ipaddr(prefix, "ISNS", initiator->isns_server); dump_ipaddr(prefix, "SLP", initiator->slp_server); dump_ipaddr(prefix, "PRIMARY_RADIUS_SERVER", initiator->pri_radius_server); dump_ipaddr(prefix, "SECONDARY_RADIUS_SERVER", initiator->sec_radius_server); dump_string(prefix, "NAME", ibft_loc + initiator->initiator_name_off, initiator->initiator_name_len); } void dump_nic_prefix(void *ibft_loc, struct ibft_nic *nic, char *prefix) { if (!nic) return; dump_mac(prefix, "HWADDR", nic->mac); /* * Assume dhcp if any non-zero portions of its address are set * (again, undocumented). */ if (memcmp(nic->dhcp, nulls, sizeof(nic->dhcp))) { dump_ipaddr(prefix, "DHCP", nic->dhcp); } else { dump_ipaddr(prefix, "IPADDR", nic->ip_addr); /* * XXX: Not sure how a mask "prefix" will be used in network * bringup, this sounds less flexible than the normal * masks used. */ printf("%s%s=%d\n", prefix, "MASK", nic->subnet_mask_prefix); dump_ipaddr(prefix, "GATEWAY", nic->gateway); dump_ipaddr(prefix, "DNSADDR1", nic->primary_dns); dump_ipaddr(prefix, "DNSADDR2", nic->secondary_dns); } dump_string(prefix, "HOSTNAME", ibft_loc + nic->hostname_off, nic->hostname_len); /* * XXX unknown vlan: */ dump_word(prefix, "VLAN", nic->vlan); /* * XXX sort of unknown pci_bdf: 8 bits bus, 5 bits device, 3 bits * function. */ if (prefix ) printf("%s%s=%d:%d:%d\n", prefix, "PCI_BDF", /* bus */ (nic->pci_bdf & 0xff00) >> 8, /* device */ (nic->pci_bdf & 0xf8) >> 3, /* function */ (nic->pci_bdf & 0x07)); else printf("%s=%d:%d:%d\n", "PCI_BDF", /* bus */ (nic->pci_bdf & 0xff00) >> 8, /* device */ (nic->pci_bdf & 0xf8) >> 3, /* function */ (nic->pci_bdf & 0x07)); } void dump_tgt_prefix(void *ibft_loc, struct ibft_tgt *tgt, char *prefix) { if (!tgt) return; dump_ipaddr(prefix, "IPADDR", tgt->ip_addr); dump_word(prefix, "PORT", tgt->port); /* * XXX there should at least be a "no LUN specified field", or * have different location objects, so the setup can search for * the appropriate LU (like mount by label, or use of the * /dev/disk/by-id names, or .... * * Like: * uint8_t lu_type; 0: nothing specified, 1: LUN, 2: misc * name - OS can use any way it wants, would have embedded a * "NAME=string", like "LABEL=myrootvolume", or * "DEV_NAME=/dev/disk/by-id/scsi-198279562093043094003030903". * union lu_value { * uint8_t lun[8]; * uint8_t misc_name[64]; * }; * * Maybe just add an extension header, and let the admin/user put * strings like: "area:VALUE=string" into it? */ dump_lun(prefix, "LUN", tgt->lun); dump_string(prefix, "NAME", ibft_loc + tgt->tgt_name_off, tgt->tgt_name_len); /* * Note: don't dump the nic association, just let the IP address take * care of the routing. */ /* * Note: don't dump the chap "type", just the chap names and secrets * if any are specified - they imply CHAP and reversed CHAP. */ dump_string(prefix, "CHAP_NAME", ibft_loc + tgt->chap_name_off, tgt->chap_name_len); dump_string(prefix, "CHAP_PASSWORD", ibft_loc + tgt->chap_secret_off, tgt->chap_secret_len); dump_string(prefix, "CHAP_NAME_IN", ibft_loc + tgt->rev_chap_name_off, tgt->rev_chap_name_len); dump_string(prefix, "CHAP_PASSWORD_IN", ibft_loc + tgt->rev_chap_secret_off, tgt->rev_chap_secret_len); } /* * Read in and dump ASCII output for ibft starting at ibft_loc. */ int dump_ibft(void *ibft_loc, struct boot_context *context) { struct ibft_table_hdr *ibft_hdr = ibft_loc; struct ibft_control *control; struct ibft_initiator *initiator = NULL; struct ibft_nic *nic0 = NULL, *nic1 = NULL; struct ibft_tgt *tgt0 = NULL, *tgt1 = NULL; char ipbuf[32]; control = ibft_loc + sizeof(*ibft_hdr); CHECK_HDR(control, control); /* * The ibft is setup to return multiple pieces for each * object (like multiple nic's or multiple targets), but it only * maps 1 initiator, two targets, and two nics, follow that layout * here (i.e. don't search for others). * * Also, unknown what to do for extensions piece, it is not * documented. */ if (control->initiator_off) { initiator = ibft_loc + control->initiator_off; CHECK_HDR(initiator, initiator); } if (control->nic0_off) { nic0 = ibft_loc + control->nic0_off; CHECK_HDR(nic0, nic); } if (control->nic1_off) { nic1 = ibft_loc + control->nic1_off; CHECK_HDR(nic1, nic); } if (control->tgt0_off) { tgt0 = ibft_loc + control->tgt0_off; CHECK_HDR(tgt0, target); } if (control->tgt1_off) { tgt1 = ibft_loc + control->tgt1_off; CHECK_HDR(tgt1, target); } strlcpy(context->initiatorname, (char *)ibft_loc+initiator->initiator_name_off, initiator->initiator_name_len + 1); if (tgt0 && (tgt0->hdr.flags & INIT_FLAG_FW_SEL_BOOT)) { strlcpy((char *)context->targetname, (char *)(ibft_loc+tgt0->tgt_name_off), tgt0->tgt_name_len); format_ipaddr(ipbuf, sizeof(ipbuf), tgt0->ip_addr); strlcpy((char *)context->target_ipaddr, ipbuf, sizeof(ipbuf)); context->target_port = tgt0->port; strlcpy(context->chap_name, (char *)(ibft_loc + tgt0->chap_name_off), tgt0->chap_name_len); strlcpy(context->chap_password, (char*)(ibft_loc + tgt0->chap_secret_off), tgt0->chap_secret_len); strlcpy(context->chap_name_in, (char *)(ibft_loc + tgt0->rev_chap_name_off), tgt0->rev_chap_name_len); strlcpy(context->chap_password_in, (char *)(ibft_loc + tgt0->rev_chap_secret_off), tgt0->rev_chap_secret_len); } else if (tgt1 && (tgt1->hdr.flags & INIT_FLAG_FW_SEL_BOOT)) { strlcpy((char *)context->targetname, (char *)(ibft_loc+tgt1->tgt_name_off), tgt1->tgt_name_len); format_ipaddr(ipbuf, sizeof(ipbuf), tgt1->ip_addr); strlcpy((char *)context->target_ipaddr,ipbuf, sizeof(ipbuf)); context->target_port = tgt1->port; strlcpy(context->chap_name, (char *)(ibft_loc + tgt1->chap_name_off), tgt1->chap_name_len); strlcpy(context->chap_password, (char*)(ibft_loc + tgt1->chap_secret_off), tgt1->chap_secret_len); strlcpy(context->chap_name_in, (char *)(ibft_loc + tgt1->rev_chap_name_off), tgt1->rev_chap_name_len); strlcpy(context->chap_password_in, (char *)(ibft_loc + tgt1->rev_chap_secret_off), tgt1->rev_chap_secret_len); } return 0; } char *search_ibft(unsigned char *start, int length) { unsigned char *cur_ptr; struct ibft_table_hdr *ibft_hdr; unsigned char check_sum; uint32_t i; cur_ptr = (unsigned char *)start; for (cur_ptr = (unsigned char *)start; cur_ptr < (start + length); cur_ptr++) { if (memcmp(cur_ptr, iBFTSTR,strlen(iBFTSTR))) continue; ibft_hdr = (struct ibft_table_hdr *)cur_ptr; /* Make sure it's correct version. */ if (ibft_hdr->revision != iBFT_REV) continue; /* Make sure that length is valid. */ if ((cur_ptr + ibft_hdr->length) <= (start + length)) { /* Let verify the checksum */ for (i = 0, check_sum = 0; i < ibft_hdr->length; i++) check_sum += cur_ptr[i]; if (check_sum == 0) return (char *)cur_ptr; } } return NULL; } int fwparam_ibft(struct boot_context *context, const char *filepath) { int fd, ret; char *filebuf, *ibft_loc; int start = 512 * 1024; /* 512k */ int end_search = (1024 * 1024) - start; /* 512k */ struct stat buf; if (filepath) strlcpy(filename, filepath, FILENAMESZ); else strlcpy(filename, X86_DEFAULT_FILENAME, FILENAMESZ); fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "Could not open %s: %s (%d)\n", filename, strerror(errno), errno); return -1; } /* Find the size. */ if (stat(filename, &buf)!=0) { fprintf(stderr, "Could not stat file %s: %s (%d)\n", filename, strerror(errno), errno); return -1; } /* And if not zero use that size */ if (buf.st_size > 0) { start = 0; end_search=buf.st_size; } /* * XXX Possibly warn and exit if start > filesize(fd), or if start + * end_search > filesize(fd). Else, we will get a bus error for * small files (with memmap, and for testing at least, it would * be hard to find a system with less than 1024k). */ filebuf = mmap(NULL, end_search, PROT_READ, MAP_PRIVATE, fd, start); if (filebuf == MAP_FAILED) { fprintf(stderr, "Could not mmap %s: %s (%d)\n", filename, strerror(errno), errno); ret = -1; goto done; } ibft_loc = search_ibft((unsigned char *)filebuf, end_search); if (ibft_loc) ret = dump_ibft(ibft_loc, context); else { printf("Could not find iBFT.\n"); ret = -1; } munmap(filebuf, end_search); done: close(fd); return ret; } open-iscsi-2.0.873/utils/fwparam_ibft/fwparam_ibft.h000066400000000000000000000070561175631155400223770ustar00rootroot00000000000000/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * Copyright (C) IBM Corporation, 2006,2007 * * Authors: Doug Maxey * Patrick Mansfield * */ #ifndef FWPARAM_IBFT_H_ #define FWPARAM_IBFT_H_ /* #include */ #include #include "fw_context.h" /* * Structures here are is based on Doug's original code, and Patrick's * interpretation of the IBM internal design document title the "iSCSI * Boot Firmware Table (iBFT)". */ #define iBFTSTR "iBFT" #define iBFT_SIG { 'i','B','F','T' } #define iBFT_REV 1 /* * These macros are lower case to make the verify_hdr macro easier. */ #define version_control 1 #define version_initiator 1 #define version_nic 1 #define version_target 1 #define version_extensions 1 enum ibft_id { id_control = 1, id_initiator, id_nic, id_target, id_extensions, }; struct ibft_hdr { uint8_t id; uint8_t version; uint16_t length; uint8_t ind; uint8_t flags; }; struct ibft_table_hdr { uint8_t signature[4]; uint32_t length; uint8_t revision; uint8_t checksum; uint8_t oemid[6]; uint8_t oem_table_id[8]; uint8_t rsvd1[24]; } __attribute__((__packed__)); struct ibft_control { struct ibft_hdr hdr; uint16_t extensions; uint16_t initiator_off; uint16_t nic0_off; uint16_t tgt0_off; uint16_t nic1_off; uint16_t tgt1_off; } __attribute__((__packed__)); struct ibft_initiator { #define INIT_FLAG_VALID 1 #define INIT_FLAG_FW_SEL_BOOT 2 struct ibft_hdr hdr; uint8_t isns_server[16]; uint8_t slp_server[16]; uint8_t pri_radius_server[16]; uint8_t sec_radius_server[16]; uint16_t initiator_name_len; uint16_t initiator_name_off; } __attribute__((__packed__)); struct ibft_nic { #define NIC_FLAG_VALID 1 #define NIC_FLAG_FW_SEL_BOOT 2 struct ibft_hdr hdr; uint8_t ip_addr[16]; uint8_t subnet_mask_prefix; uint8_t origin; uint8_t gateway[16]; uint8_t primary_dns[16]; uint8_t secondary_dns[16]; uint8_t dhcp[16]; uint16_t vlan; uint8_t mac[6]; uint16_t pci_bdf; uint16_t hostname_len; uint16_t hostname_off; } __attribute__((__packed__)); struct ibft_tgt { #define TGT_FLAG_VALID 1 #define TGT_FLAG_FW_SEL_BOOT 2 #define TGT_FLAG_USE_RADIUS_CHAT 4 #define TGT_FLAG_USE_RADIUS_RCHAT 8 struct ibft_hdr hdr; uint8_t ip_addr[16]; uint16_t port; uint8_t lun[8]; #define TGT_CHAP 1 #define TGT_MUTUAL_CHAP 2 uint8_t chap_type; uint8_t nic_assoc; uint16_t tgt_name_len; uint16_t tgt_name_off; uint16_t chap_name_len; uint16_t chap_name_off; uint16_t chap_secret_len; uint16_t chap_secret_off; uint16_t rev_chap_name_len; uint16_t rev_chap_name_off; uint16_t rev_chap_secret_len; uint16_t rev_chap_secret_off; } __attribute__((__packed__)); /* Common variables */ #define FILENAMESZ (256) extern char filename[FILENAMESZ]; #define X86_DEFAULT_FILENAME "/dev/mem" extern int debug; extern int dev_count; extern int fwparam_ibft(struct boot_context *context, const char *filepath); #endif /* FWPARAM_IBFT_H_ */ open-iscsi-2.0.873/utils/fwparam_ibft/fwparam_ibft_sysfs.c000066400000000000000000000224721175631155400236200ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Konrad Rzeszutek * Copyright (C) Red Hat, Inc. All rights reserved. 2008 * Copyright (C) Mike Christie 2008 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define _XOPEN_SOURCE 500 #define _SVID_SOURCE #include #include #include #include #include #include #include #include #include #include #include "sysfs.h" #include "fw_context.h" #include "fwparam.h" #include "sysdeps.h" #include "iscsi_net_util.h" #define IBFT_MAX 255 #define IBFT_SYSFS_ROOT "/sys/firmware/ibft/" #define NET_SYSFS_ROOT "/sys/class/net/" #define IBFT_SUBSYS "ibft" static char *target_list[IBFT_MAX]; static char *nic_list[IBFT_MAX]; static int nic_cnt; static int tgt_cnt; static int file_exist(const char *file) { struct stat bootpath_stat; return !stat(file, &bootpath_stat); } /* * Finds the etherrnetX and targetX under the sysfs directory. */ static int find_sysfs_dirs(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw) { if (tflag == FTW_D && (strstr(fpath + ftw->base, "target"))) { if (tgt_cnt == IBFT_MAX) { printf("Too many targets found in IBFT data." "Max number of targets %d\n", IBFT_MAX); return 0; } target_list[tgt_cnt++] = strdup(strstr(fpath, "target")); } if (tflag == FTW_D && (strstr(fpath + ftw->base, "ethernet"))) { if (nic_cnt == IBFT_MAX) { printf("Too many nics found in IBFT data." "Max number of nics %d\n", IBFT_MAX); return 0; } nic_list[nic_cnt++] = strdup(strstr(fpath, "ethernet")); } return 0; } static int get_iface_from_device(char *id, struct boot_context *context) { char dev_dir[FILENAMESZ]; int rc = ENODEV; DIR *dirfd; struct dirent *dent; memset(dev_dir, 0, FILENAMESZ); snprintf(dev_dir, FILENAMESZ, IBFT_SYSFS_ROOT"/%s/device", id); if (!file_exist(dev_dir)) return 0; dirfd = opendir(dev_dir); if (!dirfd) return errno; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..") || strncmp(dent->d_name, "net:", 4)) continue; if (!strncmp(dent->d_name, "net:", 4)) { if ((strlen(dent->d_name) - 4) > (sizeof(context->iface) - 1)) { rc = EINVAL; printf("Net device %s too big for iface " "buffer.\n", dent->d_name); break; } if (sscanf(dent->d_name, "net:%s", context->iface) != 1) rc = EINVAL; rc = 0; break; } else { printf("Could not read ethernet to net link.\n"); rc = EOPNOTSUPP; break; } } closedir(dirfd); if (rc != ENODEV) return rc; /* If not found try again with newer kernel networkdev sysfs layout */ strlcat(dev_dir, "/net", FILENAMESZ); if (!file_exist(dev_dir)) return rc; dirfd = opendir(dev_dir); if (!dirfd) return errno; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; /* Take the first "regular" directory entry */ if (strlen(dent->d_name) > (sizeof(context->iface) - 1)) { rc = EINVAL; printf("Net device %s too big for iface buffer.\n", dent->d_name); break; } strcpy(context->iface, dent->d_name); rc = 0; break; } closedir(dirfd); return rc; } /* * Routines to fill in the context values. */ static int fill_nic_context(char *id, struct boot_context *context) { int rc; rc = sysfs_get_str(id, IBFT_SUBSYS, "mac", context->mac, sizeof(context->mac)); if (rc) return rc; /* * Some offload cards like bnx2i use different MACs for the net and * iscsi functions, so we have to follow the sysfs links. * * Other ibft implementations may not be tied to a pci function, * so there will not be any device/net link, so we drop down to * the MAC matching. */ rc = get_iface_from_device(id, context); if (rc) { rc = net_get_netdev_from_hwaddress(context->mac, context->iface); if (rc) return rc; } sysfs_get_str(id, IBFT_SUBSYS, "ip-addr", context->ipaddr, sizeof(context->ipaddr)); sysfs_get_str(id, IBFT_SUBSYS, "vlan", context->vlan, sizeof(context->vlan)); sysfs_get_str(id, IBFT_SUBSYS, "subnet-mask", context->mask, sizeof(context->mask)); sysfs_get_str(id, IBFT_SUBSYS, "gateway", context->gateway, sizeof(context->gateway)); sysfs_get_str(id, IBFT_SUBSYS, "primary-dns", context->primary_dns, sizeof(context->primary_dns)); sysfs_get_str(id, IBFT_SUBSYS, "secondary-dns", context->secondary_dns, sizeof(context->secondary_dns)); sysfs_get_str(id, IBFT_SUBSYS, "dhcp", context->dhcp, sizeof(context->dhcp)); return 0; } static void fill_initiator_context(struct boot_context *context) { sysfs_get_str("initiator", IBFT_SUBSYS, "initiator-name", context->initiatorname, sizeof(context->initiatorname)); sysfs_get_str("initiator", IBFT_SUBSYS, "isid", context->isid, sizeof(context->isid)); } static int fill_tgt_context(char *id, struct boot_context *context) { int rc; rc = sysfs_get_str(id, IBFT_SUBSYS, "target-name", context->targetname, sizeof(context->targetname)); if (rc) return rc; rc = sysfs_get_str(id, IBFT_SUBSYS, "ip-addr", context->target_ipaddr, sizeof(context->target_ipaddr)); if (rc) return rc; /* * We can live without the rest of they do not exist. If we * failed to get them we will figure it out when we login. */ if (sysfs_get_int(id, IBFT_SUBSYS, "port", &context->target_port)) context->target_port = ISCSI_LISTEN_PORT; sysfs_get_str(id, IBFT_SUBSYS, "lun", context->lun, sizeof(context->lun)); sysfs_get_str(id, IBFT_SUBSYS, "chap-name", context->chap_name, sizeof(context->chap_name)); sysfs_get_str(id, IBFT_SUBSYS, "chap-secret", context->chap_password, sizeof(context->chap_password)); sysfs_get_str(id, IBFT_SUBSYS, "rev-chap-name", context->chap_name_in, sizeof(context->chap_name_in)); sysfs_get_str(id, IBFT_SUBSYS, "rev-chap-name-secret", context->chap_password_in, sizeof(context->chap_password_in)); return 0; } #define IBFT_SYSFS_FLAG_FW_SEL_BOOT 2 static int find_boot_flag(char *list[], ssize_t size, int *boot_idx) { int rc = ENODEV; int i, flag = 0; for (i = 0; i < size; i++, flag = -1) { rc = sysfs_get_int(list[i], IBFT_SUBSYS, "flags", &flag); if (rc) continue; if (flag & IBFT_SYSFS_FLAG_FW_SEL_BOOT) { *boot_idx = i; rc = 0; break; } rc = ENODEV; flag = 0; } return rc; } static void deallocate_lists(void) { int i; for (i = 0; i < nic_cnt; i++) free(nic_list[i]); nic_cnt = 0; for (i = 0; i < tgt_cnt; i++) free(target_list[i]); tgt_cnt = 0; } int fwparam_ibft_sysfs_boot_info(struct boot_context *context) { char initiator_dir[FILENAMESZ]; int rc = 1; int nic_idx = -1, tgt_idx = -1; memset(&initiator_dir, 0 , FILENAMESZ); snprintf(initiator_dir, FILENAMESZ, "%sinitiator", IBFT_SYSFS_ROOT); nic_cnt = 0; tgt_cnt = 0; if (file_exist(initiator_dir)) { /* Find the target's and the ethernet's */ rc = nftw(IBFT_SYSFS_ROOT, find_sysfs_dirs, 20, 1); /* Find wihch target and which ethernet have the boot flag set. */ rc = find_boot_flag(nic_list, nic_cnt, &nic_idx); if (rc) goto free; rc = find_boot_flag(target_list, tgt_cnt, &tgt_idx); if (rc) goto free; /* Fill in the context values */ rc = fill_nic_context(nic_list[nic_idx], context); rc |= fill_tgt_context(target_list[tgt_idx], context); fill_initiator_context(context); } free: deallocate_lists(); return rc; } int fwparam_ibft_sysfs_get_targets(struct list_head *list) { struct boot_context *context; int rc = 0, i, nic_idx, nic; char initiator_dir[FILENAMESZ]; memset(&initiator_dir, 0 , FILENAMESZ); snprintf(initiator_dir, FILENAMESZ, "%sinitiator", IBFT_SYSFS_ROOT); if (!file_exist(initiator_dir)) return ENODEV; nic_cnt = 0; tgt_cnt = 0; /* Find the target's and the ethernet's */ nftw(IBFT_SYSFS_ROOT, find_sysfs_dirs, 20, 1); for (i = 0; i < tgt_cnt; i++) { context = calloc(1, sizeof(*context)); if (!context) { rc = ENOMEM; break; } rc = fill_tgt_context(target_list[i], context); if (rc) break; rc = sysfs_get_int(target_list[i], IBFT_SUBSYS, "nic-assoc", &nic_idx); if (rc) break; for (nic = 0; nic < nic_cnt; nic++) { int id; rc = sysfs_get_int(nic_list[nic], IBFT_SUBSYS, "index", &id); if (!rc && (id == nic_idx)) break; } if (nic == nic_cnt) { printf("Invalid nic-assoc of %d. Max id %d.\n", nic_idx, nic_cnt); break; } rc = fill_nic_context(nic_list[nic], context); if (rc) break; fill_initiator_context(context); list_add_tail(&context->list, list); } if (rc) { if (context) free(context); fw_free_targets(list); } deallocate_lists(); return rc; } open-iscsi-2.0.873/utils/fwparam_ibft/fwparam_ppc.c000066400000000000000000000344351175631155400222310ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define _XOPEN_SOURCE 500 #include #include #include #include #include #include #include #include "fwparam.h" #include "fw_context.h" #include "iscsi_obp.h" #include "prom_parse.h" #include "sysdeps.h" #include "iscsi_err.h" void* yy_scan_string(const char *str); int yyparse(struct ofw_dev *ofwdev); #define BOOTPATH "/chosen/bootpath" #define DT_TOP "/proc/device-tree" #define LOCAL_MAC_FILE "/local-mac-address" static int devtree_offset; static char *bootpath_val; static int bytes_read; #define OFWDEV_MAX (10) static struct ofw_dev *ofwdevs[OFWDEV_MAX]; static char *niclist[OFWDEV_MAX]; static int nic_count; static int debug; static int dev_count; static void cp_param(char *dest, const char *name, struct ofw_dev *dev, enum obp_param item, int len) { if (dev->param[item]) strlcpy(dest, dev->param[item]->val, len); } static void cp_int_param(int *dest, const char *name, struct ofw_dev *dev, enum obp_param item) { if (dev->param[item]) *dest = strtol(dev->param[item]->val, NULL, 10); } static char *find_devtree(const char *filename) { char *devtree = strdup(filename); char *chop_at; struct stat dt_stat; int error; /* * What is the path to the device-tree? The only valid * directories to locate the property are under /aliases or * /chosen. */ chop_at = strstr(devtree, "/chosen"); if (!chop_at) chop_at = strstr(devtree, "/aliases"); if (!chop_at) { char *vdev = malloc(strlen(filename) + strlen("/vdevice") + 1); /* * test to see if there is /vdevice dir */ if (vdev) { sprintf(vdev, "%s%s", filename, "/vdevice"); error = stat(vdev, &dt_stat); free(vdev); if (error) { free(devtree); return NULL; } } } else devtree[chop_at - devtree] = 0; if (devtree) devtree_offset = strlen(devtree); return devtree; } /* * Take the path to the property under chosen, and swizzle to make that * the base for the device path discovered. */ static int locate_mac(const char *devtree, struct ofw_dev *ofwdev) { int error = 0; int mac_path_len = strlen(ofwdev->dev_path) + strlen(LOCAL_MAC_FILE) + 2; char *mac_file; int mac_fd; mac_path_len += strlen(devtree); mac_file = malloc(mac_path_len); if (!mac_file) { error = ENOMEM; fprintf(stderr, "%s: malloc , %s\n", __func__, strerror(errno)); goto lpm_bail; } snprintf(mac_file, mac_path_len, "%s%s%s", devtree, ofwdev->dev_path, LOCAL_MAC_FILE); mac_fd = open(mac_file, O_RDONLY); if (mac_fd < 0) { error = errno; fprintf(stderr, "%s: open %s, %s\n", __func__, mac_file, strerror(errno)); goto lpm_bail; } bytes_read = read(mac_fd, ofwdev->mac, 6); if (bytes_read != 6) { error = EIO; fprintf(stderr, "%s: read %s, %s\n", __func__, mac_file, strerror(errno)); goto lpm_bail; } free(mac_file); close(mac_fd); lpm_bail: return error; } const char *obp_qual_set(struct ofw_dev *ofwdev, const char *qual) { if (!strcmp("bootp", qual)) ofwdev->quals[ofwdev->qual_count++] = OBP_QUAL_BOOTP; else if (!strcmp("dhcpv6", qual)) ofwdev->quals[ofwdev->qual_count++] = OBP_QUAL_DHCPV6; else if (!strcmp("ipv6", qual)) ofwdev->quals[ofwdev->qual_count++] = OBP_QUAL_IPV6; else if (!strcmp("iscsi", qual)) { ofwdev->type = OFW_DT_ISCSI; ofwdev->quals[ofwdev->qual_count++] = OBP_QUAL_ISCSI; } else if (!strcmp("ping", qual)) ofwdev->quals[ofwdev->qual_count++] = OBP_QUAL_PING; else printf("%s: %s UNKNOWN\n", __func__, qual); return qual; } void add_obp_parm(struct ofw_dev *ofwdev, enum obp_param parm, const char *str) { int psz = sizeof(struct ofw_obp_param) + strlen(str); ofwdev->param[parm] = malloc(psz); if (ofwdev->param[parm] == NULL) { printf("%s: ENOMEM!\n", __func__); return; } memset(ofwdev->param[parm], 0, psz); ofwdev->param[parm]->len = psz; strcpy(ofwdev->param[parm]->val, str); } void obp_parm_addr(struct ofw_dev *ofwdev, const char *parm, const char *addr) { if (!strcmp("ciaddr", parm)) add_obp_parm(ofwdev, OBP_PARAM_CIADDR, addr); else if (!strcmp("dhcp", parm)) add_obp_parm(ofwdev, OBP_PARAM_DHCP, addr); else if (!strcmp("giaddr", parm)) add_obp_parm(ofwdev, OBP_PARAM_GIADDR, addr); else if (!strcmp("isns", parm)) add_obp_parm(ofwdev, OBP_PARAM_ISNS, addr); else if (!strcmp("siaddr", parm)) add_obp_parm(ofwdev, OBP_PARAM_SIADDR, addr); else if (!strcmp("slp", parm)) add_obp_parm(ofwdev, OBP_PARAM_SLP, addr); else if (!strcmp("subnet-mask", parm)) add_obp_parm(ofwdev, OBP_PARAM_SUBNET_MASK, addr); else printf("%s: %s UNKNOWN\n", __func__, parm); } void obp_parm_iqn(struct ofw_dev *ofwdev, const char *parm, const char *iqn) { if (!strcmp("itname", parm)) add_obp_parm(ofwdev, OBP_PARAM_ITNAME, iqn); else if (!strcmp("iname", parm)) add_obp_parm(ofwdev, OBP_PARAM_INAME, iqn); else printf("%s: %s UNKNOWN\n", __func__, parm); } void obp_parm_hexnum(struct ofw_dev *ofwdev, const char *parm, const char *numstr) { if (!strcmp("bootp-retries", parm)) add_obp_parm(ofwdev, OBP_PARAM_BOOTP_RETRIES, numstr); else if (!strcmp("tftp-retries", parm)) add_obp_parm(ofwdev, OBP_PARAM_TFTP_RETRIES, numstr); else if (!strcmp("iport", parm)) add_obp_parm(ofwdev, OBP_PARAM_IPORT, numstr); else if (!strcmp("ilun", parm)) add_obp_parm(ofwdev, OBP_PARAM_ILUN, numstr); else if (!strcmp("isid", parm)) add_obp_parm(ofwdev, OBP_PARAM_ISID, numstr); else printf("%s: %s UNKNOWN <%s>\n", __func__, parm, numstr); } void obp_parm_str(struct ofw_dev *ofwdev, const char *parm, const char *str) { if (!strcmp("filename", parm)) add_obp_parm(ofwdev, OBP_PARAM_FILENAME, str); else if (!strcmp("ichapid", parm)) add_obp_parm(ofwdev, OBP_PARAM_ICHAPID, str); else if (!strcmp("ichappw", parm)) add_obp_parm(ofwdev, OBP_PARAM_ICHAPPW, str); else if (!strcmp("chapid", parm)) add_obp_parm(ofwdev, OBP_PARAM_CHAPID, str); else if (!strcmp("chappw", parm)) add_obp_parm(ofwdev, OBP_PARAM_CHAPPW, str); else printf("%s: %s UNKNOWN <%s>\n", __func__, parm, str); } void yyerror(struct ofw_dev *ofwdev, const char *msg) { fprintf(stderr, "%s: error in <%s> at l%d.c%d\n", "fwparam_ppc", ofwdev->prop_path, yylloc.last_line, yylloc.last_column); } static int parse_params(const char *buf, struct ofw_dev *ofwdev) { int error = 0; #if YYDEBUG yydebug = 1; #endif if (yy_scan_string(buf)) error = yyparse(ofwdev); return error; } static int find_file(const char *filename) { int error, fd; struct stat bootpath_stat; error = stat(filename, &bootpath_stat); if (error < 0) { fprintf(stderr, "%s: stat %s, %s\n", __func__, filename, strerror(errno)); return error; } bootpath_val = malloc(bootpath_stat.st_size); if (!bootpath_val) { error = ENOMEM; fprintf(stderr, "%s: Could not open %s: %s (%d)\n", __func__, filename, strerror(error), error); return -1; } fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "%s: Could not open %s: %s (%d)\n", __func__, filename, strerror(errno), errno); free(bootpath_val); return -1; } bytes_read = read(fd, bootpath_val, bootpath_stat.st_size); close(fd); free(bootpath_val); if (bytes_read != bootpath_stat.st_size) { fprintf(stderr, "%s: Could not open %s: %s (%d)\n", __func__, filename, strerror(EIO), EIO); return -1; } return 1; } static int find_nics(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw) { if (tflag == FTW_D && (strstr(fpath + ftw->base, "iscsi-toe") || strstr(fpath + ftw->base, "ethernet"))) { if (nic_count < OFWDEV_MAX) niclist[nic_count++] = strdup(fpath + devtree_offset); } return 0; } int nic_cmp(const char **a, const char **b) { return strcmp(*a, *b); } static int find_initiator(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw) { struct ofw_dev *dev; if (tflag == FTW_F && (strstr(fpath + ftw->base, "/aliases/iscsi-disk"))) { if (dev_count < OFWDEV_MAX) { ofwdevs[dev_count++] = dev = calloc(sizeof(struct ofw_dev), 1); dev->prop_path = strdup(fpath + devtree_offset); } } return 0; } static int loop_devs(const char *devtree) { int error; int i; char prefix[256]; nic_count = 0; error = nftw(devtree, find_nics, 20, 0); if (error) return error; /* * Sort the nics into "natural" order. The proc fs * device-tree has them in somewhat random, or reversed order. */ qsort(niclist, nic_count, sizeof(char *), (__compar_fn_t)nic_cmp); snprintf(prefix, sizeof(prefix), "%s/%s", devtree, "aliases"); dev_count = 0; error = nftw(prefix, find_initiator, 20, 0); if (error) return error; for (i = 0; i < dev_count; i++) { snprintf(prefix, sizeof(prefix), "%s%s", devtree, ofwdevs[i]->prop_path); if (find_file(prefix) > 0) { error = parse_params(bootpath_val, ofwdevs[i]); if (!error) error = locate_mac(devtree, ofwdevs[i]); } } return error; } #define set_context(fld,abrv,item) \ cp_param(context->fld, (abrv), ofwdev, (item), sizeof(context->fld)) #define set_int_context(fld,abrv,item) \ cp_int_param(&context->fld, (abrv), ofwdev, (item)) static void fill_context(struct boot_context *context, struct ofw_dev *ofwdev) { int ndx; memset(context, 0, sizeof(*context)); set_context(initiatorname, "NAME", OBP_PARAM_ITNAME); snprintf(context->mac, sizeof(context->mac), "%02x:%02x:%02x:%02x:%02x:%02x", ofwdev->mac[0], ofwdev->mac[1], ofwdev->mac[2], ofwdev->mac[3], ofwdev->mac[4], ofwdev->mac[5]); /* * nic parameters */ for (ndx = 0; ndx < nic_count; ndx++) { if (!strcmp(niclist[ndx], ofwdev->dev_path)) { snprintf(context->iface, sizeof(context->iface), "eth%d", ndx); break; } } set_context(ipaddr, "IPADDR", OBP_PARAM_CIADDR); set_context(mask, "MASK", OBP_PARAM_SUBNET_MASK); /* * target parameters */ set_context(target_ipaddr, "IPADDR", OBP_PARAM_SIADDR); set_int_context(target_port, "PORT", OBP_PARAM_IPORT); set_context(lun, "LUN", OBP_PARAM_ILUN); set_context(targetname, "NAME", OBP_PARAM_INAME); set_context(isid, "ISID", OBP_PARAM_ISID); /* * chap stuff is always associated with the target */ set_context(chap_name, "CHAP_NAME", OBP_PARAM_ICHAPID); set_context(chap_password, "CHAP_PASSWORD", OBP_PARAM_ICHAPPW); set_context(chap_name_in, "CHAP_NAME_IN", OBP_PARAM_CHAPID); set_context(chap_password_in, "CHAP_PASSWORD_IN", OBP_PARAM_CHAPPW); } int fwparam_ppc_boot_info(struct boot_context *context) { char filename[FILENAMESZ]; int error; char *devtree; /* * For powerpc, our operations are fundamentally to locate * either the one boot target (the singleton disk), or to find * the nics that support iscsi boot. The only nics in IBM * systems that can support iscsi are the ones that provide * the appropriate FCODE with a load method. */ memset(filename, 0, FILENAMESZ); snprintf(filename, FILENAMESZ, "%s%s", DT_TOP, BOOTPATH); if (debug) fprintf(stderr, "%s: file:%s; debug:%d\n", __func__, filename, debug); devtree = find_devtree(filename); if (!devtree) return ISCSI_ERR_INVAL; /* * Always search the device-tree to find the capable nic devices. */ error = loop_devs(devtree); if (error) goto free_devtree; if (find_file(filename) < 1) error = ISCSI_ERR_NO_OBJS_FOUND; else { if (debug) printf("%s:\n%s\n\n", filename, bootpath_val); /* * We find *almost* everything we need in the * bootpath, save the mac-address. */ if (!strstr(bootpath_val, "iscsi")) { error = ISCSI_ERR_INVAL; goto free_devtree; } ofwdevs[0] = calloc(1, sizeof(struct ofw_dev)); if (!ofwdevs[0]) { error = ISCSI_ERR_NOMEM; goto free_devtree; } error = parse_params(bootpath_val, ofwdevs[0]); if (!error) error = locate_mac(devtree, ofwdevs[0]); if (!error) { context = calloc(1, sizeof(*context)); if (!context) error = ISCSI_ERR_NOMEM; else fill_context(context, ofwdevs[0]); } free(ofwdevs[0]); } free_devtree: free(devtree); return error; } /* * Due to lack of time this is just fwparam_ppc_boot_info which * adds the target used for boot to the list. It does not add * all possible targets (IBM please add). */ int fwparam_ppc_get_targets(struct list_head *list) { char filename[FILENAMESZ]; struct boot_context *context; int error; char *devtree; /* * For powerpc, our operations are fundamentally to locate * either the one boot target (the singleton disk), or to find * the nics that support iscsi boot. The only nics in IBM * systems that can support iscsi are the ones that provide * the appropriate FCODE with a load method. */ memset(filename, 0, FILENAMESZ); snprintf(filename, FILENAMESZ, "%s%s", DT_TOP, BOOTPATH); if (debug) fprintf(stderr, "%s: file:%s; debug:%d\n", __func__, filename, debug); devtree = find_devtree(filename); if (!devtree) return ISCSI_ERR_INVAL; /* * Always search the device-tree to find the capable nic devices. */ error = loop_devs(devtree); if (error) goto free_devtree; if (find_file(filename) < 1) error = ISCSI_ERR_NO_OBJS_FOUND; else { if (debug) printf("%s:\n%s\n\n", filename, bootpath_val); /* * We find *almost* everything we need in the * bootpath, save the mac-address. */ if (!strstr(bootpath_val, "iscsi")) { error = ISCSI_ERR_INVAL; goto free_devtree; } ofwdevs[0] = calloc(1, sizeof(struct ofw_dev)); if (!ofwdevs[0]) { error = ISCSI_ERR_NOMEM; goto free_devtree; } error = parse_params(bootpath_val, ofwdevs[0]); if (!error) error = locate_mac(devtree, ofwdevs[0]); if (!error) { context = calloc(1, sizeof(*context)); if (!context) error = ISCSI_ERR_NOMEM; else { fill_context(context, ofwdevs[0]); list_add_tail(&context->list, list); } } free(ofwdevs[0]); } free_devtree: free(devtree); return error; } open-iscsi-2.0.873/utils/fwparam_ibft/fwparam_sysfs.c000066400000000000000000000274471175631155400226230ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Konrad Rzeszutek * Copyright (C) Red Hat, Inc. All rights reserved. 2008 - 2010 * Copyright (C) Mike Christie 2008 - 2010 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define _XOPEN_SOURCE 500 #define _SVID_SOURCE #include #include #include #include #include #include #include #include #include #include #include "sysfs.h" #include "fw_context.h" #include "fwparam.h" #include "sysdeps.h" #include "iscsi_net_util.h" #include "iscsi_err.h" #define ISCSI_BOOT_MAX 255 #define IBFT_SYSFS_ROOT "/sys/firmware/ibft/" #define IBFT_SUBSYS "ibft" #define ISCSI_LLD_ROOT "/sys/firmware/" #define ISCSI_LLD_SUBSYS_PREFIX "iscsi_boot" static char *target_list[ISCSI_BOOT_MAX]; static char *nic_list[ISCSI_BOOT_MAX]; static int nic_cnt; static int tgt_cnt; static int file_exist(const char *file) { struct stat bootpath_stat; return !stat(file, &bootpath_stat); } /* * Finds the etherrnetX and targetX under the sysfs directory. */ static int find_sysfs_dirs(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw) { if (tflag == FTW_D && (strstr(fpath + ftw->base, "target"))) { if (tgt_cnt == ISCSI_BOOT_MAX) { printf("Too many targets found in iSCSI boot data." "Max number of targets %d\n", ISCSI_BOOT_MAX); return 0; } target_list[tgt_cnt++] = strdup(strstr(fpath, "target")); } if (tflag == FTW_D && (strstr(fpath + ftw->base, "ethernet"))) { if (nic_cnt == ISCSI_BOOT_MAX) { printf("Too many nics found in iSCSI boot data." "Max number of nics %d\n", ISCSI_BOOT_MAX); return 0; } nic_list[nic_cnt++] = strdup(strstr(fpath, "ethernet")); } return 0; } static int get_iface_from_device(char *id, struct boot_context *context) { char dev_dir[FILENAMESZ]; int rc = ENODEV; DIR *dirfd; struct dirent *dent; memset(dev_dir, 0, FILENAMESZ); snprintf(dev_dir, FILENAMESZ, IBFT_SYSFS_ROOT"/%s/device", id); if (!file_exist(dev_dir)) return 0; dirfd = opendir(dev_dir); if (!dirfd) return errno; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..") || strncmp(dent->d_name, "net:", 4)) continue; if (!strncmp(dent->d_name, "net:", 4)) { if ((strlen(dent->d_name) - 4) > (sizeof(context->iface) - 1)) { rc = EINVAL; printf("Net device %s too big for iface " "buffer.\n", dent->d_name); break; } if (sscanf(dent->d_name, "net:%s", context->iface) != 1) rc = EINVAL; rc = 0; break; } else { printf("Could not read ethernet to net link.\n"); rc = EOPNOTSUPP; break; } } closedir(dirfd); if (rc != ENODEV) return rc; /* If not found try again with newer kernel networkdev sysfs layout */ strlcat(dev_dir, "/net", FILENAMESZ); if (!file_exist(dev_dir)) return rc; dirfd = opendir(dev_dir); if (!dirfd) return errno; while ((dent = readdir(dirfd))) { if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; /* Take the first "regular" directory entry */ if (strlen(dent->d_name) > (sizeof(context->iface) - 1)) { rc = EINVAL; printf("Net device %s too big for iface buffer.\n", dent->d_name); break; } strcpy(context->iface, dent->d_name); rc = 0; break; } closedir(dirfd); return rc; } /* * Routines to fill in the context values. */ static int fill_nic_context(char *subsys, char *id, struct boot_context *context) { int rc; rc = sysfs_get_str(id, subsys, "mac", context->mac, sizeof(context->mac)); if (rc) return rc; /* * Some offload cards like bnx2i use different MACs for the net and * iscsi functions, so we have to follow the sysfs links. * * Other ibft implementations may not be tied to a pci function, * so there will not be any device/net link, so we drop down to * the MAC matching. * * And finally, some cards like be2iscsi and qla4xxx do not have * any linux network subsys representation. These hosts will * not have the ibft subsys. Instead the subsys is the scsi host * number. */ if (!strcmp(IBFT_SUBSYS, subsys)) { rc = get_iface_from_device(id, context); if (rc) { rc = net_get_netdev_from_hwaddress(context->mac, context->iface); if (rc) return rc; } } else strlcpy(context->scsi_host_name, subsys, sizeof(context->scsi_host_name)); sysfs_get_str(id, subsys, "ip-addr", context->ipaddr, sizeof(context->ipaddr)); sysfs_get_str(id, subsys, "vlan", context->vlan, sizeof(context->vlan)); sysfs_get_str(id, subsys, "subnet-mask", context->mask, sizeof(context->mask)); sysfs_get_str(id, subsys, "gateway", context->gateway, sizeof(context->gateway)); sysfs_get_str(id, subsys, "primary-dns", context->primary_dns, sizeof(context->primary_dns)); sysfs_get_str(id, subsys, "secondary-dns", context->secondary_dns, sizeof(context->secondary_dns)); sysfs_get_str(id, subsys, "dhcp", context->dhcp, sizeof(context->dhcp)); return 0; } static void fill_initiator_context(char *subsys, struct boot_context *context) { sysfs_get_str("initiator", subsys, "initiator-name", context->initiatorname, sizeof(context->initiatorname)); sysfs_get_str("initiator", subsys, "isid", context->isid, sizeof(context->isid)); } static int fill_tgt_context(char *subsys, char *id, struct boot_context *context) { int rc; rc = sysfs_get_str(id, subsys, "target-name", context->targetname, sizeof(context->targetname)); if (rc) return rc; rc = sysfs_get_str(id, subsys, "ip-addr", context->target_ipaddr, sizeof(context->target_ipaddr)); if (rc) return rc; /* * We can live without the rest of they do not exist. If we * failed to get them we will figure it out when we login. */ if (sysfs_get_int(id, subsys, "port", &context->target_port)) context->target_port = ISCSI_LISTEN_PORT; sysfs_get_str(id, subsys, "lun", context->lun, sizeof(context->lun)); sysfs_get_str(id, subsys, "chap-name", context->chap_name, sizeof(context->chap_name)); sysfs_get_str(id, subsys, "chap-secret", context->chap_password, sizeof(context->chap_password)); sysfs_get_str(id, subsys, "rev-chap-name", context->chap_name_in, sizeof(context->chap_name_in)); sysfs_get_str(id, subsys, "rev-chap-name-secret", context->chap_password_in, sizeof(context->chap_password_in)); return 0; } #define IBFT_SYSFS_FLAG_FW_SEL_BOOT 2 static int find_boot_flag(char *subsys, char *list[], ssize_t size, int *boot_idx) { int rc = ENODEV; int i, flag = 0; for (i = 0; i < size; i++, flag = -1) { rc = sysfs_get_int(list[i], subsys, "flags", &flag); if (rc) continue; if (flag & IBFT_SYSFS_FLAG_FW_SEL_BOOT) { *boot_idx = i; rc = 0; break; } rc = ENODEV; flag = 0; } return rc; } static void deallocate_lists(void) { int i; for (i = 0; i < nic_cnt; i++) free(nic_list[i]); nic_cnt = 0; for (i = 0; i < tgt_cnt; i++) free(target_list[i]); tgt_cnt = 0; } static int get_boot_info(struct boot_context *context, char *rootdir, char *subsys) { char initiator_dir[FILENAMESZ]; int rc = ENODEV; int nic_idx = -1, tgt_idx = -1; memset(&initiator_dir, 0 , FILENAMESZ); snprintf(initiator_dir, FILENAMESZ, "%sinitiator", rootdir); nic_cnt = 0; tgt_cnt = 0; if (file_exist(initiator_dir)) { /* Find the target's and the ethernet's */ rc = nftw(rootdir, find_sysfs_dirs, 20, 1); /* Find wihch target and which ethernet have the boot flag set. */ rc = find_boot_flag(subsys, nic_list, nic_cnt, &nic_idx); if (rc) goto free; rc = find_boot_flag(subsys, target_list, tgt_cnt, &tgt_idx); if (rc) goto free; /* Fill in the context values */ rc = fill_nic_context(subsys, nic_list[nic_idx], context); rc |= fill_tgt_context(subsys, target_list[tgt_idx], context); fill_initiator_context(subsys, context); } free: deallocate_lists(); return rc; } int fwparam_sysfs_boot_info(struct boot_context *context) { struct dirent *dent; DIR *dirfd; int rc = 0; if (!get_boot_info(context, IBFT_SYSFS_ROOT, IBFT_SUBSYS)) return 0; /* * We could have multiple iscsi llds and each lld could have * multiple targets/ethernet ports */ dirfd = opendir(ISCSI_LLD_ROOT); if (!dirfd) return ISCSI_ERR_SYSFS_LOOKUP; while ((dent = readdir(dirfd))) { char lld_root[FILENAMESZ]; memset(&lld_root, 0 , FILENAMESZ); if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; if (strncmp(dent->d_name, ISCSI_LLD_SUBSYS_PREFIX, 10)) continue; snprintf(lld_root, FILENAMESZ, ISCSI_LLD_ROOT"%s/", dent->d_name); if (!get_boot_info(context, lld_root, dent->d_name)) goto done; } rc = ISCSI_ERR_NO_OBJS_FOUND; done: closedir(dirfd); return rc; } static int get_targets(struct list_head *list, char *rootdir, char *subsys) { struct boot_context *context; int rc = 0, i, nic_idx, nic; char initiator_dir[FILENAMESZ]; memset(&initiator_dir, 0 , FILENAMESZ); snprintf(initiator_dir, FILENAMESZ, "%sinitiator", rootdir); if (!file_exist(initiator_dir)) return ENODEV; nic_cnt = 0; tgt_cnt = 0; /* Find the target's and the ethernet's */ nftw(rootdir, find_sysfs_dirs, 20, 1); for (i = 0; i < tgt_cnt; i++) { context = calloc(1, sizeof(*context)); if (!context) { rc = ENOMEM; break; } rc = fill_tgt_context(subsys, target_list[i], context); if (rc) goto cleanup; rc = sysfs_get_int(target_list[i], subsys, "nic-assoc", &nic_idx); if (rc) goto cleanup; for (nic = 0; nic < nic_cnt; nic++) { int id; rc = sysfs_get_int(nic_list[nic], subsys, "index", &id); if (!rc && (id == nic_idx)) break; } if (nic == nic_cnt) { printf("Invalid nic-assoc of %d. Max id %d.\n", nic_idx, nic_cnt); goto cleanup; } rc = fill_nic_context(subsys, nic_list[nic], context); if (rc) goto cleanup; fill_initiator_context(subsys, context); list_add_tail(&context->list, list); continue; cleanup: free(context); context = NULL; } if (rc) { if (context) free(context); /* * If there are some valid targets return them. Most likely, * the driver/ibft-implementation reported partial info * for targets/initiators that were not used for boot. */ if (!list_empty(list)) rc = 0; } deallocate_lists(); return rc; } int fwparam_sysfs_get_targets(struct list_head *list) { struct dirent *dent; DIR *dirfd; int rc = 0; /* ibft only has one instance */ get_targets(list, IBFT_SYSFS_ROOT, IBFT_SUBSYS); /* * We could have multiple iscsi llds and each lld could have * multiple targets/ethernet ports */ dirfd = opendir(ISCSI_LLD_ROOT); if (!dirfd) { rc = ISCSI_ERR_SYSFS_LOOKUP; goto done; } while ((dent = readdir(dirfd))) { char lld_root[FILENAMESZ]; memset(&lld_root, 0 , FILENAMESZ); if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; if (strncmp(dent->d_name, ISCSI_LLD_SUBSYS_PREFIX, 10)) continue; snprintf(lld_root, FILENAMESZ, ISCSI_LLD_ROOT"%s/", dent->d_name); get_targets(list, lld_root, dent->d_name); } closedir(dirfd); done: if (!rc && list_empty(list)) rc = ISCSI_ERR_NO_OBJS_FOUND; if (rc) fw_free_targets(list); return rc; } open-iscsi-2.0.873/utils/fwparam_ibft/iscsi_obp.h000066400000000000000000000061171175631155400217050ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef ISCSI_OBP_H_ #define ISCSI_OBP_H_ enum ofw_dev_type { OFW_DT_NONE, OFW_DT_BLOCK, OFW_DT_NETWORK, OFW_DT_ISCSI, }; enum obp_tftp_qual { OBP_QUAL_NONE, OBP_QUAL_BOOTP, OBP_QUAL_DHCPV6, OBP_QUAL_IPV6, OBP_QUAL_ISCSI, OBP_QUAL_PING, OBP_QUAL_COUNT, /* Numnber of defined OBP qualifiers */ }; enum obp_param { /* * Defined iscsi boot parameters. */ OBP_PARAM_NONE, OBP_PARAM_BLKSIZE, /* default is 512 */ OBP_PARAM_BOOTP_RETRIES, /* default 5 */ OBP_PARAM_CHAPID, /* target chap id */ OBP_PARAM_CHAPPW, /* target chap password */ OBP_PARAM_CIADDR, /* client (my) ip addr */ OBP_PARAM_DHCP, /* dhcp server address */ OBP_PARAM_FILENAME, /* boot filename */ OBP_PARAM_GIADDR, /* gateway addr */ OBP_PARAM_ICHAPID, /* initiator chapid */ OBP_PARAM_ICHAPPW, /* initiator chap password */ OBP_PARAM_ILUN, /* misnomer, really the target lun */ OBP_PARAM_INAME, /* NB: target iqn */ OBP_PARAM_IPORT, /* initiator port, defaults to 3260 */ OBP_PARAM_ISID, /* session id */ OBP_PARAM_ISNS, /* sns server address */ OBP_PARAM_ITNAME, /* NB: Initiator iqn */ OBP_PARAM_SIADDR, /* iscsi server ip address. */ OBP_PARAM_SLP, /* slp server address */ OBP_PARAM_SUBNET_MASK, OBP_PARAM_TFTP_RETRIES, /* default 5 */ OBP_PARAM_TIMEOUT, /* ping timeout period. */ OBP_PARAM_COUNT, /* number of defined OBP_PARAMs */ }; struct ofw_obp_param { unsigned char len; /* length of value string. */ char val[1]; /* string value from the property */ }; struct ofw_dev { char *prop_path; /* where we found these properties. */ enum ofw_dev_type type; /* known type of boot device. */ int qual_count; /* count of qualifiers. */ enum obp_tftp_qual quals[OBP_QUAL_COUNT]; struct ofw_obp_param *param[OBP_PARAM_COUNT]; int cfg_part; /* boot partition number. */ char *dev_path; /* path to this ofw device. */ unsigned char mac[6]; /* The binary mac address. */ }; const char *obp_qual_set(struct ofw_dev *ofwdev, const char *qual); void add_obp_parm(struct ofw_dev *ofwdev, enum obp_param parm, const char *str); void obp_parm_addr(struct ofw_dev *ofwdev, const char *parm, const char *addr); void obp_parm_iqn(struct ofw_dev *ofwdev, const char *parm, const char *iqn); void obp_parm_hexnum(struct ofw_dev *ofwdev, const char *parm, const char *numstr); void obp_parm_str(struct ofw_dev *ofwdev, const char *parm, const char *str); #endif /* ISCSI_OBP_H_ */ open-iscsi-2.0.873/utils/fwparam_ibft/prom_lex.c000066400000000000000000002174061175631155400215600ustar00rootroot00000000000000 #line 3 "" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char yytext[]; static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ if ( yyleng >= YYLMAX ) \ YY_FATAL_ERROR( "token too large, exceeds YYLMAX" ); \ yy_flex_strncpy( yytext, (yytext_ptr), yyleng + 1 ); \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 17 #define YY_END_OF_BUFFER 18 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[444] = { 0, 0, 0, 18, 16, 15, 15, 12, 12, 16, 12, 12, 12, 12, 12, 12, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 15, 0, 12, 12, 14, 0, 0, 0, 12, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 12, 12, 14, 7, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 3, 0, 9, 6, 0, 0, 5, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 8, 0, 13, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 2, 8, 13, 1, 0, 9, 0, 0, 0, 0, 0, 0, 8, 13, 0, 9, 0, 0, 10, 0, 0, 0, 13, 0, 9, 0, 0, 0, 0, 0, 13, 0, 9, 0, 0, 0, 13, 0, 9, 0, 0, 13, 9, 0, 0, 13, 9, 13, 9, 13, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 1, 6, 6, 7, 6, 6, 6, 8, 6, 6, 6, 9, 1, 1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 1, 12, 1, 1, 1, 1, 13, 14, 15, 16, 17, 18, 19, 20, 21, 11, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 11, 11, 35, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[36] = { 0, 1, 1, 1, 2, 3, 4, 4, 4, 5, 4, 2, 6, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } ; static yyconst flex_int16_t yy_base[680] = { 0, 0, 0, 1198, 1199, 34, 36, 35, 1192, 0, 39, 40, 41, 47, 42, 44, 29, 67, 1176, 1182, 1179, 1180, 86, 1174, 1161, 1174, 51, 69, 73, 1184, 0, 1175, 1165, 1160, 43, 1172, 1171, 51, 1168, 1152, 1161, 1157, 1166, 1163, 1162, 1156, 1158, 1142, 1160, 25, 1147, 85, 1146, 1153, 1139, 1147, 1133, 1135, 1135, 1199, 1151, 1136, 1148, 1130, 1146, 1142, 80, 1153, 1152, 0, 1199, 1126, 1124, 1128, 1126, 1136, 1199, 1124, 1128, 1132, 1131, 1131, 1116, 1132, 1119, 1119, 1113, 1133, 1135, 1109, 1122, 1107, 1123, 1122, 1130, 1112, 1119, 1110, 1114, 1199, 1104, 1101, 1094, 97, 106, 0, 1105, 42, 1101, 94, 1108, 1090, 1093, 1096, 1104, 1098, 1091, 1100, 1085, 1199, 0, 1094, 1090, 1099, 1086, 1095, 1093, 1105, 1087, 117, 1102, 0, 1071, 1076, 104, 1088, 1069, 1073, 1093, 1075, 1086, 1069, 1199, 99, 0, 1093, 1079, 1069, 1199, 1065, 1062, 1063, 1076, 121, 125, 0, 1073, 1070, 1059, 1056, 1069, 1061, 1068, 1049, 0, 120, 1056, 1077, 1063, 1062, 131, 1073, 0, 1047, 1059, 1055, 1043, 1056, 0, 1046, 1050, 1044, 1038, 1044, 1036, 1199, 134, 0, 1199, 1035, 0, 1039, 1034, 1046, 1046, 1048, 1031, 1199, 0, 1030, 0, 1027, 1035, 1199, 1039, 1025, 1033, 0, 1032, 0, 1039, 137, 1018, 1028, 1032, 0, 1031, 0, 1018, 1025, 1015, 0, 1014, 0, 145, 142, 0, 0, 120, 132, 0, 0, 0, 0, 1199, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1199, 1199, 149, 152, 156, 159, 163, 144, 166, 143, 170, 142, 174, 131, 178, 115, 182, 112, 186, 92, 190, 89, 194, 87, 198, 85, 202, 67, 206, 56, 210, 214, 218, 222, 226, 230, 234, 238, 242, 246, 250, 254, 258, 262, 266, 270, 274, 278, 282, 286, 290, 294, 298, 302, 306, 310, 314, 318, 322, 326, 330, 334, 338, 342, 346, 350, 354, 358, 362, 366, 370, 374, 378, 382, 386, 390, 394, 398, 402, 406, 410, 414, 418, 422, 426, 430, 434, 438, 442, 446, 450, 454, 458, 462, 466, 470, 474, 478, 482, 486, 490, 494, 498, 502, 506, 510, 514, 518, 522, 526, 530, 534, 538, 542, 546, 550, 554, 558, 562, 566, 570, 574, 578, 582, 586, 590, 594, 598, 602, 606, 610, 614, 618, 622, 626, 630, 634, 638, 642, 646, 650, 654, 658, 662, 666, 670, 674, 678, 682, 686, 690, 694, 698, 702, 706, 710, 714, 718, 722, 726, 730, 734, 738, 742, 746, 750, 754, 758, 762, 766, 770, 774, 778, 782, 786, 790, 794, 798, 802, 806, 810, 814, 818, 822, 826, 830, 834, 838, 842, 846, 850, 854, 858, 862, 866, 870, 874, 878, 882, 886, 890, 894, 898, 902, 906, 910, 914, 918, 922, 926, 930, 934, 938, 942, 946, 950, 954, 958, 962, 966, 970, 974, 978, 982, 986, 990, 994, 998, 1002, 1006, 1010, 1014, 1018, 1022, 1026, 1030, 1034, 1038 } ; static yyconst flex_int16_t yy_def[680] = { 0, 443, 1, 443, 443, 443, 443, 444, 444, 445, 444, 444, 444, 444, 444, 444, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 446, 446, 447, 443, 443, 443, 446, 443, 443, 446, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 448, 448, 447, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 449, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 450, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 451, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 452, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 453, 443, 443, 443, 443, 443, 443, 443, 443, 454, 443, 443, 443, 443, 443, 443, 443, 455, 443, 443, 443, 443, 443, 456, 443, 443, 443, 443, 443, 443, 443, 443, 457, 443, 443, 458, 443, 443, 443, 443, 443, 443, 443, 459, 443, 460, 443, 443, 443, 443, 443, 443, 461, 443, 462, 443, 443, 443, 443, 443, 463, 443, 464, 443, 443, 443, 465, 443, 466, 443, 443, 467, 468, 443, 443, 469, 470, 471, 472, 443, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 443, 0, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443 } ; static yyconst flex_int16_t yy_nxt[1235] = { 0, 4, 5, 6, 4, 4, 7, 7, 7, 4, 8, 4, 9, 10, 11, 12, 13, 14, 15, 16, 4, 17, 4, 18, 4, 19, 4, 20, 4, 21, 22, 23, 24, 25, 4, 4, 26, 26, 26, 26, 27, 28, 28, 28, 443, 443, 443, 443, 443, 443, 42, 86, 443, 26, 26, 133, 443, 34, 87, 43, 234, 35, 36, 32, 37, 41, 33, 38, 39, 134, 31, 232, 73, 40, 44, 66, 66, 66, 27, 67, 67, 67, 45, 46, 76, 103, 104, 104, 104, 230, 47, 226, 48, 221, 49, 50, 215, 51, 52, 57, 89, 58, 59, 129, 129, 129, 90, 60, 158, 61, 91, 103, 130, 130, 130, 135, 207, 159, 62, 198, 162, 136, 153, 154, 154, 154, 163, 170, 170, 170, 153, 171, 171, 171, 179, 187, 180, 186, 186, 186, 197, 197, 197, 203, 203, 203, 172, 155, 131, 188, 188, 181, 29, 29, 30, 30, 30, 229, 30, 68, 68, 69, 69, 69, 228, 69, 105, 105, 144, 144, 144, 144, 164, 164, 164, 164, 178, 178, 178, 178, 190, 190, 190, 190, 200, 200, 200, 200, 209, 209, 209, 209, 217, 217, 217, 217, 223, 223, 223, 223, 227, 227, 227, 227, 231, 231, 231, 231, 233, 233, 233, 233, 235, 235, 235, 235, 236, 236, 236, 236, 237, 237, 237, 237, 238, 238, 238, 238, 239, 239, 239, 239, 240, 240, 240, 240, 241, 241, 241, 241, 242, 242, 242, 242, 243, 243, 243, 243, 244, 244, 244, 244, 245, 245, 245, 245, 246, 246, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249, 250, 250, 250, 250, 251, 251, 251, 251, 252, 252, 252, 252, 253, 253, 253, 253, 254, 254, 254, 254, 255, 255, 255, 255, 256, 256, 256, 256, 257, 257, 257, 257, 258, 258, 258, 258, 259, 259, 259, 259, 260, 260, 260, 260, 261, 261, 261, 261, 262, 262, 262, 262, 263, 263, 263, 263, 264, 264, 264, 264, 265, 265, 265, 265, 266, 266, 266, 266, 267, 267, 267, 267, 268, 268, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 274, 274, 274, 274, 275, 275, 275, 275, 276, 276, 276, 276, 277, 277, 277, 277, 278, 278, 278, 278, 279, 279, 279, 279, 280, 280, 280, 280, 281, 281, 281, 281, 282, 282, 282, 282, 283, 283, 283, 283, 284, 284, 284, 284, 285, 285, 285, 285, 286, 286, 286, 286, 287, 287, 287, 287, 288, 288, 288, 288, 289, 289, 289, 289, 290, 290, 290, 290, 291, 291, 291, 291, 292, 292, 292, 292, 293, 293, 293, 293, 294, 294, 294, 294, 295, 295, 295, 295, 296, 296, 296, 296, 297, 297, 297, 297, 298, 298, 298, 298, 299, 299, 299, 299, 300, 300, 300, 300, 301, 301, 301, 301, 302, 302, 302, 302, 303, 303, 303, 303, 304, 304, 304, 304, 305, 305, 305, 305, 306, 306, 306, 306, 307, 307, 307, 307, 308, 308, 308, 308, 309, 309, 309, 309, 310, 310, 310, 310, 311, 311, 311, 311, 312, 312, 312, 312, 313, 313, 313, 313, 314, 314, 314, 314, 315, 315, 315, 315, 316, 316, 316, 316, 317, 317, 317, 317, 318, 318, 318, 318, 319, 319, 319, 319, 320, 320, 320, 320, 321, 321, 321, 321, 322, 322, 322, 322, 323, 323, 323, 323, 324, 324, 324, 324, 325, 325, 325, 325, 326, 326, 326, 326, 327, 327, 327, 327, 328, 328, 328, 328, 329, 329, 329, 329, 330, 330, 330, 330, 331, 331, 331, 331, 332, 332, 332, 332, 333, 333, 333, 333, 334, 334, 334, 334, 335, 335, 335, 335, 336, 336, 336, 336, 337, 337, 337, 337, 338, 338, 338, 338, 339, 339, 339, 339, 340, 340, 340, 340, 341, 341, 341, 341, 342, 342, 342, 342, 343, 343, 343, 343, 344, 344, 344, 344, 345, 345, 345, 345, 346, 346, 346, 346, 347, 347, 347, 347, 348, 348, 348, 348, 349, 349, 349, 349, 350, 350, 350, 350, 351, 351, 351, 351, 352, 352, 352, 352, 353, 353, 353, 353, 354, 354, 354, 354, 355, 355, 355, 355, 356, 356, 356, 356, 357, 357, 357, 357, 358, 358, 358, 358, 359, 359, 359, 359, 360, 360, 360, 360, 361, 361, 361, 361, 362, 362, 362, 362, 363, 363, 363, 363, 364, 364, 364, 364, 365, 365, 365, 365, 366, 366, 366, 366, 367, 367, 367, 367, 368, 368, 368, 368, 369, 369, 369, 369, 370, 370, 370, 370, 371, 371, 371, 371, 372, 372, 372, 372, 373, 373, 373, 373, 374, 374, 374, 374, 375, 375, 375, 375, 376, 376, 376, 376, 377, 377, 377, 377, 378, 378, 378, 378, 379, 379, 379, 379, 380, 380, 380, 380, 381, 381, 381, 381, 382, 382, 382, 382, 383, 383, 383, 383, 384, 384, 384, 384, 385, 385, 385, 385, 386, 386, 386, 386, 387, 387, 387, 387, 388, 388, 388, 388, 389, 389, 389, 389, 390, 390, 390, 390, 391, 391, 391, 391, 392, 392, 392, 392, 393, 393, 393, 393, 394, 394, 394, 394, 395, 395, 395, 395, 396, 396, 396, 396, 397, 397, 397, 397, 398, 398, 398, 398, 399, 399, 399, 399, 400, 400, 400, 400, 401, 401, 401, 401, 402, 402, 402, 402, 403, 403, 403, 403, 404, 404, 404, 404, 405, 405, 405, 405, 406, 406, 406, 406, 407, 407, 407, 407, 408, 408, 408, 408, 409, 409, 409, 409, 410, 410, 410, 410, 411, 411, 411, 411, 412, 412, 412, 412, 413, 413, 413, 413, 414, 414, 414, 414, 415, 415, 415, 415, 416, 416, 416, 416, 417, 417, 417, 417, 418, 418, 418, 418, 419, 419, 419, 419, 420, 420, 420, 420, 421, 421, 421, 421, 422, 422, 422, 422, 423, 423, 423, 423, 424, 424, 424, 424, 425, 425, 425, 425, 426, 426, 426, 426, 427, 427, 427, 427, 428, 428, 428, 428, 429, 429, 429, 429, 430, 430, 430, 430, 431, 431, 431, 431, 432, 432, 432, 432, 433, 433, 433, 433, 434, 434, 434, 434, 435, 435, 435, 435, 436, 436, 436, 436, 437, 437, 437, 437, 438, 438, 438, 438, 439, 439, 439, 439, 440, 440, 440, 440, 441, 441, 441, 441, 442, 442, 442, 442, 99, 99, 225, 224, 222, 220, 99, 219, 218, 216, 214, 213, 212, 211, 210, 208, 206, 205, 204, 203, 202, 201, 199, 196, 195, 194, 193, 192, 191, 99, 59, 188, 189, 188, 153, 185, 184, 183, 182, 99, 99, 177, 176, 175, 174, 173, 99, 169, 168, 167, 99, 166, 99, 165, 99, 161, 160, 119, 99, 99, 99, 157, 156, 103, 152, 151, 150, 149, 148, 147, 146, 145, 99, 99, 143, 142, 141, 140, 139, 138, 137, 59, 132, 128, 127, 126, 125, 70, 70, 124, 123, 70, 122, 99, 99, 121, 120, 119, 118, 117, 99, 116, 115, 114, 113, 112, 59, 111, 110, 109, 108, 107, 106, 443, 27, 102, 70, 101, 100, 99, 98, 97, 96, 95, 70, 94, 93, 92, 88, 85, 84, 70, 83, 70, 82, 81, 80, 79, 78, 77, 75, 74, 72, 71, 70, 443, 65, 64, 63, 56, 55, 54, 53, 443, 443, 3, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443 } ; static yyconst flex_int16_t yy_chk[1235] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 6, 6, 7, 7, 7, 7, 10, 11, 12, 14, 34, 15, 16, 49, 13, 26, 26, 107, 37, 12, 49, 16, 471, 12, 12, 11, 13, 15, 11, 13, 13, 107, 10, 469, 34, 14, 17, 27, 27, 27, 28, 28, 28, 28, 17, 17, 37, 66, 66, 66, 66, 467, 17, 465, 17, 463, 17, 17, 461, 17, 17, 22, 51, 22, 22, 103, 103, 103, 51, 22, 134, 22, 51, 104, 104, 104, 104, 109, 459, 134, 22, 457, 143, 109, 129, 129, 129, 129, 143, 153, 153, 153, 154, 154, 154, 154, 165, 455, 165, 170, 170, 170, 186, 186, 186, 211, 211, 211, 453, 451, 449, 229, 228, 165, 444, 444, 445, 445, 445, 225, 445, 446, 446, 447, 447, 447, 224, 447, 448, 448, 450, 450, 450, 450, 452, 452, 452, 452, 454, 454, 454, 454, 456, 456, 456, 456, 458, 458, 458, 458, 460, 460, 460, 460, 462, 462, 462, 462, 464, 464, 464, 464, 466, 466, 466, 466, 468, 468, 468, 468, 470, 470, 470, 470, 472, 472, 472, 472, 473, 473, 473, 473, 474, 474, 474, 474, 475, 475, 475, 475, 476, 476, 476, 476, 477, 477, 477, 477, 478, 478, 478, 478, 479, 479, 479, 479, 480, 480, 480, 480, 481, 481, 481, 481, 482, 482, 482, 482, 483, 483, 483, 483, 484, 484, 484, 484, 485, 485, 485, 485, 486, 486, 486, 486, 487, 487, 487, 487, 488, 488, 488, 488, 489, 489, 489, 489, 490, 490, 490, 490, 491, 491, 491, 491, 492, 492, 492, 492, 493, 493, 493, 493, 494, 494, 494, 494, 495, 495, 495, 495, 496, 496, 496, 496, 497, 497, 497, 497, 498, 498, 498, 498, 499, 499, 499, 499, 500, 500, 500, 500, 501, 501, 501, 501, 502, 502, 502, 502, 503, 503, 503, 503, 504, 504, 504, 504, 505, 505, 505, 505, 506, 506, 506, 506, 507, 507, 507, 507, 508, 508, 508, 508, 509, 509, 509, 509, 510, 510, 510, 510, 511, 511, 511, 511, 512, 512, 512, 512, 513, 513, 513, 513, 514, 514, 514, 514, 515, 515, 515, 515, 516, 516, 516, 516, 517, 517, 517, 517, 518, 518, 518, 518, 519, 519, 519, 519, 520, 520, 520, 520, 521, 521, 521, 521, 522, 522, 522, 522, 523, 523, 523, 523, 524, 524, 524, 524, 525, 525, 525, 525, 526, 526, 526, 526, 527, 527, 527, 527, 528, 528, 528, 528, 529, 529, 529, 529, 530, 530, 530, 530, 531, 531, 531, 531, 532, 532, 532, 532, 533, 533, 533, 533, 534, 534, 534, 534, 535, 535, 535, 535, 536, 536, 536, 536, 537, 537, 537, 537, 538, 538, 538, 538, 539, 539, 539, 539, 540, 540, 540, 540, 541, 541, 541, 541, 542, 542, 542, 542, 543, 543, 543, 543, 544, 544, 544, 544, 545, 545, 545, 545, 546, 546, 546, 546, 547, 547, 547, 547, 548, 548, 548, 548, 549, 549, 549, 549, 550, 550, 550, 550, 551, 551, 551, 551, 552, 552, 552, 552, 553, 553, 553, 553, 554, 554, 554, 554, 555, 555, 555, 555, 556, 556, 556, 556, 557, 557, 557, 557, 558, 558, 558, 558, 559, 559, 559, 559, 560, 560, 560, 560, 561, 561, 561, 561, 562, 562, 562, 562, 563, 563, 563, 563, 564, 564, 564, 564, 565, 565, 565, 565, 566, 566, 566, 566, 567, 567, 567, 567, 568, 568, 568, 568, 569, 569, 569, 569, 570, 570, 570, 570, 571, 571, 571, 571, 572, 572, 572, 572, 573, 573, 573, 573, 574, 574, 574, 574, 575, 575, 575, 575, 576, 576, 576, 576, 577, 577, 577, 577, 578, 578, 578, 578, 579, 579, 579, 579, 580, 580, 580, 580, 581, 581, 581, 581, 582, 582, 582, 582, 583, 583, 583, 583, 584, 584, 584, 584, 585, 585, 585, 585, 586, 586, 586, 586, 587, 587, 587, 587, 588, 588, 588, 588, 589, 589, 589, 589, 590, 590, 590, 590, 591, 591, 591, 591, 592, 592, 592, 592, 593, 593, 593, 593, 594, 594, 594, 594, 595, 595, 595, 595, 596, 596, 596, 596, 597, 597, 597, 597, 598, 598, 598, 598, 599, 599, 599, 599, 600, 600, 600, 600, 601, 601, 601, 601, 602, 602, 602, 602, 603, 603, 603, 603, 604, 604, 604, 604, 605, 605, 605, 605, 606, 606, 606, 606, 607, 607, 607, 607, 608, 608, 608, 608, 609, 609, 609, 609, 610, 610, 610, 610, 611, 611, 611, 611, 612, 612, 612, 612, 613, 613, 613, 613, 614, 614, 614, 614, 615, 615, 615, 615, 616, 616, 616, 616, 617, 617, 617, 617, 618, 618, 618, 618, 619, 619, 619, 619, 620, 620, 620, 620, 621, 621, 621, 621, 622, 622, 622, 622, 623, 623, 623, 623, 624, 624, 624, 624, 625, 625, 625, 625, 626, 626, 626, 626, 627, 627, 627, 627, 628, 628, 628, 628, 629, 629, 629, 629, 630, 630, 630, 630, 631, 631, 631, 631, 632, 632, 632, 632, 633, 633, 633, 633, 634, 634, 634, 634, 635, 635, 635, 635, 636, 636, 636, 636, 637, 637, 637, 637, 638, 638, 638, 638, 639, 639, 639, 639, 640, 640, 640, 640, 641, 641, 641, 641, 642, 642, 642, 642, 643, 643, 643, 643, 644, 644, 644, 644, 645, 645, 645, 645, 646, 646, 646, 646, 647, 647, 647, 647, 648, 648, 648, 648, 649, 649, 649, 649, 650, 650, 650, 650, 651, 651, 651, 651, 652, 652, 652, 652, 653, 653, 653, 653, 654, 654, 654, 654, 655, 655, 655, 655, 656, 656, 656, 656, 657, 657, 657, 657, 658, 658, 658, 658, 659, 659, 659, 659, 660, 660, 660, 660, 661, 661, 661, 661, 662, 662, 662, 662, 663, 663, 663, 663, 664, 664, 664, 664, 665, 665, 665, 665, 666, 666, 666, 666, 667, 667, 667, 667, 668, 668, 668, 668, 669, 669, 669, 669, 670, 670, 670, 670, 671, 671, 671, 671, 672, 672, 672, 672, 673, 673, 673, 673, 674, 674, 674, 674, 675, 675, 675, 675, 676, 676, 676, 676, 677, 677, 677, 677, 678, 678, 678, 678, 679, 679, 679, 679, 222, 220, 219, 218, 216, 214, 213, 212, 210, 208, 206, 205, 204, 202, 201, 199, 196, 195, 194, 193, 192, 191, 189, 184, 183, 182, 181, 180, 179, 177, 176, 175, 174, 173, 171, 169, 168, 167, 166, 163, 162, 161, 160, 159, 158, 157, 156, 152, 151, 150, 149, 147, 146, 145, 141, 140, 139, 138, 137, 136, 135, 133, 132, 130, 128, 127, 126, 125, 124, 123, 122, 121, 118, 117, 116, 115, 114, 113, 112, 111, 110, 108, 106, 102, 101, 100, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 75, 74, 73, 72, 71, 68, 67, 65, 64, 63, 62, 61, 60, 58, 57, 56, 55, 54, 53, 52, 50, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 36, 35, 33, 32, 31, 29, 25, 24, 23, 21, 20, 19, 18, 8, 3, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443, 443 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #ifndef YYLMAX #define YYLMAX 8192 #endif char yytext[YYLMAX]; char *yytext_ptr; #line 1 "prom_lex.l" /* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* definitions */ #line 23 "prom_lex.l" #include "prom_parse.h" #undef LEXDEBUG #ifdef LEXDEBUG #define dbg(a) dbgprint((a)) #else #define dbg(a) do {} while (0) #endif /* LEXDEBUG */ #define upval(d) \ dbg(#d); \ yylval.str[0] = 0; \ strcat(yylval.str, yytext); \ yylloc.first_column = yylloc.last_column; \ yylloc.last_column += yyleng; \ return d void dbgprint(const char *item) { fprintf(stderr, "%s: \"%s\" len=%d ", item, yytext, yyleng);} #define YY_NO_INPUT 1 /* CHOSEN uses only boot related paths. */ #line 975 "" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); int yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 65 "prom_lex.l" #line 1163 "" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 444 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 443 ); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 67 "prom_lex.l" { upval(CHOSEN); } YY_BREAK case 2: YY_RULE_SETUP #line 68 "prom_lex.l" { upval(VDEVICE); } YY_BREAK case 3: YY_RULE_SETUP #line 69 "prom_lex.l" { upval(VDEVINST); } YY_BREAK case 4: YY_RULE_SETUP #line 70 "prom_lex.l" { upval(VDEVDEV); } YY_BREAK case 5: YY_RULE_SETUP #line 71 "prom_lex.l" { upval(VDEVRAW); } YY_BREAK case 6: YY_RULE_SETUP #line 72 "prom_lex.l" { upval(OBPQUAL); } YY_BREAK case 7: YY_RULE_SETUP #line 73 "prom_lex.l" { upval(BUSNAME); } YY_BREAK case 8: YY_RULE_SETUP #line 74 "prom_lex.l" { upval(IPV4); } YY_BREAK case 9: YY_RULE_SETUP #line 75 "prom_lex.l" { upval(IQN); } YY_BREAK case 10: YY_RULE_SETUP #line 76 "prom_lex.l" { upval(BOOTDEV); } YY_BREAK case 11: YY_RULE_SETUP #line 77 "prom_lex.l" { upval(OBPPARM); } YY_BREAK case 12: YY_RULE_SETUP #line 78 "prom_lex.l" { upval(HEX4); } YY_BREAK case 13: YY_RULE_SETUP #line 79 "prom_lex.l" { upval(HEX16); } YY_BREAK case 14: YY_RULE_SETUP #line 80 "prom_lex.l" { upval(FILENAME); } YY_BREAK case 15: /* rule 15 can match eol */ YY_RULE_SETUP #line 81 "prom_lex.l" { /* eat all whitespace. */ yylloc.first_column = yylloc.last_column; yylloc.last_column += yyleng; } YY_BREAK case 16: YY_RULE_SETUP #line 85 "prom_lex.l" { /* any other single char. */ dbg("??"); yylloc.first_column = yylloc.last_column; yylloc.last_column += yyleng; return *yytext; } YY_BREAK case YY_STATE_EOF(INITIAL): #line 92 "prom_lex.l" yyterminate(); YY_BREAK case 17: YY_RULE_SETUP #line 93 "prom_lex.l" ECHO; YY_BREAK #line 1340 "" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 444 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 444 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 443); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 93 "prom_lex.l" open-iscsi-2.0.873/utils/fwparam_ibft/prom_lex.l000066400000000000000000000054051175631155400215630ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* definitions */ %option array %{ #include "prom_parse.h" #undef LEXDEBUG #ifdef LEXDEBUG #define dbg(a) dbgprint((a)) #else #define dbg(a) do {} while (0) #endif /* LEXDEBUG */ #define upval(d) \ dbg(#d); \ yylval.str[0] = 0; \ strcat(yylval.str, yytext); \ yylloc.first_column = yylloc.last_column; \ yylloc.last_column += yyleng; \ return d void dbgprint(const char *item) { fprintf(stderr, "%s: \"%s\" len=%d ", item, yytext, yyleng);} %} %option noyywrap %option never-interactive %option nounput %option noinput VDEVICE vdevice VDEVINST gscsi VDEVDEV dev VDEVRAW rawio /* CHOSEN uses only boot related paths. */ CHOSEN bootpath|bootargs|iscsi-bootargs|nas-bootdevice BUSNAME ata|i2c|ide|pci|sata|scsi|usb|lhea BOOTDEV cdrom|disk|ethernet|iscsi-(disk[0-9]|toe)|sd HEX4 [[:xdigit:]]{1,4} HEX16 [[:xdigit:]]{5,16} IPV4 [0-9]{1,3}(\.[0-9]{1,3}){3} IQN iqn\.[-[:alnum:]:.]{1,219} OBPQUAL bootp|ipv6|iscsi|dhcpv6 OBPPARM blksize|bootp-retries|chapid|chappw|ciaddr|dhcp|filename|giaddr|ichapid|ichappw|ilun|iname|iport|isid|isns|itname|siaddr|slp|subnet-mask|tftp-retries FILENAME \\[-[:alnum:]\\\.]{1,} %% /* rules */ {CHOSEN} { upval(CHOSEN); } {VDEVICE} { upval(VDEVICE); } {VDEVINST} { upval(VDEVINST); } {VDEVDEV} { upval(VDEVDEV); } {VDEVRAW} { upval(VDEVRAW); } {OBPQUAL} { upval(OBPQUAL); } {BUSNAME} { upval(BUSNAME); } {IPV4} { upval(IPV4); } {IQN} { upval(IQN); } {BOOTDEV} { upval(BOOTDEV); } {OBPPARM} { upval(OBPPARM); } {HEX4} { upval(HEX4); } {HEX16} { upval(HEX16); } {FILENAME} { upval(FILENAME); } [ \t\n]+ { /* eat all whitespace. */ yylloc.first_column = yylloc.last_column; yylloc.last_column += yyleng; } . { /* any other single char. */ dbg("??"); yylloc.first_column = yylloc.last_column; yylloc.last_column += yyleng; return *yytext; } <> yyterminate(); %% /* user code */ open-iscsi-2.0.873/utils/fwparam_ibft/prom_parse.h000066400000000000000000000022141175631155400220740ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef PROM_PARSE_H_ #define PROM_PARSE_H_ #include #include #include "iscsi_obp.h" struct ofw_dev; void yyerror(struct ofw_dev *ofwdev, const char *msg); extern int yyleng; extern int yydebug; #include extern FILE *yyin; extern char yytext[]; int yylex(void); #define YY_NO_UNPUT 1 /* match this with %option never-interactive. */ #include "prom_parse.tab.h" #endif /* PROM_PARSE_H_ */ open-iscsi-2.0.873/utils/fwparam_ibft/prom_parse.tab.c000066400000000000000000001612651175631155400226500ustar00rootroot00000000000000/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Using locations. */ #define YYLSP_NEEDED 1 /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { BUSNAME = 258, BOOTDEV = 259, IPV4 = 260, IQN = 261, OBPPARM = 262, OBPQUAL = 263, HEX4 = 264, HEX16 = 265, VDEVICE = 266, VDEVINST = 267, VDEVDEV = 268, VDEVRAW = 269, CHOSEN = 270, FILENAME = 271 }; #endif /* Tokens. */ #define BUSNAME 258 #define BOOTDEV 259 #define IPV4 260 #define IQN 261 #define OBPPARM 262 #define OBPQUAL 263 #define HEX4 264 #define HEX16 265 #define VDEVICE 266 #define VDEVINST 267 #define VDEVDEV 268 #define VDEVRAW 269 #define CHOSEN 270 #define FILENAME 271 /* Copy the first part of user declarations. */ #line 21 "prom_parse.y" /* literal block. include lines, decls, defns. */ //#define YYDEBUG 1 #if YYDEBUG #define DPRINT(fmt,...) printf(fmt,__VA_ARGS__) #else #define DPRINT(fmt,...) do {} while(0) #endif #include "prom_parse.h" #include "iscsi_obp.h" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 33 "prom_parse.y" { char str[256]; } /* Line 187 of yacc.c. */ #line 145 "prom_parse.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 170 "prom_parse.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 8 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 103 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 24 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 19 /* YYNRULES -- Number of rules. */ #define YYNRULES 51 /* YYNRULES -- Number of states. */ #define YYNSTATES 93 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 273 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 19, 2, 2, 17, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 20, 2, 2, 21, 2, 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 5, 9, 14, 20, 27, 35, 37, 41, 43, 47, 53, 57, 63, 67, 73, 81, 85, 88, 92, 96, 100, 103, 107, 111, 113, 117, 121, 125, 129, 133, 135, 139, 141, 143, 145, 147, 149, 151, 155, 157, 160, 164, 167, 169, 173, 175, 178, 184, 187 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 25, 0, -1, 17, -1, 17, 26, 28, -1, 17, 26, 28, 41, -1, 17, 26, 28, 34, 32, -1, 17, 26, 28, 34, 32, 41, -1, 17, 29, 28, 30, 34, 32, 41, -1, 27, -1, 26, 17, 27, -1, 3, -1, 3, 18, 9, -1, 3, 18, 9, 19, 9, -1, 3, 18, 10, -1, 3, 19, 9, 18, 10, -1, 17, 4, 20, -1, 17, 4, 18, 9, 20, -1, 17, 4, 18, 9, 19, 9, 20, -1, 11, 17, 12, -1, 20, 31, -1, 30, 19, 31, -1, 30, 19, 14, -1, 13, 21, 15, -1, 19, 33, -1, 32, 19, 33, -1, 32, 19, 41, -1, 9, -1, 7, 21, 10, -1, 7, 21, 36, -1, 7, 21, 6, -1, 7, 21, 9, -1, 7, 21, 16, -1, 35, -1, 34, 19, 35, -1, 8, -1, 31, -1, 37, -1, 38, -1, 5, -1, 39, -1, 39, 20, 37, -1, 40, -1, 39, 22, -1, 39, 22, 40, -1, 22, 40, -1, 9, -1, 40, 23, 9, -1, 42, -1, 9, 42, -1, 18, 9, 19, 9, 42, -1, 20, 9, -1, 20, 9, 19, 16, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 58, 58, 61, 64, 72, 80, 87, 94, 97, 102, 105, 108, 111, 114, 120, 123, 126, 131, 136, 139, 142, 147, 152, 155, 158, 163, 166, 171, 175, 179, 183, 189, 192, 197, 200, 205, 208, 213, 218, 221, 226, 229, 232, 235, 240, 243, 248, 251, 254, 259, 262 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "BUSNAME", "BOOTDEV", "IPV4", "IQN", "OBPPARM", "OBPQUAL", "HEX4", "HEX16", "VDEVICE", "VDEVINST", "VDEVDEV", "VDEVRAW", "CHOSEN", "FILENAME", "'/'", "'@'", "','", "':'", "'='", "\"::\"", "\":\"", "$accept", "devpath", "busses", "bus", "bootdev", "vdevice", "vdev_parms", "vdev_parm", "obp_params", "obp_param", "obp_quals", "obp_qual", "ipaddr", "ipv4", "ipv6", "hexpart", "hexseq", "disklabel", "diskpart", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 47, 64, 44, 58, 61, 272, 273 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 24, 25, 25, 25, 25, 25, 25, 26, 26, 27, 27, 27, 27, 27, 28, 28, 28, 29, 30, 30, 30, 31, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 35, 35, 36, 36, 37, 38, 38, 39, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 3, 4, 5, 6, 7, 1, 3, 1, 3, 5, 3, 5, 3, 5, 7, 3, 2, 3, 3, 3, 2, 3, 3, 1, 3, 3, 3, 3, 3, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 2, 3, 2, 1, 3, 1, 2, 5, 2, 4 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 2, 0, 10, 0, 0, 8, 0, 1, 0, 0, 0, 0, 3, 0, 0, 11, 13, 0, 18, 0, 9, 34, 0, 0, 0, 0, 35, 0, 32, 4, 47, 0, 0, 0, 0, 0, 15, 48, 0, 0, 50, 0, 5, 19, 0, 0, 12, 14, 0, 22, 0, 0, 0, 26, 23, 33, 0, 6, 21, 20, 0, 0, 16, 0, 51, 0, 26, 24, 25, 7, 0, 49, 38, 29, 30, 27, 31, 0, 28, 36, 37, 39, 41, 17, 45, 44, 0, 42, 0, 40, 43, 46 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 2, 5, 6, 13, 7, 33, 27, 43, 55, 28, 29, 79, 80, 81, 82, 83, 30, 31 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -73 static const yytype_int8 yypact[] = { -15, 19, 13, 20, 18, 23, -73, 25, -73, 39, 51, 50, 49, 16, 46, 43, 42, -73, 47, -73, -9, -73, -73, 44, 45, 58, 59, -73, 52, -73, -73, -73, 56, 24, 61, 62, 64, -73, -73, 60, 55, 57, 38, 8, -73, 41, 52, -73, -73, 37, -73, 68, 63, 65, -73, -73, -73, 3, -73, -73, -73, 8, 69, -73, 44, -73, -2, 44, -73, -73, -73, 67, -73, -73, -73, 36, -73, -73, 71, -73, -73, -73, 11, 66, -73, -73, 66, 76, 71, 73, -73, 66, -73 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -73, -73, -73, 72, 78, -73, -73, -27, 48, 26, 70, 53, -73, 1, -73, -73, -72, -42, -23 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -46 static const yytype_int8 yytable[] = { 38, 58, 1, 73, 74, 44, 86, 75, 76, 36, 53, 37, 67, 8, 77, 69, 91, 23, 60, 70, 78, 25, 3, 26, 22, 23, 25, 57, 26, 24, 4, 87, 22, 88, 25, 11, 26, 24, 9, 10, 12, 72, 14, 45, 38, 53, 22, 54, 16, 17, 20, 24, 3, 20, 24, 59, 62, 63, -45, -45, 18, 34, 19, 32, 26, 35, 39, 40, 41, 24, 47, 42, 48, 49, 51, 50, 52, 64, 71, 65, 85, 73, 92, 68, 21, 15, 66, 84, 90, 89, 0, 0, 0, 0, 61, 56, 0, 0, 0, 0, 0, 0, 0, 46 }; static const yytype_int8 yycheck[] = { 23, 43, 17, 5, 6, 32, 78, 9, 10, 18, 7, 20, 9, 0, 16, 57, 88, 9, 45, 61, 22, 18, 3, 20, 8, 9, 18, 19, 20, 13, 11, 20, 8, 22, 18, 17, 20, 13, 18, 19, 17, 64, 17, 19, 67, 7, 8, 9, 9, 10, 4, 13, 3, 4, 13, 14, 19, 20, 22, 23, 9, 19, 12, 20, 20, 18, 21, 9, 9, 13, 9, 19, 10, 9, 19, 15, 19, 9, 9, 16, 9, 5, 9, 57, 12, 7, 21, 20, 87, 23, -1, -1, -1, -1, 46, 42, -1, -1, -1, -1, -1, -1, -1, 33 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 17, 25, 3, 11, 26, 27, 29, 0, 18, 19, 17, 17, 28, 17, 28, 9, 10, 9, 12, 4, 27, 8, 9, 13, 18, 20, 31, 34, 35, 41, 42, 20, 30, 19, 18, 18, 20, 42, 21, 9, 9, 19, 32, 31, 19, 34, 9, 10, 9, 15, 19, 19, 7, 9, 33, 35, 19, 41, 14, 31, 32, 19, 20, 9, 16, 21, 9, 33, 41, 41, 9, 42, 5, 6, 9, 10, 16, 22, 36, 37, 38, 39, 40, 20, 9, 40, 20, 22, 23, 37, 40, 9 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (ofwdev, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, ofwdev); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, struct ofw_dev *ofwdev) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, ofwdev) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; struct ofw_dev *ofwdev; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (ofwdev); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, struct ofw_dev *ofwdev) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, ofwdev) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; struct ofw_dev *ofwdev; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, ofwdev); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, struct ofw_dev *ofwdev) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, ofwdev) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; struct ofw_dev *ofwdev; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , ofwdev); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, ofwdev); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, struct ofw_dev *ofwdev) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, ofwdev) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; struct ofw_dev *ofwdev; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (ofwdev); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (struct ofw_dev *ofwdev); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (struct ofw_dev *ofwdev) #else int yyparse (ofwdev) struct ofw_dev *ofwdev; #endif #endif { int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 58 "prom_parse.y" { DPRINT("****rootonly: \"%s\"\n", "/"); ;} break; case 3: #line 61 "prom_parse.y" { DPRINT("****devpath busses:\n/%s/%s\n", (yyvsp[(2) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 4: #line 64 "prom_parse.y" { ofwdev->dev_path = malloc(strlen((yyvsp[(2) - (4)].str)) + strlen((yyvsp[(3) - (4)].str)) + 3); sprintf(ofwdev->dev_path, "/%s%s", (yyvsp[(2) - (4)].str), (yyvsp[(3) - (4)].str)); DPRINT("****devpath busses bootdev " "disklabel:\n/%s/%s%s\n", (yyvsp[(2) - (4)].str), (yyvsp[(3) - (4)].str), (yyvsp[(4) - (4)].str)); ;} break; case 5: #line 72 "prom_parse.y" { ofwdev->dev_path = malloc(strlen((yyvsp[(2) - (5)].str)) + strlen((yyvsp[(3) - (5)].str)) + 3); sprintf(ofwdev->dev_path, "/%s%s", (yyvsp[(2) - (5)].str), (yyvsp[(3) - (5)].str)); DPRINT("****busses bootdev obp_quals obp_parms:\n" "/%s/%s:%s%s\n", (yyvsp[(2) - (5)].str), (yyvsp[(3) - (5)].str), (yyvsp[(4) - (5)].str), (yyvsp[(5) - (5)].str)); ;} break; case 6: #line 80 "prom_parse.y" { ofwdev->dev_path = malloc(strlen((yyvsp[(2) - (6)].str)) + strlen((yyvsp[(3) - (6)].str)) + 3); sprintf(ofwdev->dev_path, "/%s%s", (yyvsp[(2) - (6)].str), (yyvsp[(3) - (6)].str)); DPRINT("****busses bootdev obp_quals obp_parms " "disklabel:\n/%s:%s%s%s\n", (yyvsp[(2) - (6)].str), (yyvsp[(4) - (6)].str), (yyvsp[(5) - (6)].str), (yyvsp[(6) - (6)].str)); ;} break; case 7: #line 87 "prom_parse.y" { DPRINT("****vdevice bootdev obp_parms " "disklabel:\n/%s:%s%s%s%s\n", (yyvsp[(2) - (7)].str), (yyvsp[(4) - (7)].str), (yyvsp[(5) - (7)].str), (yyvsp[(6) - (7)].str), (yyvsp[(7) - (7)].str)); ;} break; case 8: #line 94 "prom_parse.y" { strcpy((yyval.str), (yyvsp[(1) - (1)].str)); ;} break; case 9: #line 97 "prom_parse.y" { sprintf((yyval.str), "%s/%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 10: #line 102 "prom_parse.y" { strcpy((yyval.str), (yyvsp[(1) - (1)].str)); ;} break; case 11: #line 105 "prom_parse.y" { sprintf((yyval.str), "%s@%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 12: #line 108 "prom_parse.y" { sprintf((yyval.str), "%s@%s,%s", (yyvsp[(1) - (5)].str), (yyvsp[(3) - (5)].str), (yyvsp[(5) - (5)].str)); ;} break; case 13: #line 111 "prom_parse.y" { sprintf((yyval.str), "%s@%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 14: #line 114 "prom_parse.y" { sprintf((yyval.str), "%s,%s@%s", (yyvsp[(1) - (5)].str), (yyvsp[(3) - (5)].str), (yyvsp[(5) - (5)].str)); ;} break; case 15: #line 120 "prom_parse.y" { sprintf((yyval.str), "/%s", (yyvsp[(2) - (3)].str)); ;} break; case 16: #line 123 "prom_parse.y" { sprintf((yyval.str), "/%s@%s", (yyvsp[(2) - (5)].str), (yyvsp[(4) - (5)].str)); ;} break; case 17: #line 126 "prom_parse.y" { sprintf((yyval.str), "/%s@%s,%s", (yyvsp[(2) - (7)].str), (yyvsp[(4) - (7)].str), (yyvsp[(6) - (7)].str)); ;} break; case 18: #line 131 "prom_parse.y" { sprintf((yyval.str), "%s/%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 19: #line 136 "prom_parse.y" { sprintf((yyval.str), ":%s", (yyvsp[(2) - (2)].str)); ;} break; case 20: #line 139 "prom_parse.y" { sprintf((yyval.str), "%s,%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 21: #line 142 "prom_parse.y" { sprintf((yyval.str), "%s,%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 22: #line 147 "prom_parse.y" { sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 23: #line 152 "prom_parse.y" { sprintf((yyval.str), ",%s", (yyvsp[(2) - (2)].str)); ;} break; case 24: #line 155 "prom_parse.y" { sprintf((yyval.str), "%s,%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 25: #line 158 "prom_parse.y" { sprintf((yyval.str), "%s,%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 26: #line 163 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 27: #line 166 "prom_parse.y" { /* luns > 0 are the SAM-3+ hex representation. */ obp_parm_hexnum(ofwdev, (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 28: #line 171 "prom_parse.y" { obp_parm_addr(ofwdev, (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 29: #line 175 "prom_parse.y" { obp_parm_iqn(ofwdev, (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 30: #line 179 "prom_parse.y" { obp_parm_hexnum(ofwdev, (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 31: #line 183 "prom_parse.y" { obp_parm_str(ofwdev, (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); sprintf((yyval.str), "%s=%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 32: #line 189 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 33: #line 192 "prom_parse.y" { sprintf((yyval.str), "%s,%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 34: #line 197 "prom_parse.y" { sprintf((yyval.str), "%s", obp_qual_set(ofwdev, (yyvsp[(1) - (1)].str))); ;} break; case 35: #line 200 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 36: #line 205 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 37: #line 208 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 38: #line 213 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 39: #line 218 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 40: #line 221 "prom_parse.y" { sprintf((yyval.str), "%s:%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 41: #line 226 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 42: #line 229 "prom_parse.y" { sprintf((yyval.str), "%s::", (yyvsp[(1) - (2)].str)); ;} break; case 43: #line 232 "prom_parse.y" { sprintf((yyval.str), "%s::%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 44: #line 235 "prom_parse.y" { sprintf((yyval.str), "::%s", (yyvsp[(2) - (2)].str)); ;} break; case 45: #line 240 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 46: #line 243 "prom_parse.y" { sprintf((yyval.str), "%s:%s", (yyvsp[(1) - (3)].str), (yyvsp[(3) - (3)].str)); ;} break; case 47: #line 248 "prom_parse.y" { sprintf((yyval.str), "%s", (yyvsp[(1) - (1)].str)); ;} break; case 48: #line 251 "prom_parse.y" { sprintf((yyval.str), "%s%s", (yyvsp[(1) - (2)].str), (yyvsp[(2) - (2)].str)); ;} break; case 49: #line 254 "prom_parse.y" { sprintf((yyval.str), "@%s,%s%s", (yyvsp[(2) - (5)].str), (yyvsp[(4) - (5)].str), (yyvsp[(5) - (5)].str)); ;} break; case 50: #line 259 "prom_parse.y" { sprintf((yyval.str), ":%s", (yyvsp[(2) - (2)].str)); ;} break; case 51: #line 262 "prom_parse.y" { sprintf((yyval.str), ":%s,%s", (yyvsp[(2) - (4)].str), (yyvsp[(4) - (4)].str)); ;} break; /* Line 1267 of yacc.c. */ #line 1848 "prom_parse.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (ofwdev, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (ofwdev, yymsg); } else { yyerror (ofwdev, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, ofwdev); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, ofwdev); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (ofwdev, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, ofwdev); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, ofwdev); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 267 "prom_parse.y" open-iscsi-2.0.873/utils/fwparam_ibft/prom_parse.tab.h000066400000000000000000000057261175631155400226540ustar00rootroot00000000000000/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { BUSNAME = 258, BOOTDEV = 259, IPV4 = 260, IQN = 261, OBPPARM = 262, OBPQUAL = 263, HEX4 = 264, HEX16 = 265, VDEVICE = 266, VDEVINST = 267, VDEVDEV = 268, VDEVRAW = 269, CHOSEN = 270, FILENAME = 271 }; #endif /* Tokens. */ #define BUSNAME 258 #define BOOTDEV 259 #define IPV4 260 #define IQN 261 #define OBPPARM 262 #define OBPQUAL 263 #define HEX4 264 #define HEX16 265 #define VDEVICE 266 #define VDEVINST 267 #define VDEVDEV 268 #define VDEVRAW 269 #define CHOSEN 270 #define FILENAME 271 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 33 "prom_parse.y" { char str[256]; } /* Line 1489 of yacc.c. */ #line 85 "prom_parse.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE yylval; #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif extern YYLTYPE yylloc; open-iscsi-2.0.873/utils/fwparam_ibft/prom_parse.y000066400000000000000000000140561175631155400221240ustar00rootroot00000000000000/* * Copyright (C) IBM Corporation. 2007 * Author: Doug Maxey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* - DEFINITION section. */ %{ /* literal block. include lines, decls, defns. */ //#define YYDEBUG 1 #if YYDEBUG #define DPRINT(fmt,...) printf(fmt,__VA_ARGS__) #else #define DPRINT(fmt,...) do {} while(0) #endif #include "prom_parse.h" #include "iscsi_obp.h" %} %union { char str[256]; } /* definitions. */ %token BUSNAME BOOTDEV %token IPV4 IQN %token OBPPARM OBPQUAL %token HEX4 HEX16 %token VDEVICE VDEVINST VDEVDEV VDEVRAW %token CHOSEN %token FILENAME %type devpath busses bus bootdev %type disklabel diskpart %type vdevice vdev_parms vdev_parm %type obp_quals obp_qual obp_params obp_param %type ipaddr ipv4 ipv6 %type hexpart hexseq %locations %parse-param {struct ofw_dev *ofwdev} %% devpath: '/' { DPRINT("****rootonly: \"%s\"\n", "/"); } | '/' busses bootdev { DPRINT("****devpath busses:\n/%s/%s\n", $2, $3); } | '/' busses bootdev disklabel { ofwdev->dev_path = malloc(strlen($2) + strlen($3) + 3); sprintf(ofwdev->dev_path, "/%s%s", $2, $3); DPRINT("****devpath busses bootdev " "disklabel:\n/%s/%s%s\n", $2, $3, $4); } | '/' busses bootdev obp_quals obp_params { ofwdev->dev_path = malloc(strlen($2) + strlen($3) + 3); sprintf(ofwdev->dev_path, "/%s%s", $2, $3); DPRINT("****busses bootdev obp_quals obp_parms:\n" "/%s/%s:%s%s\n", $2, $3, $4, $5); } | '/' busses bootdev obp_quals obp_params disklabel { ofwdev->dev_path = malloc(strlen($2) + strlen($3) + 3); sprintf(ofwdev->dev_path, "/%s%s", $2, $3); DPRINT("****busses bootdev obp_quals obp_parms " "disklabel:\n/%s:%s%s%s\n", $2, $4, $5, $6); } | '/' vdevice bootdev vdev_parms obp_quals obp_params disklabel { DPRINT("****vdevice bootdev obp_parms " "disklabel:\n/%s:%s%s%s%s\n", $2, $4, $5, $6, $7); } ; busses: bus { strcpy($$, $1); } | busses '/' bus { sprintf($$, "%s/%s", $1, $3); } ; bus: BUSNAME { strcpy($$, $1); } | BUSNAME '@' HEX4 { sprintf($$, "%s@%s", $1, $3); } | BUSNAME '@' HEX4 ',' HEX4 { sprintf($$, "%s@%s,%s", $1, $3, $5); } | BUSNAME '@' HEX16 { sprintf($$, "%s@%s", $1, $3); } | BUSNAME ',' HEX4 '@' HEX16 { sprintf($$, "%s,%s@%s", $1, $3, $5); } ; bootdev: '/' BOOTDEV ':' { sprintf($$, "/%s", $2); } | '/' BOOTDEV '@' HEX4 ':' { sprintf($$, "/%s@%s", $2, $4); } | '/' BOOTDEV '@' HEX4 ',' HEX4 ':' { sprintf($$, "/%s@%s,%s", $2, $4, $6); } ; vdevice: VDEVICE '/' VDEVINST { sprintf($$, "%s/%s", $1, $3); } ; vdev_parms: ':' vdev_parm { sprintf($$, ":%s", $2); } | vdev_parms ',' vdev_parm { sprintf($$, "%s,%s", $1, $3); } | vdev_parms ',' VDEVRAW { sprintf($$, "%s,%s", $1, $3); } ; vdev_parm: VDEVDEV '=' CHOSEN { sprintf($$, "%s=%s", $1, $3); } ; obp_params: ',' obp_param { sprintf($$, ",%s", $2); } | obp_params ',' obp_param { sprintf($$, "%s,%s", $1, $3); } | obp_params ',' disklabel { sprintf($$, "%s,%s", $1, $3); } ; obp_param: HEX4 { sprintf($$, "%s", $1); } | OBPPARM '=' HEX16 { /* luns > 0 are the SAM-3+ hex representation. */ obp_parm_hexnum(ofwdev, $1, $3); sprintf($$, "%s=%s", $1, $3); } | OBPPARM '=' ipaddr { obp_parm_addr(ofwdev, $1, $3); sprintf($$, "%s=%s", $1, $3); } | OBPPARM '=' IQN { obp_parm_iqn(ofwdev, $1, $3); sprintf($$, "%s=%s", $1, $3); } | OBPPARM '=' HEX4 { obp_parm_hexnum(ofwdev, $1, $3); sprintf($$, "%s=%s", $1, $3); } | OBPPARM '=' FILENAME { obp_parm_str(ofwdev, $1, $3); sprintf($$, "%s=%s", $1, $3); } ; obp_quals: obp_qual { sprintf($$, "%s", $1); } | obp_quals ',' obp_qual { sprintf($$, "%s,%s", $1, $3); } ; obp_qual: OBPQUAL { sprintf($$, "%s", obp_qual_set(ofwdev, $1)); } | vdev_parm { sprintf($$, "%s", $1); } ; ipaddr: ipv4 { sprintf($$, "%s", $1); } | ipv6 { sprintf($$, "%s", $1); } ; ipv4: IPV4 { sprintf($$, "%s", $1); } ; ipv6: hexpart { sprintf($$, "%s", $1); } | hexpart ':' ipv4 { sprintf($$, "%s:%s", $1, $3); } ; hexpart: hexseq { sprintf($$, "%s", $1); } | hexpart "::" { sprintf($$, "%s::", $1); } | hexpart "::" hexseq { sprintf($$, "%s::%s", $1, $3); } | "::" hexseq { sprintf($$, "::%s", $2); } ; hexseq: HEX4 { sprintf($$, "%s", $1); } | hexseq ":" HEX4 { sprintf($$, "%s:%s", $1, $3); } ; disklabel: diskpart { sprintf($$, "%s", $1); } | HEX4 diskpart { sprintf($$, "%s%s", $1, $2); } | '@' HEX4 ',' HEX4 diskpart { sprintf($$, "@%s,%s%s", $2, $4, $5); } ; diskpart: ':' HEX4 { sprintf($$, ":%s", $2); } | ':' HEX4 ',' FILENAME { sprintf($$, ":%s,%s", $2, $4); } ; %% open-iscsi-2.0.873/utils/iscsi-iname.c000066400000000000000000000077641175631155400174770ustar00rootroot00000000000000/* * iSCSI InitiatorName creation utility * Copyright (C) 2001 Cisco Systems, Inc. * maintained by linux-iscsi-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * See the file COPYING included with this distribution for more details. * * $Id: iscsi-iname.c,v 1.1.2.3 2005/03/15 06:33:44 wysochanski Exp $ * * iscsi-iname.c - Compute an iSCSI InitiatorName for this host. * Note that to ensure uniqueness, the system time is * a factor. This name must be cached and only regenerated * if there is no cached value. */ #include #include #include #include #include #include #include #include #include "md5.h" #define RANDOM_NUM_GENERATOR "/dev/urandom" int main(int argc, char *argv[]) { char iname[256]; struct timeval time; struct utsname system_info; long hostid; struct MD5Context context; unsigned char digest[16]; unsigned char *bytes = digest; unsigned char entropy[16]; int e; int fd; char *prefix; /* initialize */ memset(iname, 0, sizeof (iname)); memset(digest, 0, sizeof (digest)); memset(&context, 0, sizeof (context)); MD5Init(&context); /* take a prefix if given, otherwise use a default. */ if (argc > 1 && argv[1]) { prefix = argv[1]; if (( strcmp(prefix, "-h") == 0 ) || ( strcmp(prefix, "--help") == 0 )) { printf("\nGenerates a unique iSCSI node name " "on every invocation.\n"); exit(0); } else if ( strcmp(prefix, "-p") == 0 ) { prefix = argv[2]; } else { printf("\nUsage: iscsi-iname [-h | --help | " "-p ]\n"); exit(0); } } else { prefix = "iqn.2005-03.org.open-iscsi"; } /* try to feed some entropy from the pool to MD5 in order to get * uniqueness properties */ if ((fd = open(RANDOM_NUM_GENERATOR, O_RDONLY))) { e = read(fd, &entropy, 16); if (e >= 1) MD5Update(&context, (md5byte *)entropy, e); close(fd); } /* time the name is created is a factor in order to get * uniqueness properties */ if (gettimeofday(&time, NULL) < 0) { perror("error: gettimeofday failed"); return 1; } MD5Update(&context, (md5byte *) & time.tv_sec, sizeof (time.tv_sec)); MD5Update(&context, (md5byte *) & time.tv_usec, sizeof (time.tv_usec)); /* hostid */ hostid = gethostid(); MD5Update(&context, (md5byte *) & hostid, sizeof (hostid)); /* get the hostname and system name */ if (uname(&system_info) < 0) { perror("error: uname failed"); return 1; } MD5Update(&context, (md5byte *) system_info.sysname, sizeof (system_info.sysname)); MD5Update(&context, (md5byte *) system_info.nodename, sizeof (system_info.nodename)); MD5Update(&context, (md5byte *) system_info.release, sizeof (system_info.release)); MD5Update(&context, (md5byte *) system_info.version, sizeof (system_info.version)); MD5Update(&context, (md5byte *) system_info.machine, sizeof (system_info.machine)); /* compute the md5 hash of all the bits we just collected */ MD5Final(digest, &context); /* vary which md5 bytes we pick (though we probably don't need to do * this, since hopefully MD5 produces results such that each byte is as * good as any other). */ if ((fd = open(RANDOM_NUM_GENERATOR, O_RDONLY))) { if (read(fd, entropy, 1) == 1) bytes = &digest[(entropy[0] % (sizeof(digest) - 6))]; close(fd); } /* print the prefix followed by 6 bytes of the MD5 hash */ sprintf(iname, "%s:%x%x%x%x%x%x", prefix, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]); iname[sizeof (iname) - 1] = '\0'; printf("%s\n", iname); return 0; } open-iscsi-2.0.873/utils/iscsi_discovery000077500000000000000000000122441175631155400202460ustar00rootroot00000000000000#!/bin/bash # # Copyright (C) Voltaire Ltd. 2006. ALL RIGHTS RESERVED. # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # # Author: Dan Bar Dov # iscsi_discovery: # * does a send-targets discovery to the given IP # * set the transport type to the preferred transport (or tcp is -t flag is not used) # * tries to login # * if succeeds, # o logout, # o mark record autmatic (unless -m flag is used) # * else # o reset transport type to TCP # o try to login # o if succeeded # + logout # + mark record automatic (unless -m flag is used) # usage() { echo "Usage: $0 [-p ] [-d] [-t [-f]] [-m] [-l]" echo "Options:" echo "-p set the port number (defualt is 3260)." echo "-d print debugging information" echo "-t set trasnpot (default is tcp)." echo "-f force specific transport -disable the fallback to tcp (default is fallback enabled)." echo " force the transport specified by the argument of the -t flag." echo "-m manual startup - will set manual startup (default is automatic startup)." echo "-l login to the new discovered nodes (defualt is false)." } dbg() { $debug && echo $@ } initialize() { trap "exit" 2 debug=false force="0" log_out="1" startup_manual="0" #set defualt transport to tcp transport=tcp #set defualt port to 3260 port=3260; } parse_cmdline() { if [ $# -lt 1 ]; then usage exit 1 fi # check if the IP address is valid ip=`echo $1 | awk -F'.' '$1 != "" && $1 <=255 && $2 != "" && $2 <= 255 && $3 != "" && $3 <= 255 && $4 != "" && $4 <= 255 {print $0}'` if [ -z "$ip" ]; then echo "$1 is not a vaild IP address!" exit 1 fi shift while getopts "dfmlt:p:" options; do case $options in d ) debug=true;; f ) force="1";; t ) transport=$OPTARG;; p ) port=$OPTARG;; m ) startup_manual="1";; l ) log_out=0;; \? ) usage exit 1;; * ) usage exit 1;; esac done } discover() { # If open-iscsi is already logged in to the portal, exit if [ $(iscsiadm -m session | grep -c ${ip}:${port}) -ne 0 ]; then echo "Please logout from all targets on ${ip}:${port} before trying to run discovery on that portal" exit 2 fi connected=0 discovered=0 dbg "starting discovery to $ip" disc="$(iscsiadm -m discovery --type sendtargets --portal ${ip}:${port})" echo "${disc}" | while read portal target do portal=${portal%,*} select_transport done discovered=$(echo "${disc}" | wc -l) if [ ${discovered} = 0 ]; then echo "failed to discover targets at ${ip}" exit 2 else echo "discovered ${discovered} targets at ${ip}" fi } try_login() { if [ "$startup_manual" != "1" ]; then iscsiadm -m node --targetname ${target} --portal ${portal} --op update -n node.conn[0].startup -v automatic fi iscsiadm -m node --targetname ${target} --portal ${portal} --login >/dev/null 2>&1 ret=$? if [ ${ret} = 0 ]; then echo "Set target ${target} to automatic login over ${transport} to portal ${portal}" ((connected++)) if [ "$log_out" = "1" ]; then iscsiadm -m node --targetname ${target} --portal ${portal} --logout fi else echo "Cannot login over ${transport} to portal ${portal}" iscsiadm -m node --targetname ${target} --portal ${portal} --op update -n node.conn[0].startup -v manual fi return ${ret} } set_transport() { transport=$1 case "$transport" in iser) # iSER does not use digest iscsiadm -m node --targetname ${target} --portal ${portal} \ --op update -n node.conn[0].iscsi.HeaderDigest -v None iscsiadm -m node --targetname ${target} --portal ${portal} \ --op update -n node.conn[0].iscsi.DataDigest -v None ;; cxgb3i) # cxgb3i supports <= 16K packet (BHS + AHS + pdu payload + digests) iscsiadm -m node --targetname ${target} --portal ${portal} \ --op update -n node.conn[0].iscsi.MaxRecvDataSegmentLength \ -v 8192 ;; esac transport_name=`iscsiadm -m node -p ${portal} -T ${target} |awk '/transport_name/ {print $1}'` iscsiadm -m node --targetname ${target} --portal ${portal} \ --op update -n ${transport_name} -v ${transport} } select_transport() { set_transport $transport dbg "Testing $transport-login to target ${target} portal ${portal}" try_login; if [ $? != 0 -a "$force" = "0" ]; then set_transport tcp dbg "starting to test tcp-login to target ${target} portal ${portal}" try_login; fi } check_iscsid() { #check if iscsid is running pidof iscsid &>/dev/null ret=$? if [ $ret -ne 0 ]; then echo "iscsid is not running" echo "Exiting..." exit 1 fi } check_iscsid initialize parse_cmdline "$@" discover open-iscsi-2.0.873/utils/md5.c000066400000000000000000000165361175631155400157600ustar00rootroot00000000000000/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' header * definitions; now uses stuff from dpkg's config.h. * - Ian Jackson . * Still in the public domain. */ #include #include "md5.h" #if (__BYTE_ORDER == __BIG_ENDIAN) /* * we can compile this away for little endian since * it does not do anything on those archs */ void byteSwap(uint32_t * buf, unsigned words) { md5byte *p = (md5byte *) buf; do { *buf++ = (uint32_t) ((unsigned) p[3] << 8 | p[2]) << 16 | ((unsigned) p[1] << 8 | p[0]); p += 4; } while (--words); } #else #define byteSwap(buf,words) #endif /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bytes[0] = 0; ctx->bytes[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *ctx, md5byte const *buf, unsigned len) { uint32_t t; /* Update byte count */ t = ctx->bytes[0]; if ((ctx->bytes[0] = t + len) < t) ctx->bytes[1]++; /* Carry from low to high */ t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ if (t > len) { memcpy((md5byte *) ctx->in + 64 - t, buf, len); return; } /* First chunk is an odd size */ memcpy((md5byte *) ctx->in + 64 - t, buf, t); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += t; len -= t; /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(md5byte digest[16], struct MD5Context *ctx) { int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */ md5byte *p = (md5byte *) ctx->in + count; /* Set the first char of padding to 0x80. There is always room. */ *p++ = 0x80; /* Bytes of padding needed to make 56 bytes (-8..55) */ count = 56 - 1 - count; if (count < 0) { /* Padding forces an extra block */ memset(p, 0, count + 8); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); p = (md5byte *) ctx->in; count = 56; } memset(p, 0, count); byteSwap(ctx->in, 14); /* Append length in bits and transform */ ctx->in[14] = ctx->bytes[0] << 3; ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29; MD5Transform(ctx->buf, ctx->in); byteSwap(ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof (ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f,w,x,y,z,in,s) \ (w += f(x,y,z) + in, w = (w<>(32-s)) + x) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void MD5Transform(uint32_t buf[4], uint32_t const in[16]) { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #endif open-iscsi-2.0.873/utils/md5.h000066400000000000000000000025021175631155400157510ustar00rootroot00000000000000/* * This is the header file for the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' * header definitions; now uses stuff from dpkg's config.h * - Ian Jackson . * Still in the public domain. */ #ifndef MD5_H #define MD5_H #include #define md5byte unsigned char struct MD5Context { uint32_t buf[4]; uint32_t bytes[2]; uint32_t in[16]; }; void MD5Init(struct MD5Context *context); void MD5Update(struct MD5Context *context, md5byte const *buf, unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *context); void MD5Transform(uint32_t buf[4], uint32_t const in[16]); #endif /* !MD5_H */ open-iscsi-2.0.873/utils/open-isns/000077500000000000000000000000001175631155400170275ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/COPYING000066400000000000000000000634761175631155400201020ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-iscsi-2.0.873/utils/open-isns/ChangeLog000066400000000000000000000024541175631155400206060ustar00rootroot00000000000000Under development: 2007-09-27: Fixed a serious interoperability bug Added SLP support (using openslp) Init script (courtesy Albert Pauw) 2007-09-18: Fixed a number of bugs Added more test cases Implemented default DD Support autoconf, and building with/without openssl 2007-08-24: Improved discovery domain handling Implemented DD deregistration Backward compat fixes for older openssl versions Made SCN more robust, SCN state now persists across server restarts More regression tests 2007-07-27: Implemented SCN and ESI Created iSNS discovery daemon (isnsdd) Rewrote the policy handling a bit Started to write some regression test code Better manpages 2007-07-12: DevGetNext support You can now define policies linking authentication to permitted storage node names, permitted entity names, etc. Implemented DDReg Queries and GetNext are now scoped to discovery domains Lots of little bits and pieces for RFC conformance 2005-07-18: Public snapshot released DSA based authentication Deregistration Simple file backed storage for the iSNS database Entity Registration Period + Timestamp support (server side), and entity expiration isnsd now writes a pid file Improved manual pages DevGetNext support under development 2007-05-11: First public release, supporting register/query open-iscsi-2.0.873/utils/open-isns/HACKING000066400000000000000000000021451175631155400200200ustar00rootroot00000000000000 When hacking on open-isns, or when trying to locate a problem, the following information may be useful: - You can start the daemon using the -f option, which prevents it from backgrounding itself. Crucial if you want to run it in a debugger, or under strace. This option works for isnsd and isnsdd - All tools support the "-d" option to enable debugging. In general, you want to use "-d all" to turn on all debugging options. However, you can select individual debug facilities - check out the manpages and/or the source code in logging.c - If isnsd crashes, and you suspect memory corruption, you can compile open-isns with memory debugging enabled. Re-run the configure script and add the option --enable-memdebug. Then run "make clean all" to rebuild everything. Memory debugging can be chosen at run-time by setting the ISNS_MDEBUG environment variable, and re-starting the application: export ISNS_MDEBUG=1 ./isnsd -f -d all Memory debugging works for all memory allocations done by the Open-iSNS code, but does not affect memory allocations by other libraries (such as glibc or openssl). open-iscsi-2.0.873/utils/open-isns/Makefile.in000066400000000000000000000024111175631155400210720ustar00rootroot00000000000000prefix = @prefix@ exec_prefix = @exec_prefix@ sbindir = @sbindir@ mandir = @mandir@ etcdir = /etc vardir = /var/lib/isns SBINDIR = $(INSTALL_ROOT)$(sbindir) ETCDIR = $(INSTALL_ROOT)$(etcdir) CFGDIR = $(ETCDIR)/isns MANDIR = $(INSTALL_ROOT)$(mandir) VARDIR = $(INSTALL_ROOT)$(vardir) CC = @CC@ CPPFLAGS= @CPPFLAGS@ CFLAGS = @CFLAGS@ -I. LDFLAGS = @LDFLAGS@ LIB = libisns.a LIBOBJS = server.o \ client.o \ objects.o \ callback.o \ timer.o \ vendor.o \ db.o \ db-file.o \ db-policy.o \ relation.o \ scope.o \ message.o \ security.o \ authblock.o \ policy.o \ register.o \ query.o \ getnext.o \ deregister.o \ esi.o \ scn.o \ dd.o \ entity.o \ portal-group.o \ storage-node.o \ domain.o \ simple.o \ tags.o \ attrs.o \ export.o \ socket.o \ slp.o \ error.o \ logging.o \ config.o \ parser.o \ buffer.o \ pidfile.o \ sysdep-unix.o \ util.o \ bitvector.o \ mdebug.o SECLINK = @SECLIBS@ SLPLINK = @SLPLIBS@ SLPLIN = @SLPLIBS@ all: $(LIB) clean distclean:: rm -f *.o $(LIB) *~ distclean:: rm -f config.h Makefile config.status config.log rm -rf autom4te.cache $(LIB): $(LIBOBJS) ar cr $@ $(LIBOBJS) depend: gcc $(CFLAGS) -M `ls *.c` > .depend -include .depend open-iscsi-2.0.873/utils/open-isns/README000066400000000000000000000133321175631155400177110ustar00rootroot00000000000000 Welcome to Open-iSNS ==================== This is a partial implementation of iSNS, according to RFC4171. The implementation is still somewhat incomplete, but I'm releasing it for your reading pleasure. The distribution comprises isnsd This is the iSNS server, supporting persistent storage of registrations in a file based database. isnsadm A command line utility for querying the iSNS database, and for registering/deregistering nodes and portals isnsdd An iSNS Discovery Daemon, which is still very much work in progress. The daemon is supposed to handle all the bit banging and server communications required to register a node, its portals, and to maintain the registration. It is also supposed to use the iSNS State Change Notification framework to learn of new targets or initiators coming online, and inform local services (such as the iSCSI initiator daemon) about these changes. Thanks! ------- Many thanks to Albert Pauw for his fearless testing of snapshots, and his copious feedback! What works, after a fashion: ---------------------------- - For now, I've been focusing on getting the iSCSI part to work. There is some very basic support for FC objects, but this will be hardly useful yet. - Registration, deregistration, query, getnext You can use isnsadm to register iSCSI nodes, and portals. isnsadm also illustrates how this is supposed to be used from the client perspective. - Discovery domains are supported mostly. The administrator can create discovery domains using isnsadm, and place storage nodes in domains. Queries by clients are scoped by their discovery domains membership, so that they will be unable to see nodes not part of a shared DD. Open-iSNS currently does not allow clients to place themselves in a DD. Optionally, storage nodes that are not in any discovery domain will be placed in a "default DD" (see the DefaultDiscoveryDomain in isnsd.conf). - ESI, supported both by the server and the discovery daemon - SCN, supported by the server and the discovery daemon What is still missing --------------------- - Better documentation (esp. a HOWTO on getting started with iSNS) - DD Sets - Various bits and pieces of the protocol - FC support Building Open-iSNS ------------------ The Open-iSNS build is now based on autoconf. The distributed tarball should include a configure script and a config.h.in file generated from configure.ac. If these are missing, you can generate them by running autoconf autoheader For most people, it should be sufficient to run configure without any arguments, or at most with the option --prefix. If run without --prefix, program files, manpages etc will be installed below /usr/local. To have everything installed /usr/bin, /usr/share/man etc, run it as ./configure --prefix=/usr Dependencies: - If you want to build Open-iSNS with support for authentication, you need the OpenSSL libraries and header files installed. The configure script should pick up the presence of these libraries, and enable security support automatically. To disable this explicitly in your build, pass the --without-security option to configure. - If you want to build Open-iSNS with SLP support, you need the OpenSLP library and header file installed. The configure script should pick up the presence of this library, and enable SLP support automatically. To disable this explicitly in your build, pass the --without-slp option to configure. When configure is run, it checks for a the presence of a number of headers and libraries in your system (the results of most of these checks are currently ignored :-). Then, it creates a Makefile and a config.h include file. With these in place, you can build the binaries and libraries: make make install Getting started --------------- On the iSNS server, you need to generate a server key and install it. The simplest way is probably to use the isnssetup script included in the source package. For each client you wish to use, you should then iSNS Security ------------- This implementation of iSNS supports authentication, as descibed in RFC 4171. In order to use it, you have to create DSA keys for the server and all clients. iSNS uses conceptually the same security mechanism as SLP, and identifies principals by a "Security Parameter Index", which is essentially a string identifying a key. Open-iSNS fully supports DSA based security, and offers a flexible policy mechanism that ties an SPI to a network entity and the storage node names it is allowed to use. For an introduction to the security model used by Open-iSNS, refer to the isns_config(5) manual page. An overview on setting up the iSNS server for authentication is given in the EXAMPLES section of the isnsadm(8) manual page. Downloading Open-iSNS --------------------- Open-iSNS is available for download from http://oss.oracle.com/~okir/open-isns You have to grab the latest tarball and compile it; fancy things such as RPMs are not available yet. ------------------------------------------------------------------ COPYRIGHT NOTICE Copyright (C) 2007 Olaf Kirch. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA open-iscsi-2.0.873/utils/open-isns/TODO000066400000000000000000000056551175631155400175320ustar00rootroot00000000000000Documentation: - Add HOWTO isnsd: - When registering a node, use the default EID given in its policy (avoid the isns.control trap) - make PGs children of the iSCSI storage node they're associated with? - Implement missing functions isnsadm: - support iSNS server discovery through DNS SRV records, and SLP isnsdd: - support iSNS server discovery through DNS SRV records, and SLP - At startup, query the server for the list of visible nodes/portals - When receiving an SCN, query for the node's portals, authmethod and such, and compare that to what we have cached - At regular intervals, repeat the query for all visible nodes/portals, and do a diff with our shadow DB - At regular intervals, check whether the portals we registered for ESI are seeing the server's ESI messages. DevAttrReg: - Refuse registration of nodes inside the CONTROL entity, unless it's a control node. - If the client uses REPLACE, is it okay for the entity's index to change? - security: optionally validate the IP addresses a client registers (either against a static policy, or using DNS). - relaxed security model: require privilege for registration of targets; anyone can register an initiator? - Gracefully handle registrations where the client specifies an index attribute, as long as it matches the next_index DevAttrQuery: - fix --local --query policy-index=iqn.1969-12.brummo and write test case - fix the way we enumerate related objects - ensure DD discovery works (5.6.5.2): DD membership can be discovered through the DevAttrQry message by including either DD member attributes (i.e., DD Member iSCSI Index, DD Member iSCSI Node, DD Member iFCP Node, DD Member Portal Index, DD Member Portal IP Addr, and DD Member Portal TCP/UDP) or the object key of the Storage Node or Portal (i.e., iSCSI Name, iSCSI Index, Portal IP Addr, Portal TCP/UDP Port, and Portal Index) in the Operating Attributes. Using DD member attributes SHALL return both registered and unregistered member Storage Nodes and/or Portals of a DD. DevAttrQry messages using the Storage Node and/or Portal object key SHALL return only member Storage Nodes or Portals that are currently registered in the iSNS database. DevAttrDereg: - PG Removal code: ignore nodes/portal that are dead - review security - cancel any SCN/ESI callbacks SCN: - Trigger a mgmt reg SCN when accepting a mgmt registration SCNEvent: - Implement ESI: - Right now the way we re-establish ESI state after database reload is awkward. DDReg: - Write test cases DDDereg: - Write test cases DDSReg/DDSDereg: - Implement Heartbeat: - Implement message send - Implement failover? Security: - Allow policies without key? - Implement simple default policies linking client IP + hostname (network entity) + storage node names Renaming - Add isns_ prefix to all visible functions Socket code: - impose upper limit on the reassembly buffer open-iscsi-2.0.873/utils/open-isns/aclocal/000077500000000000000000000000001175631155400204255ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/aclocal/config.guess000066400000000000000000001264711175631155400227550ustar00rootroot00000000000000#! /bin/sh # Attempt to guess a canonical system name. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. timestamp='2005-05-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA # 02110-1301, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Per Bothner . # Please send patches to . Submit a context # diff and a properly formatted ChangeLog entry. # # This script attempts to guess a canonical system name similar to # config.sub. If it succeeds, it prints the system name on stdout, and # exits with 0. Otherwise, it exits with 1. # # The plan is that this can be called by configure scripts if you # don't specify an explicit build system type. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep __ELF__ >/dev/null then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; amd64:OpenBSD:*:*) echo x86_64-unknown-openbsd${UNAME_RELEASE} exit ;; amiga:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit ;; cats:OpenBSD:*:*) echo arm-unknown-openbsd${UNAME_RELEASE} exit ;; hp300:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit ;; luna88k:OpenBSD:*:*) echo m88k-unknown-openbsd${UNAME_RELEASE} exit ;; mac68k:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit ;; macppc:OpenBSD:*:*) echo powerpc-unknown-openbsd${UNAME_RELEASE} exit ;; mvme68k:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit ;; mvme88k:OpenBSD:*:*) echo m88k-unknown-openbsd${UNAME_RELEASE} exit ;; mvmeppc:OpenBSD:*:*) echo powerpc-unknown-openbsd${UNAME_RELEASE} exit ;; sgi:OpenBSD:*:*) echo mips64-unknown-openbsd${UNAME_RELEASE} exit ;; sun3:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerppc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` exit ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm:riscos:*:*|arm:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:SunOS:5.*:*) echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[45]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then # avoid double evaluation of $set_cc_for_build test -n "$CC_FOR_BUILD" || eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep __LP64__ >/dev/null then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; i*:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; x86:Interix*:[34]*) echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//' exit ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; arm*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; cris:Linux:*:*) echo cris-axis-linux-gnu exit ;; crisv32:Linux:*:*) echo crisv32-axis-linux-gnu exit ;; frv:Linux:*:*) echo frv-unknown-linux-gnu exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; mips:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef mips #undef mipsel #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=mipsel #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=mips #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef mips64 #undef mips64el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=mips64el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=mips64 #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; ppc:Linux:*:*) echo powerpc-unknown-linux-gnu exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-gnu exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-gnu ;; PA8*) echo hppa2.0-unknown-linux-gnu ;; *) echo hppa-unknown-linux-gnu ;; esac exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-gnu exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; x86_64:Linux:*:*) echo x86_64-unknown-linux-gnu exit ;; i*86:Linux:*:*) # The BFD linker knows what the default object file format is, so # first see if it will tell us. cd to the root directory to prevent # problems with other programs or directories called `ld' in the path. # Set LC_ALL=C to ensure ld outputs messages in English. ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ | sed -ne '/supported targets:/!d s/[ ][ ]*/ /g s/.*supported targets: *// s/ .*// p'` case "$ld_supported_targets" in elf32-i386) TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" ;; a.out-i386-linux) echo "${UNAME_MACHINE}-pc-linux-gnuaout" exit ;; coff-i386) echo "${UNAME_MACHINE}-pc-linux-gnucoff" exit ;; "") # Either a pre-BFD a.out linker (linux-gnuoldld) or # one that does not give us useful --help. echo "${UNAME_MACHINE}-pc-linux-gnuoldld" exit ;; esac # Determine whether the default compiler is a.out or elf eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include #ifdef __ELF__ # ifdef __GLIBC__ # if __GLIBC__ >= 2 LIBC=gnu # else LIBC=gnulibc1 # endif # else LIBC=gnulibc1 # endif #else #ifdef __INTEL_COMPILER LIBC=gnu #else LIBC=gnuaout #endif #endif #ifdef __dietlibc__ LIBC=dietlibc #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=` test x"${LIBC}" != x && { echo "${UNAME_MACHINE}-pc-linux-${LIBC}" exit } test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i386. echo i386-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown case $UNAME_PROCESSOR in *86) UNAME_PROCESSOR=i686 ;; unknown) UNAME_PROCESSOR=powerpc ;; esac echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NSE-?:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; esac #echo '(No uname command or uname output not recognized.)' 1>&2 #echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; c34*) echo c34-convex-bsd exit ;; c38*) echo c38-convex-bsd exit ;; c4*) echo c4-convex-bsd exit ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: open-iscsi-2.0.873/utils/open-isns/aclocal/config.sub000066400000000000000000000755001175631155400224140ustar00rootroot00000000000000#! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. timestamp='2005-05-12' # This file is (in principle) common to ALL GNU software. # The presence of a machine in this file suggests that SOME GNU software # can handle that machine. It does not imply ALL GNU software can. # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA # 02110-1301, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Please send patches to . Submit a context # diff and a properly formatted ChangeLog entry. # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \ kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray) os= basic_machine=$1 ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ | bfin \ | c4x | clipper \ | d10v | d30v | dlx | dsp16xx \ | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64vr | mips64vrel \ | mips64orion | mips64orionel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | msp430 \ | ns16k | ns32k \ | openrisc | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ | pyramid \ | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b \ | strongarm \ | tahoe | thumb | tic4x | tic80 | tron \ | v850 | v850e \ | we32k \ | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \ | z8k) basic_machine=$basic_machine-unknown ;; m6811 | m68hc11 | m6812 | m68hc12) # Motorola 68HC11/12. basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64vr-* | mips64vrel-* \ | mips64orion-* | mips64orionel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | msp430-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ | pyramid-* \ | romp-* | rs6000-* \ | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \ | tahoe-* | thumb-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tron-* \ | v850-* | v850e-* | vax-* \ | we32k-* \ | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \ | xstormy16-* | xtensa-* \ | ymp-* \ | z8k-*) ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; c90) basic_machine=c90-cray os=-unicos ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16c) basic_machine=cr16c-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; # I'm not sure what "Sysv32" means. Should this be sysv3.2? i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; mingw32) basic_machine=i386-pc os=-mingw32 ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; msdos) basic_machine=i386-pc os=-msdos ;; mvs) basic_machine=i370-ibm os=-mvs ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; or32 | or32-*) basic_machine=or32-unknown os=-coff ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc) basic_machine=powerpc-unknown ;; ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tic54x | c54x*) basic_machine=tic54x-unknown os=-coff ;; tic55x | c55x*) basic_machine=tic55x-unknown os=-coff ;; tic6x | c6x*) basic_machine=tic6x-unknown os=-coff ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sh64) basic_machine=sh64-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* \ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* | -skyos*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -kaos*) os=-kaos ;; -zvmoe) os=-zvmoe ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 # This also exists in the configure program, but was not the # default. # os=-sunos4 ;; m68*-cisco) os=-aout ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: open-iscsi-2.0.873/utils/open-isns/aclocal/install-sh000066400000000000000000000127221175631155400224320ustar00rootroot00000000000000#!/bin/sh # # install - install a program, script, or datafile # This comes from X11R5 (mit/util/scripts/install.sh). # # Copyright 1991 by the Massachusetts Institute of Technology # # Permission to use, copy, modify, distribute, and sell this software and its # documentation for any purpose is hereby granted without fee, provided that # the above copyright notice appear in all copies and that both that # copyright notice and this permission notice appear in supporting # documentation, and that the name of M.I.T. not be used in advertising or # publicity pertaining to distribution of the software without specific, # written prior permission. M.I.T. makes no representations about the # suitability of this software for any purpose. It is provided "as is" # without express or implied warranty. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. It can only install one file at a time, a restriction # shared with many OS's install programs. # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit="${DOITPROG-}" # put in absolute paths if you don't have them in your path; or use env. vars. mvprog="${MVPROG-mv}" cpprog="${CPPROG-cp}" chmodprog="${CHMODPROG-chmod}" chownprog="${CHOWNPROG-chown}" chgrpprog="${CHGRPPROG-chgrp}" stripprog="${STRIPPROG-strip}" rmprog="${RMPROG-rm}" mkdirprog="${MKDIRPROG-mkdir}" transformbasename="" transform_arg="" instcmd="$mvprog" chmodcmd="$chmodprog 0755" chowncmd="" chgrpcmd="" stripcmd="" rmcmd="$rmprog -f" mvcmd="$mvprog" src="" dst="" dir_arg="" while [ x"$1" != x ]; do case $1 in -c) instcmd="$cpprog" shift continue;; -d) dir_arg=true shift continue;; -m) chmodcmd="$chmodprog $2" shift shift continue;; -o) chowncmd="$chownprog $2" shift shift continue;; -g) chgrpcmd="$chgrpprog $2" shift shift continue;; -s) stripcmd="$stripprog" shift continue;; -t=*) transformarg=`echo $1 | sed 's/-t=//'` shift continue;; -b=*) transformbasename=`echo $1 | sed 's/-b=//'` shift continue;; *) if [ x"$src" = x ] then src=$1 else # this colon is to work around a 386BSD /bin/sh bug : dst=$1 fi shift continue;; esac done if [ x"$src" = x ] then echo "install: no input file specified" exit 1 else true fi if [ x"$dir_arg" != x ]; then dst=$src src="" if [ -d $dst ]; then instcmd=: chmodcmd="" else instcmd=mkdir fi else # Waiting for this to be detected by the "$instcmd $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if [ -f $src -o -d $src ] then true else echo "install: $src does not exist" exit 1 fi if [ x"$dst" = x ] then echo "install: no destination specified" exit 1 else true fi # If destination is a directory, append the input filename; if your system # does not like double slashes in filenames, you may need to add some logic if [ -d $dst ] then dst="$dst"/`basename $src` else true fi fi ## this sed command emulates the dirname command dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` # Make sure that the destination directory exists. # this part is taken from Noah Friedman's mkinstalldirs script # Skip lots of stat calls in the usual case. if [ ! -d "$dstdir" ]; then defaultIFS=' ' IFS="${IFS-${defaultIFS}}" oIFS="${IFS}" # Some sh's can't handle IFS=/ for some reason. IFS='%' set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` IFS="${oIFS}" pathcomp='' while [ $# -ne 0 ] ; do pathcomp="${pathcomp}${1}" shift if [ ! -d "${pathcomp}" ] ; then $mkdirprog "${pathcomp}" else true fi pathcomp="${pathcomp}/" done fi if [ x"$dir_arg" != x ] then $doit $instcmd $dst && if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi else # If we're going to rename the final executable, determine the name now. if [ x"$transformarg" = x ] then dstfile=`basename $dst` else dstfile=`basename $dst $transformbasename | sed $transformarg`$transformbasename fi # don't allow the sed command to completely eliminate the filename if [ x"$dstfile" = x ] then dstfile=`basename $dst` else true fi # Make a temp file name in the proper directory. dsttmp=$dstdir/#inst.$$# # Move or copy the file name to the temp name $doit $instcmd $src $dsttmp && trap "rm -f ${dsttmp}" 0 && # and set any options; do chmod last to preserve setuid bits # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $instcmd $src $dsttmp" command. if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && # Now rename the file to the real destination. $doit $rmcmd -f $dstdir/$dstfile && $doit $mvcmd $dsttmp $dstdir/$dstfile fi && exit 0 open-iscsi-2.0.873/utils/open-isns/attrs.c000066400000000000000000001041401175631155400203300ustar00rootroot00000000000000/* * Handle iSNS attributes and attribute lists * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "util.h" #include "vendor.h" #include "attrs.h" #include "isns.h" /* Implementation limit - sanity checking */ #define ISNS_ATTR_MAX_LEN 8192 static void __isns_attr_set_value(isns_attr_t *, const isns_value_t *); /* * Allocate an attribute */ isns_attr_t * isns_attr_alloc(uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value) { isns_attr_t *attr; if (tag_type == NULL) tag_type = isns_tag_type_by_id(tag); attr = isns_calloc(1, sizeof(*attr)); if (!attr) isns_fatal("Out of memory!\n"); attr->ia_users = 1; attr->ia_tag_id = tag; attr->ia_tag = tag_type; __isns_attr_set_value(attr, value); return attr; } isns_attr_t * isns_attr_get(isns_attr_t *attr) { if (attr) { isns_assert(attr->ia_users); attr->ia_users++; } return attr; } void isns_attr_release(isns_attr_t *attr) { const isns_attr_type_t *type; isns_assert(attr->ia_users); if (--(attr->ia_users)) return; type = attr->ia_value.iv_type; if (type->it_destroy) type->it_destroy(&attr->ia_value); isns_free(attr); } /* * Assign a value to an attribute */ void __isns_attr_set_value(isns_attr_t *attr, const isns_value_t *new_value) { const isns_attr_type_t *type, *old_type; isns_value_t *old_value; old_value = &attr->ia_value; if (old_value == new_value) return; old_type = old_value->iv_type; if (old_type && old_type->it_destroy) old_type->it_destroy(old_value); if (!new_value || !(type = new_value->iv_type)) type = attr->ia_tag->it_type; /* When assigning the value to the attr, check * whether it needs special attention. */ if (new_value) { if (type->it_assign) { type->it_assign(&attr->ia_value, new_value); } else { attr->ia_value = *new_value; } } attr->ia_value.iv_type = type; } /* * Compare two attributes. * Returns non-null when attributes are the same, else 0. */ int isns_attr_match(const isns_attr_t *a, const isns_attr_t *b) { const isns_attr_type_t *type; if (a->ia_tag_id != b->ia_tag_id) return 0; /* NIL acts as a wildcard */ if (a->ia_value.iv_type == &isns_attr_type_nil || b->ia_value.iv_type == &isns_attr_type_nil) return 1; if (a->ia_value.iv_type != b->ia_value.iv_type) return 0; type = a->ia_value.iv_type; if (type->it_match) return type->it_match(&a->ia_value, &b->ia_value); return !memcmp(&a->ia_value, &b->ia_value, sizeof(isns_value_t)); } /* * Lexicographical comparison of two attributes. * Returns -1 when a is less than b, +1 when a is greater than * b, and 0 if equal. */ int isns_attr_compare(const isns_attr_t *a, const isns_attr_t *b) { const isns_attr_type_t *type = a->ia_value.iv_type; isns_assert(a->ia_tag_id == b->ia_tag_id); if (type != b->ia_value.iv_type) { /* One of them must be NIL */ if (type == &isns_attr_type_nil) return -1; return 1; } /* If both are NIL, consider them equal */ if (type == &isns_attr_type_nil) return 0; /* A few types need special comparison functions, but * most don't. The reason is, we don't care whether the * ordering this creates is the "canonical" ordering for * this type, eg for integers. All that matters is that * there is some consistent ordering suitable for * DevGetNext. */ if (type->it_compare) return type->it_compare(&a->ia_value, &b->ia_value); return memcmp(&a->ia_value, &b->ia_value, sizeof(isns_value_t)); } /* * Convert a string to an attribute */ isns_attr_t * isns_attr_from_string(uint32_t tag, const char *string) { const isns_tag_type_t *tag_type; int (*parse)(isns_value_t *, const char *); isns_value_t value; memset(&value, 0, sizeof(value)); tag_type = isns_tag_type_by_id(tag); if (!tag_type) return NULL; parse = tag_type->it_parse; if (parse == NULL) parse = tag_type->it_type->it_parse; if (!parse || !parse(&value, string)) return NULL; return isns_attr_alloc(tag, tag_type, &value); } /* * Initialize an attribute list. */ void isns_attr_list_init(isns_attr_list_t *list) { memset(list, 0, sizeof(*list)); } static inline void __isns_attr_list_resize(isns_attr_list_t *list, unsigned int count) { unsigned int max; max = (list->ial_count + 15) & ~15; if (count < max) return; count = (count + 15) & ~15; list->ial_data = isns_realloc(list->ial_data, count * sizeof(isns_attr_t *)); if (!list->ial_data) isns_fatal("Out of memory!\n"); } void isns_attr_list_append_list(isns_attr_list_t *dst, const isns_attr_list_t *src) { unsigned int i, j; __isns_attr_list_resize(dst, dst->ial_count + src->ial_count); j = dst->ial_count; for (i = 0; i < src->ial_count; ++i, ++j) { isns_attr_t *attr = src->ial_data[i]; dst->ial_data[j] = attr; attr->ia_users++; } dst->ial_count = j; } void isns_attr_list_copy(isns_attr_list_t *dst, const isns_attr_list_t *src) { isns_attr_list_destroy(dst); isns_attr_list_append_list(dst, src); } void isns_attr_list_destroy(isns_attr_list_t *list) { unsigned int i; for (i = 0; i < list->ial_count; ++i) { isns_attr_t *attr = list->ial_data[i]; isns_attr_release(attr); } if (list->ial_data) isns_free(list->ial_data); memset(list, 0, sizeof(*list)); } int isns_attr_list_remove_tag(isns_attr_list_t *list, uint32_t tag) { unsigned int i = 0, j = 0, removed = 0; for (i = 0; i < list->ial_count; ++i) { isns_attr_t *attr = list->ial_data[i]; if (attr->ia_tag_id == tag) { isns_attr_release(attr); removed++; } else { list->ial_data[j++] = attr; } } list->ial_count = j; return removed; } /* * Locate the given attribute in the list, remove it * and any following attributes that have a tag from the * @subordinate_tags list. This is used by the DDDereg * code to remove DD members. */ int isns_attr_list_remove_member(isns_attr_list_t *list, const isns_attr_t *match, const uint32_t *subordinate_tags) { unsigned int i = 0, j = 0, k, removed = 0, purging = 0; while (i < list->ial_count) { isns_attr_t *attr = list->ial_data[i++]; if (purging && subordinate_tags) { for (k = 0; subordinate_tags[k]; ++k) { if (attr->ia_tag_id == subordinate_tags[k]) goto purge_attr; } } purging = 0; if (!isns_attr_match(attr, match)) { list->ial_data[j++] = attr; continue; } purge_attr: isns_attr_release(attr); purging = 1; removed++; } list->ial_count = j; return removed; } /* * Find the first attribute with the given tag */ static inline isns_attr_t * __isns_attr_list_find(const isns_attr_list_t *list, uint32_t tag) { isns_attr_t *attr; unsigned int i; for (i = 0; i < list->ial_count; ++i) { attr = list->ial_data[i]; if (attr->ia_tag_id == tag) return attr; } return NULL; } /* * Add a new attribute at the end of the list */ static inline void __isns_attr_list_append_attr(isns_attr_list_t *list, isns_attr_t *attr) { __isns_attr_list_resize(list, list->ial_count + 1); list->ial_data[list->ial_count++] = attr; } void isns_attr_list_append_attr(isns_attr_list_t *list, isns_attr_t *attr) { attr->ia_users++; __isns_attr_list_append_attr(list, attr); } /* * Append an element to an attribute list */ static void __isns_attr_list_append(isns_attr_list_t *list, uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value) { isns_attr_t *attr; if (tag_type == NULL) tag_type = isns_tag_type_by_id(tag); if (value->iv_type != &isns_attr_type_nil && value->iv_type != tag_type->it_type) { isns_warning("Using wrong type (%s) " "when encoding attribute %04x (%s) - should be %s\n", value->iv_type->it_name, tag, tag_type->it_name, tag_type->it_type->it_name); } attr = isns_attr_alloc(tag, tag_type, value); __isns_attr_list_append_attr(list, attr); } /* * Update an element to an attribute list */ static void __isns_attr_list_update(isns_attr_list_t *list, uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value) { const isns_attr_type_t *type = value->iv_type; isns_attr_t *attr; if (tag_type == NULL) tag_type = isns_tag_type_by_id(tag); if (type != &isns_attr_type_nil && type != tag_type->it_type) { isns_warning("Using wrong type (%s) " "when encoding attribute %04x (%s) - should be %s\n", type->it_name, tag, tag_type->it_name, tag_type->it_type->it_name); } if (tag_type->it_multiple || (attr = __isns_attr_list_find(list, tag)) == NULL) { attr = isns_attr_alloc(tag, tag_type, NULL); __isns_attr_list_append_attr(list, attr); } __isns_attr_set_value(attr, value); } /* * Append an element to an attribute list - public interface */ void isns_attr_list_append_value(isns_attr_list_t *list, uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value) { __isns_attr_list_append(list, tag, tag_type, value); } /* * Update an element of an attribute list - public interface */ void isns_attr_list_update_value(isns_attr_list_t *list, uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value) { __isns_attr_list_update(list, tag, tag_type, value); } void isns_attr_list_update_attr(isns_attr_list_t *list, const isns_attr_t *attr) { __isns_attr_list_update(list, attr->ia_tag_id, attr->ia_tag, &attr->ia_value); } /* * Replace an attribute on a list */ int isns_attr_list_replace_attr(isns_attr_list_t *list, isns_attr_t *attr) { unsigned int i; for (i = 0; i < list->ial_count; ++i) { isns_attr_t *other = list->ial_data[i]; if (other->ia_tag_id == attr->ia_tag_id) { list->ial_data[i] = attr; attr->ia_users++; isns_attr_release(other); return 1; } } return 0; } /* * Retrieve an element of an attribute list */ int isns_attr_list_get_attr(const isns_attr_list_t *list, uint32_t tag, isns_attr_t **result) { *result = __isns_attr_list_find(list, tag); return *result != NULL; } int isns_attr_list_get_value(const isns_attr_list_t *list, uint32_t tag, isns_value_t *value) { isns_attr_t *attr; if (!(attr = __isns_attr_list_find(list, tag))) return 0; *value = attr->ia_value; return 1; } int isns_attr_list_get_uint32(const isns_attr_list_t *list, uint32_t tag, uint32_t *value) { isns_attr_t *attr; if (!(attr = __isns_attr_list_find(list, tag)) || !ISNS_ATTR_IS_UINT32(attr)) return 0; *value = attr->ia_value.iv_uint32; return 1; } int isns_attr_list_get_ipaddr(const isns_attr_list_t *list, uint32_t tag, struct in6_addr *value) { isns_attr_t *attr; if (!(attr = __isns_attr_list_find(list, tag)) || !ISNS_ATTR_IS_IPADDR(attr)) return 0; *value = attr->ia_value.iv_ipaddr; return 1; } int isns_attr_list_get_string(const isns_attr_list_t *list, uint32_t tag, const char **value) { isns_attr_t *attr; if (!(attr = __isns_attr_list_find(list, tag)) || !ISNS_ATTR_IS_STRING(attr)) return 0; *value = attr->ia_value.iv_string; return 1; } int isns_attr_list_contains(const isns_attr_list_t *list, uint32_t tag) { return __isns_attr_list_find(list, tag) != NULL; } /* * Some attribute types have an implied ordering, * which is needed for GetNext. This is used to * compare two lists. */ /* * Typed versions of isns_attr_list_append */ void isns_attr_list_append_nil(isns_attr_list_t *list, uint32_t tag) { isns_value_t var = ISNS_VALUE_INIT(nil, 0); __isns_attr_list_append(list, tag, NULL, &var); } void isns_attr_list_append_string(isns_attr_list_t *list, uint32_t tag, const char *value) { isns_value_t var = ISNS_VALUE_INIT(string, (char *) value); __isns_attr_list_append(list, tag, NULL, &var); } void isns_attr_list_append_uint32(isns_attr_list_t *list, uint32_t tag, uint32_t value) { isns_value_t var = ISNS_VALUE_INIT(uint32, value); __isns_attr_list_append(list, tag, NULL, &var); } void isns_attr_list_append_int32(isns_attr_list_t *list, uint32_t tag, int32_t value) { isns_value_t var = ISNS_VALUE_INIT(int32, value); __isns_attr_list_append(list, tag, NULL, &var); } void isns_attr_list_append_uint64(isns_attr_list_t *list, uint32_t tag, int64_t value) { isns_value_t var = ISNS_VALUE_INIT(uint64, value); __isns_attr_list_append(list, tag, NULL, &var); } void isns_attr_list_append_ipaddr(isns_attr_list_t *list, uint32_t tag, const struct in6_addr *value) { isns_value_t var = ISNS_VALUE_INIT(ipaddr, *value); __isns_attr_list_append(list, tag, NULL, &var); } /* * Untyped version of isns_attr_list_append and isns_attr_list_update. * The caller must make sure that the type of @data matches the tag's type. */ int isns_attr_list_append(isns_attr_list_t *list, uint32_t tag, const void *data) { const isns_tag_type_t *tag_type; isns_value_t var; if (!(tag_type = isns_tag_type_by_id(tag))) return 0; var.iv_type = tag_type->it_type; if (!var.iv_type->it_set(&var, data)) return 0; __isns_attr_list_append(list, tag, tag_type, &var); return 1; } int isns_attr_list_update(isns_attr_list_t *list, uint32_t tag, const void *data) { const isns_tag_type_t *tag_type; isns_attr_type_t *type; isns_value_t var; if (!(tag_type = isns_tag_type_by_id(tag))) return 0; type = tag_type->it_type; var.iv_type = type; if (!type->it_set(&var, data)) return 0; __isns_attr_list_update(list, tag, tag_type, &var); return 1; } /* * Validate the attribute list. */ int isns_attr_validate(const isns_attr_t *attr, const isns_policy_t *policy) { const isns_tag_type_t *tag_type; tag_type = attr->ia_tag; if (tag_type->it_validate == NULL) return 1; return tag_type->it_validate(&attr->ia_value, policy); } int isns_attr_list_validate(const isns_attr_list_t *list, const isns_policy_t *policy, unsigned int function) { DECLARE_BITMAP(seen, __ISNS_TAG_MAX); unsigned int i; for (i = 0; i < list->ial_count; ++i) { const isns_tag_type_t *tag_type; isns_attr_t *attr = list->ial_data[i]; uint32_t tag = attr->ia_tag_id; unsigned int bit; if (attr == NULL) return ISNS_INTERNAL_ERROR; tag_type = attr->ia_tag; if (tag_type == NULL) return ISNS_INTERNAL_ERROR; bit = tag; if (OPENISNS_IS_PRIVATE_ATTR(tag)) bit -= OPENISNS_VENDOR_PREFIX; if (bit >= __ISNS_TAG_MAX) goto invalid; if (attr->ia_value.iv_type == &isns_attr_type_nil) { if (test_bit(seen, bit)) goto invalid; } else if (attr->ia_value.iv_type == tag_type->it_type) { if (!tag_type->it_multiple && test_bit(seen, bit)) goto invalid; if (!isns_attr_validate(attr, policy)) goto invalid; } else { return ISNS_INTERNAL_ERROR; } if (function == ISNS_DEVICE_ATTRIBUTE_REGISTER && tag_type->it_readonly) goto invalid; set_bit(seen, bit); } return ISNS_SUCCESS; invalid: switch (function) { case ISNS_DEVICE_ATTRIBUTE_REGISTER: return ISNS_INVALID_REGISTRATION; case ISNS_DEVICE_DEREGISTER: return ISNS_INVALID_DEREGISTRATION; case ISNS_DEVICE_ATTRIBUTE_QUERY: case ISNS_DEVICE_GET_NEXT: return ISNS_INVALID_QUERY; } return ISNS_ATTRIBUTE_NOT_IMPLEMENTED; } /* * Debug helper: print attribute list */ void isns_attr_list_print(const isns_attr_list_t *list, isns_print_fn_t *fn) { unsigned int i; for (i = 0; i < list->ial_count; ++i) isns_attr_print(list->ial_data[i], fn); } char * isns_attr_print_value(const isns_attr_t *attr, char *buffer, size_t size) { const isns_tag_type_t *tag_type = attr->ia_tag; const isns_attr_type_t *type = attr->ia_value.iv_type; if (tag_type->it_print && type == tag_type->it_type) tag_type->it_print(&attr->ia_value, buffer, size); else type->it_print(&attr->ia_value, buffer, size); return buffer; } void isns_attr_print(const isns_attr_t *attr, isns_print_fn_t *fn) { const isns_tag_type_t *tag_type = attr->ia_tag; const isns_attr_type_t *type = attr->ia_value.iv_type; uint32_t tag; char value[512], *vspec = ""; tag = attr->ia_tag_id; if (OPENISNS_IS_PRIVATE_ATTR(tag)) { tag -= OPENISNS_VENDOR_PREFIX; vspec = "v"; } fn(" %04x%1s %-12s: %s = %s\n", tag, vspec, type->it_name, tag_type? tag_type->it_name : "Unknown Attribute", isns_attr_print_value(attr, value, sizeof(value))); } /* * TLV encode a single attribute */ int isns_attr_encode(buf_t *bp, const isns_attr_t *attr) { const isns_value_t *value = &attr->ia_value; const isns_attr_type_t *type = value->iv_type; if (!buf_put32(bp, attr->ia_tag_id) || !type->it_encode(bp, value)) return ISNS_INTERNAL_ERROR; return ISNS_SUCCESS; } /* * TLV decode a single attribute */ int isns_attr_decode(buf_t *bp, isns_attr_t **result) { isns_attr_t *attr = NULL; isns_value_t *value; uint32_t tag, len; if (!buf_get32(bp, &tag) || !buf_get32(bp, &len)) goto msg_fmt_error; /* Attributes MUST be word aligned */ if (len & 3) goto msg_fmt_error; if (len > ISNS_ATTR_MAX_LEN) goto msg_fmt_error; /* Allocate the attribute */ attr = isns_attr_alloc(tag, NULL, NULL); value = &attr->ia_value; if (len == 0) value->iv_type = &isns_attr_type_nil; if (!value->iv_type->it_decode(bp, len, value)) goto msg_fmt_error; *result = attr; return ISNS_SUCCESS; msg_fmt_error: isns_error("Error decoding attribute, tag=0x%04x, len=%u\n", tag, len); if (attr) isns_attr_release(attr); return ISNS_MESSAGE_FORMAT_ERROR; } /* * Decode the list of TLV encoded attributes inside an * iSNS message. */ static int __isns_attr_list_decode(buf_t *bp, isns_attr_list_t *list, int delimited) { int status; while (buf_avail(bp)) { isns_attr_t *attr; status = isns_attr_decode(bp, &attr); if (status != ISNS_SUCCESS) return status; if (delimited && attr->ia_tag_id == ISNS_TAG_DELIMITER) { isns_attr_release(attr); break; } __isns_attr_list_append_attr(list, attr); } return ISNS_SUCCESS; } int isns_attr_list_decode(buf_t *bp, isns_attr_list_t *list) { return __isns_attr_list_decode(bp, list, 0); } int isns_attr_list_decode_delimited(buf_t *bp, isns_attr_list_t *list) { return __isns_attr_list_decode(bp, list, 1); } /* * Remove all attributes from a list save those matching * the given tags. */ void isns_attr_list_prune(isns_attr_list_t *list, const uint32_t *tags, unsigned int num_tags) { unsigned int i, j, k; for (i = j = 0; i < list->ial_count; ++i) { isns_attr_t *attr = list->ial_data[i]; for (k = 0; k < num_tags; ++k) { if (attr->ia_tag_id == tags[k]) { list->ial_data[j++] = attr; goto next; } } isns_attr_release(attr); next: ; } list->ial_count = j; } /* * TLV ecode the list of attributes to go with * iSNS message. */ int isns_attr_list_encode(buf_t *bp, const isns_attr_list_t *list) { unsigned int i, status = ISNS_SUCCESS; for (i = 0; i < list->ial_count; ++i) { struct isns_attr *attr = list->ial_data[i]; status = isns_attr_encode(bp, attr); if (status) break; } return status; } /* * Encode the delimiter attribute */ int isns_encode_delimiter(buf_t *bp) { uint32_t tag = 0, len = 0; if (!buf_put32(bp, tag) || !buf_put32(bp, len)) return ISNS_INTERNAL_ERROR; return ISNS_SUCCESS; } /* * Padded encoding */ static inline int isns_encode_padded(buf_t *bp, const void *ptr, size_t len) { if (!buf_put(bp, ptr, len)) return 0; if ((len & 3) == 0) return 1; return buf_put(bp, "\0\0\0", 4 - (len & 3)); } /* * Helper functions to deal with portal information */ void isns_portal_init(isns_portal_info_t *portal, const struct sockaddr *saddr, int proto) { const struct sockaddr_in *sin; memset(portal, 0, sizeof(*portal)); switch (saddr->sa_family) { case AF_INET6: portal->addr = *(const struct sockaddr_in6 *) saddr; break; case AF_INET: sin = (const struct sockaddr_in *) saddr; portal->addr.sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr; portal->addr.sin6_port = sin->sin_port; portal->addr.sin6_family = AF_INET6; break; default: isns_warning("Unknown address family in isns_portal_init\n"); return; } portal->proto = proto; } int isns_portal_from_attr_list(isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, const isns_attr_list_t *list) { const isns_attr_t *addr_attr = NULL, *port_attr = NULL; unsigned int i; for (i = 0; i + 1 < list->ial_count; ++i) { const isns_attr_t *attr = list->ial_data[i]; if (!ISNS_ATTR_IS_IPADDR(attr)) continue; if (addr_tag && attr->ia_tag_id != addr_tag) continue; addr_attr = attr; if (port_tag == 0) { port_attr = list->ial_data[i + 1]; goto extract_portal; } break; } /* We have a specific port tag. */ while (++i < list->ial_count) { const isns_attr_t *attr = list->ial_data[i]; if (attr->ia_tag_id == port_tag) { port_attr = attr; goto extract_portal; } } return 0; extract_portal: return isns_portal_from_attr_pair(portal, addr_attr, port_attr); } int isns_portal_from_attr_pair(isns_portal_info_t *portal, const isns_attr_t *addr_attr, const isns_attr_t *port_attr) { uint32_t portspec; memset(portal, 0, sizeof(*portal)); portal->addr.sin6_family = AF_INET6; if (!ISNS_ATTR_IS_IPADDR(addr_attr) || !ISNS_ATTR_IS_UINT32(port_attr)) return 0; portal->addr.sin6_addr = addr_attr->ia_value.iv_ipaddr; portspec = port_attr->ia_value.iv_uint32; portal->addr.sin6_port = htons(portspec & 0xffff); portal->proto = (portspec & ISNS_PORTAL_PORT_UDP_MASK)? IPPROTO_UDP : IPPROTO_TCP; return 1; } int isns_portal_to_attr_list(const isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, isns_attr_list_t *list) { uint32_t portspec; portspec = htons(portal->addr.sin6_port); if (portal->proto == IPPROTO_UDP) portspec |= ISNS_PORTAL_PORT_UDP_MASK; { isns_value_t addr_value = ISNS_VALUE_INIT(ipaddr, portal->addr.sin6_addr); isns_value_t port_value = ISNS_VALUE_INIT(uint32, portspec); isns_attr_list_update_value(list, addr_tag, NULL, &addr_value); isns_attr_list_update_value(list, port_tag, NULL, &port_value); } return 1; } const char * isns_portal_string(const isns_portal_info_t *portal) { const struct sockaddr_in6 *six = &portal->addr; static char buffer[128]; char abuf[128]; inet_ntop(six->sin6_family, &six->sin6_addr, abuf, sizeof(abuf)); snprintf(buffer, sizeof(buffer), "[%s]:%d/%s", abuf, ntohs(six->sin6_port), (portal->proto == IPPROTO_UDP)? "udp" : "tcp"); return buffer; } int isns_portal_is_wildcard(const isns_portal_info_t *portal) { return !memcmp(&portal->addr.sin6_addr, &in6addr_any, sizeof(struct in6_addr)); } int isns_portal_equal(const isns_portal_info_t *a, const isns_portal_info_t *b) { if (a->proto != b->proto) return 0; return !memcmp(&a->addr, &b->addr, sizeof(a->addr)); } uint32_t isns_portal_tcpudp_port(const isns_portal_info_t *portal) { uint32_t port; port = isns_addr_get_port((const struct sockaddr *) &portal->addr); if (portal->proto == IPPROTO_UDP) port |= ISNS_PORTAL_PORT_UDP_MASK; return port; } int isns_portal_parse(isns_portal_info_t *portal, const char *spec, const char *default_port) { struct sockaddr_storage addr; char *copy, *psp; int alen, proto = IPPROTO_TCP, sock_type = SOCK_STREAM; if (spec[0] == '/') { isns_warning("%s: no AF_LOCAL addresses for portals!\n", __FUNCTION__); return 0; } /* Look at trailing /tcp or /udp */ copy = isns_strdup(spec); if ((psp = strrchr(copy, '/')) != NULL) { if (!strcasecmp(psp, "/udp")) { sock_type = SOCK_DGRAM; proto = IPPROTO_UDP; *psp = '\0'; } else if (!strcasecmp(psp, "/tcp")) { sock_type = SOCK_STREAM; proto = IPPROTO_TCP; *psp = '\0'; } } alen = isns_get_address(&addr, copy, default_port, 0, sock_type, 0); isns_free(copy); if (alen < 0) return 0; isns_portal_init(portal, (struct sockaddr *) &addr, proto); return 1; } /* * Attribute type NIL */ static int isns_attr_type_nil_encode(buf_t *bp, const isns_value_t *value) { return buf_put32(bp, 0); } static int isns_attr_type_nil_decode(buf_t *bp, size_t len, isns_value_t *value) { return len == 0; } static void isns_attr_type_nil_print(const isns_value_t *value, char *buf, size_t size) { snprintf(buf, size, ""); } static int isns_attr_type_nil_parse(isns_value_t *value, const char *string) { if (string && *string) return 0; return 1; } isns_attr_type_t isns_attr_type_nil = { .it_id = ISNS_ATTR_TYPE_NIL, .it_name = "nil", .it_encode = isns_attr_type_nil_encode, .it_decode = isns_attr_type_nil_decode, .it_print = isns_attr_type_nil_print, .it_parse = isns_attr_type_nil_parse, }; /* * Attribute type UINT32 */ static int isns_attr_type_uint32_encode(buf_t *bp, const isns_value_t *value) { return buf_put32(bp, 4) && buf_put32(bp, value->iv_uint32); } static int isns_attr_type_uint32_decode(buf_t *bp, size_t len, isns_value_t *value) { if (len != 4) return 0; return buf_get32(bp, &value->iv_uint32); } static void isns_attr_type_uint32_print(const isns_value_t *value, char *buf, size_t size) { snprintf(buf, size, "%u", value->iv_uint32); } static int isns_attr_type_uint32_parse(isns_value_t *value, const char *string) { char *end; value->iv_uint32 = strtoul(string, &end, 0); return *end == '\0'; } static void isns_attr_type_int32_print(const isns_value_t *value, char *buf, size_t size) { snprintf(buf, size, "%d", value->iv_uint32); } static int isns_attr_type_int32_parse(isns_value_t *value, const char *string) { char *end; value->iv_int32 = strtol(string, &end, 0); return *end == '\0'; } isns_attr_type_t isns_attr_type_uint32 = { .it_id = ISNS_ATTR_TYPE_UINT32, .it_name = "uint32", .it_encode = isns_attr_type_uint32_encode, .it_decode = isns_attr_type_uint32_decode, .it_print = isns_attr_type_uint32_print, .it_parse = isns_attr_type_uint32_parse, }; isns_attr_type_t isns_attr_type_int32 = { .it_id = ISNS_ATTR_TYPE_INT32, .it_name = "int32", .it_encode = isns_attr_type_uint32_encode, .it_decode = isns_attr_type_uint32_decode, .it_print = isns_attr_type_int32_print, .it_parse = isns_attr_type_int32_parse, }; /* * 16bit min/max */ static int isns_attr_type_range16_encode(buf_t *bp, const isns_value_t *value) { uint32_t word; word = (value->iv_range.max << 16) | value->iv_range.min; return buf_put32(bp, 4) && buf_put32(bp, word); } static int isns_attr_type_range16_decode(buf_t *bp, size_t len, isns_value_t *value) { uint32_t word; if (len != 4) return 0; if (!buf_get32(bp, &word)) return 0; value->iv_range.max = word >> 16; value->iv_range.min = word & 0xFFFF; return 1; } static void isns_attr_type_range16_print(const isns_value_t *value, char *buf, size_t size) { snprintf(buf, size, "[%u, %u]", value->iv_range.min, value->iv_range.max); } isns_attr_type_t isns_attr_type_range16 = { .it_id = ISNS_ATTR_TYPE_RANGE16, .it_name = "range16", .it_encode = isns_attr_type_range16_encode, .it_decode = isns_attr_type_range16_decode, .it_print = isns_attr_type_range16_print, // .it_parse = isns_attr_type_range16_parse, }; /* * 64bit integers */ static int isns_attr_type_uint64_encode(buf_t *bp, const isns_value_t *value) { return buf_put32(bp, 8) && buf_put64(bp, value->iv_uint64); } static int isns_attr_type_uint64_decode(buf_t *bp, size_t len, isns_value_t *value) { if (len != 8) return 0; return buf_get64(bp, &value->iv_uint64); } static void isns_attr_type_uint64_print(const isns_value_t *value, char *buf, size_t size) { snprintf(buf, size, "%Lu", (unsigned long long) value->iv_uint64); } static int isns_attr_type_uint64_parse(isns_value_t *value, const char *string) { char *end; value->iv_uint64 = strtoull(string, &end, 0); return *end == '\0'; } isns_attr_type_t isns_attr_type_uint64 = { .it_id = ISNS_ATTR_TYPE_UINT64, .it_name = "uint64", .it_encode = isns_attr_type_uint64_encode, .it_decode = isns_attr_type_uint64_decode, .it_print = isns_attr_type_uint64_print, .it_parse = isns_attr_type_uint64_parse, }; /* * Attribute type STRING */ static void isns_attr_type_string_destroy(isns_value_t *value) { isns_free(value->iv_string); value->iv_string = NULL; } static int isns_attr_type_string_match(const isns_value_t *a, const isns_value_t *b) { if (a->iv_string && b->iv_string) return !strcmp(a->iv_string, b->iv_string); return a->iv_string == b->iv_string; } static int isns_attr_type_string_compare(const isns_value_t *a, const isns_value_t *b) { if (a->iv_string && b->iv_string) return strcmp(a->iv_string, b->iv_string); return a->iv_string? 1 : -1; } static int isns_attr_type_string_encode(buf_t *bp, const isns_value_t *value) { uint32_t len; len = value->iv_string? strlen(value->iv_string) + 1 : 0; if (!buf_put32(bp, ISNS_PAD(len))) return 0; if (len && !isns_encode_padded(bp, value->iv_string, len)) return 0; return 1; } static int isns_attr_type_string_decode(buf_t *bp, size_t len, isns_value_t *value) { /* Is this legal? */ if (len == 0) return 1; /* The string should be NUL terminated, but * better be safe than sorry. */ value->iv_string = isns_malloc(len + 1); if (!buf_get(bp, value->iv_string, len)) { isns_free(value->iv_string); return 0; } value->iv_string[len] = '\0'; return 1; } static void isns_attr_type_string_print(const isns_value_t *value, char *buf, size_t size) { if (!value->iv_string) snprintf(buf, size, "(empty)"); else snprintf(buf, size, "\"%s\"", value->iv_string); } static int isns_attr_type_string_parse(isns_value_t *value, const char *string) { value->iv_string = isns_strdup(string); return 1; } static void isns_attr_type_string_assign(isns_value_t *value, const isns_value_t *new_value) { isns_assert(!value->iv_string); if (new_value->iv_string) value->iv_string = isns_strdup(new_value->iv_string); } isns_attr_type_t isns_attr_type_string = { .it_id = ISNS_ATTR_TYPE_STRING, .it_name = "string", .it_assign = isns_attr_type_string_assign, .it_destroy = isns_attr_type_string_destroy, .it_match = isns_attr_type_string_match, .it_compare = isns_attr_type_string_compare, .it_encode = isns_attr_type_string_encode, .it_decode = isns_attr_type_string_decode, .it_print = isns_attr_type_string_print, .it_parse = isns_attr_type_string_parse, }; /* * Attribute type IPADDR */ static int isns_attr_type_ipaddr_encode(buf_t *bp, const isns_value_t *value) { if (!buf_put32(bp, 16) || !buf_put(bp, &value->iv_ipaddr, 16)) return 0; return 1; } static int isns_attr_type_ipaddr_decode(buf_t *bp, size_t len, isns_value_t *value) { if (len != 16) return 0; return buf_get(bp, &value->iv_ipaddr, 16); } static void isns_attr_type_ipaddr_print(const isns_value_t *value, char *buf, size_t size) { const struct in6_addr *addr = &value->iv_ipaddr; char buffer[INET6_ADDRSTRLEN + 1]; /* The standard requires IPv4 mapping, but * some oldish implementations seem to use * IPv4 compatible addresss. */ if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) { struct in_addr ipv4; ipv4.s_addr = addr->s6_addr32[3]; inet_ntop(AF_INET, &ipv4, buffer, sizeof(buffer)); } else { inet_ntop(AF_INET6, addr, buffer, sizeof(buffer)); } snprintf(buf, size, "%s", buffer); } static int isns_attr_type_ipaddr_parse(isns_value_t *value, const char *string) { struct in_addr addr4; if (inet_pton(AF_INET, string, &addr4)) { value->iv_ipaddr = in6addr_any; value->iv_ipaddr.s6_addr32[3] = addr4.s_addr; return 1; } return inet_pton(AF_INET6, string, &value->iv_ipaddr); } isns_attr_type_t isns_attr_type_ipaddr = { .it_id = ISNS_ATTR_TYPE_IPADDR, .it_name = "ipaddr", .it_encode = isns_attr_type_ipaddr_encode, .it_decode = isns_attr_type_ipaddr_decode, .it_print = isns_attr_type_ipaddr_print, .it_parse = isns_attr_type_ipaddr_parse, }; /* * Attribute type OPAQUE */ static void isns_attr_type_opaque_assign(isns_value_t *value, const isns_value_t *new_value) { size_t new_len = new_value->iv_opaque.len; isns_assert(value->iv_opaque.len == 0); if (new_len) { value->iv_opaque.ptr = isns_malloc(new_len); value->iv_opaque.len = new_len; memcpy(value->iv_opaque.ptr, new_value->iv_opaque.ptr, new_len); } } static void isns_attr_type_opaque_destroy(isns_value_t *value) { isns_free(value->iv_opaque.ptr); value->iv_opaque.ptr = NULL; value->iv_opaque.len = 0; } static int isns_attr_type_opaque_match(const isns_value_t *a, const isns_value_t *b) { if (a->iv_opaque.len != b->iv_opaque.len) return 0; return !memcmp(a->iv_opaque.ptr, b->iv_opaque.ptr, a->iv_opaque.len); } static int isns_attr_type_opaque_compare(const isns_value_t *a, const isns_value_t *b) { long delta; delta = a->iv_opaque.len - b->iv_opaque.len; if (delta) return delta; return memcmp(a->iv_opaque.ptr, b->iv_opaque.ptr, a->iv_opaque.len); } static int isns_attr_type_opaque_encode(buf_t *bp, const isns_value_t *value) { uint32_t len; len = value->iv_opaque.len; if (len & 3) return 0; if (!buf_put32(bp, len) || !buf_put(bp, value->iv_opaque.ptr, len)) return 0; return 1; } static int isns_attr_type_opaque_decode(buf_t *bp, size_t len, isns_value_t *value) { value->iv_opaque.ptr = isns_malloc(len); if (!buf_get(bp, value->iv_opaque.ptr, len)) { isns_free(value->iv_opaque.ptr); return 0; } value->iv_opaque.len = len; return 1; } static void isns_attr_type_opaque_print(const isns_value_t *value, char *buf, size_t size) { unsigned char *data = value->iv_opaque.ptr; unsigned int i, len; /* There must be room for "<...>\0" */ if (size < 6) return; size -= 6; if ((len = value->iv_opaque.len) > 20) len = 20; if (size < 3 * len) len = size / 3; *buf++ = '<'; for (i = 0; i < len; ++i) { if (i) *buf++ = ' '; sprintf(buf, "%02x", data[i]); buf += 2; } if (len < value->iv_opaque.len) { strcat(buf, "..."); buf += 4; } *buf++ = '>'; *buf++ = '\0'; } isns_attr_type_t isns_attr_type_opaque = { .it_id = ISNS_ATTR_TYPE_OPAQUE, .it_name = "opaque", .it_assign = isns_attr_type_opaque_assign, .it_destroy = isns_attr_type_opaque_destroy, .it_match = isns_attr_type_opaque_match, .it_compare = isns_attr_type_opaque_compare, .it_encode = isns_attr_type_opaque_encode, .it_decode = isns_attr_type_opaque_decode, .it_print = isns_attr_type_opaque_print, }; /* * Map attribute type IDs to attribute types */ static isns_attr_type_t * isns_attr_types_builtin[__ISNS_ATTR_TYPE_BUILTIN_MAX] = { [ISNS_ATTR_TYPE_NIL] = &isns_attr_type_nil, [ISNS_ATTR_TYPE_OPAQUE] = &isns_attr_type_opaque, [ISNS_ATTR_TYPE_STRING] = &isns_attr_type_string, [ISNS_ATTR_TYPE_INT32] = &isns_attr_type_int32, [ISNS_ATTR_TYPE_UINT32] = &isns_attr_type_uint32, [ISNS_ATTR_TYPE_UINT64] = &isns_attr_type_uint64, [ISNS_ATTR_TYPE_IPADDR] = &isns_attr_type_ipaddr, [ISNS_ATTR_TYPE_RANGE16] = &isns_attr_type_range16, }; const isns_attr_type_t * isns_attr_type_by_id(unsigned int id) { if (id < __ISNS_ATTR_TYPE_BUILTIN_MAX) return isns_attr_types_builtin[id]; /* TODO: handle dynamic registration of attrtypes * for vendor extensions. */ return NULL; } open-iscsi-2.0.873/utils/open-isns/attrs.h000066400000000000000000000171321175631155400203410ustar00rootroot00000000000000/* * iSNS object attributes * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_ATTRS_H #define ISNS_ATTRS_H #include #include "buffer.h" #include "isns.h" /* * Type identifier */ enum { ISNS_ATTR_TYPE_NIL = 0, ISNS_ATTR_TYPE_OPAQUE, ISNS_ATTR_TYPE_STRING, ISNS_ATTR_TYPE_INT32, ISNS_ATTR_TYPE_UINT32, ISNS_ATTR_TYPE_UINT64, ISNS_ATTR_TYPE_IPADDR, ISNS_ATTR_TYPE_RANGE16, __ISNS_ATTR_TYPE_BUILTIN_MAX }; /* * Union holding an attribute value */ typedef struct isns_value { const struct isns_attr_type * iv_type; /* Data is stuffed into an anonymous union */ union { uint32_t iv_nil; struct __isns_opaque { void * ptr; size_t len; } iv_opaque; char * iv_string; int32_t iv_int32; uint32_t iv_uint32; uint64_t iv_uint64; struct in6_addr iv_ipaddr; struct { uint16_t min, max; } iv_range; }; } isns_value_t; #define __ISNS_ATTRTYPE(type) isns_attr_type_##type #define __ISNS_MEMBER(type) iv_##type #define ISNS_VALUE_INIT(type, value) \ (isns_value_t) { .iv_type = &__ISNS_ATTRTYPE(type), \ { .__ISNS_MEMBER(type) = (value) } } #define isns_attr_initialize(attrp, tag, type, value) do { \ isns_attr_t *__attr = (attrp); \ uint32_t __tag = (tag); \ __attr->ia_users = 1; \ __attr->ia_tag_id = (__tag); \ __attr->ia_tag = isns_tag_type_by_id(__tag); \ __attr->ia_value = ISNS_VALUE_INIT(type, value); \ } while (0) #define ISNS_ATTR_INIT(tag, type, value) (isns_attr_t) { \ .ia_users = 1, \ .ia_tag_id = (tag), \ .ia_tag = isns_tag_type_by_id(tag), \ .ia_value = ISNS_VALUE_INIT(type, value) \ } /* * Attribute type */ typedef struct isns_attr_type { uint32_t it_id; const char * it_name; void (*it_assign)(isns_value_t *, const isns_value_t *); int (*it_set)(isns_value_t *, const void *); int (*it_get)(isns_value_t *, void *); int (*it_match)(const isns_value_t *, const isns_value_t *); int (*it_compare)(const isns_value_t *, const isns_value_t *); int (*it_encode)(buf_t *, const isns_value_t *); int (*it_decode)(buf_t *, size_t, isns_value_t *); void (*it_destroy)(isns_value_t *); void (*it_print)(const isns_value_t *, char *, size_t); int (*it_parse)(isns_value_t *, const char *); } isns_attr_type_t; /* * Tag info: for each tag, provides a printable name, * and the attribute type associated with it. */ struct isns_tag_type { uint32_t it_id; const char * it_name; unsigned int it_multiple : 1, it_readonly : 1; isns_attr_type_t *it_type; int (*it_validate)(const isns_value_t *, const isns_policy_t *); void (*it_print)(const isns_value_t *, char *, size_t); int (*it_parse)(isns_value_t *, const char *); const char * (*it_help)(void); }; /* * Attribute */ struct isns_attr { unsigned int ia_users; uint32_t ia_tag_id; const isns_tag_type_t * ia_tag; isns_value_t ia_value; }; extern isns_attr_type_t isns_attr_type_nil; extern isns_attr_type_t isns_attr_type_opaque; extern isns_attr_type_t isns_attr_type_string; extern isns_attr_type_t isns_attr_type_int32; extern isns_attr_type_t isns_attr_type_uint32; extern isns_attr_type_t isns_attr_type_uint64; extern isns_attr_type_t isns_attr_type_ipaddr; extern isns_attr_type_t isns_attr_type_range16; extern isns_attr_t * isns_attr_alloc(uint32_t, const isns_tag_type_t *, const isns_value_t *); extern void isns_attr_list_append_value(isns_attr_list_t *, uint32_t tag, const isns_tag_type_t *, const isns_value_t *); extern void isns_attr_list_update_value(isns_attr_list_t *, uint32_t tag, const isns_tag_type_t *, const isns_value_t *); extern int isns_attr_list_get_value(const isns_attr_list_t *, uint32_t tag, isns_value_t *); extern int isns_attr_list_get_uint32(const isns_attr_list_t *, uint32_t tag, uint32_t *); extern int isns_attr_list_get_string(const isns_attr_list_t *, uint32_t tag, const char **); extern int isns_attr_list_validate(const isns_attr_list_t *, const isns_policy_t *, unsigned int function); extern int isns_attr_validate(const isns_attr_t *, const isns_policy_t *); extern void isns_attr_list_prune(isns_attr_list_t *, const uint32_t *, unsigned int); extern int isns_attr_list_remove_member(isns_attr_list_t *, const isns_attr_t *, const uint32_t *); extern void isns_attr_list_update_attr(isns_attr_list_t *, const isns_attr_t *); extern int isns_attr_decode(buf_t *, isns_attr_t **); extern int isns_attr_encode(buf_t *, const isns_attr_t *); extern int isns_attr_list_decode(buf_t *, isns_attr_list_t *); extern int isns_attr_list_decode_delimited(buf_t *, isns_attr_list_t *); extern int isns_attr_list_encode(buf_t *, const isns_attr_list_t *); extern int isns_encode_delimiter(buf_t *); extern const isns_tag_type_t *isns_tag_type_by_id(unsigned int); extern const isns_attr_type_t *isns_attr_type_by_id(unsigned int); typedef struct isns_quick_attr_list isns_quick_attr_list_t; struct isns_quick_attr_list { isns_attr_list_t iqa_list; isns_attr_t * iqa_attrs[1]; isns_attr_t iqa_attr; }; #define ISNS_QUICK_ATTR_LIST_DECLARE(qlist, tag, type, value) \ isns_quick_attr_list_t qlist = { \ .iqa_list = (isns_attr_list_t) { \ .ial_data = qlist.iqa_attrs, \ .ial_count = 1 \ }, \ .iqa_attrs = { &qlist.iqa_attr }, \ .iqa_attr = ISNS_ATTR_INIT(tag, type, value), \ } /* * The following is used to chop up an incoming attr list as * given in eg. a DevAttrReg message into separate chunks, * following the ordering constraints laid out in the RFC. * * isns_attr_list_scanner_init initializes the scanner state. * * isns_attr_list_scanner_next advances to the next object in * the list, returning the keys and attrs for one object. * * The isns_attr_list_scanner struct should really be opaque, but * we put it here so you can declare a scanner variable on the * stack. */ struct isns_attr_list_scanner { isns_source_t * source; isns_policy_t * policy; isns_object_t * key_obj; isns_attr_list_t orig_attrs; unsigned int pos; isns_attr_list_t keys; isns_attr_list_t attrs; isns_object_template_t *tmpl; unsigned int num_key_attrs; unsigned int entities; uint32_t pgt_next_attr; uint32_t pgt_value; const char * pgt_iscsi_name; isns_portal_info_t pgt_portal_info; isns_object_t * pgt_base_object; unsigned int index_acceptable : 1; }; extern void isns_attr_list_scanner_init(struct isns_attr_list_scanner *, isns_object_t *key_obj, const isns_attr_list_t *attrs); extern int isns_attr_list_scanner_next(struct isns_attr_list_scanner *); extern void isns_attr_list_scanner_destroy(struct isns_attr_list_scanner *); /* * The following is used to parse attribute lists given as * a bunch of strings. */ struct isns_attr_list_parser { struct isns_tag_prefix *prefix; const char * default_port; unsigned int multi_type_permitted : 1, nil_permitted : 1; isns_attr_t * (*load_key)(const char *); isns_attr_t * (*generate_key)(void); }; extern int isns_attr_list_split(char *line, char **argv, unsigned int argc_max); extern void isns_attr_list_parser_init(struct isns_attr_list_parser *, isns_object_template_t *); extern int isns_parse_attrs(unsigned int, char **, isns_attr_list_t *, struct isns_attr_list_parser *); extern int isns_parse_query_attrs(unsigned int, char **, isns_attr_list_t *, isns_attr_list_t *, struct isns_attr_list_parser *); extern void isns_attr_list_parser_help(struct isns_attr_list_parser *); extern isns_object_template_t *isns_attr_list_parser_context(const struct isns_attr_list_parser *); extern int isns_print_attrs(isns_object_t *, char **, unsigned int); #endif /* ISNS_ATTRS_H */ open-iscsi-2.0.873/utils/open-isns/authblock.c000066400000000000000000000027611175631155400211550ustar00rootroot00000000000000/* * iSNS authentication functions * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "message.h" #include "util.h" /* We impose an artificial limit on the size of * the size of the authenticator */ #define ISNS_SPISTR_MAX 512 int isns_authblock_decode(buf_t *bp, struct isns_authblk *auth) { unsigned int avail = buf_avail(bp); if (!buf_get32(bp, &auth->iab_bsd) || !buf_get32(bp, &auth->iab_length) || !buf_get64(bp, &auth->iab_timestamp) || !buf_get32(bp, &auth->iab_spi_len)) return 0; /* Make sure the length specified by the auth block * is reasonable. */ if (auth->iab_length < ISNS_AUTHBLK_SIZE || auth->iab_length > avail) return 0; /* This chops off any data trailing the auth block. * It also makes sure that we detect if iab_length * exceeds the amount of available data. */ if (!buf_truncate(bp, auth->iab_length - ISNS_AUTHBLK_SIZE)) return 0; auth->iab_spi = buf_head(bp); if (!buf_pull(bp, auth->iab_spi_len)) return 0; auth->iab_sig = buf_head(bp); auth->iab_sig_len = buf_avail(bp); return 1; } int isns_authblock_encode(buf_t *bp, const struct isns_authblk *auth) { if (!buf_put32(bp, auth->iab_bsd) || !buf_put32(bp, auth->iab_length) || !buf_put64(bp, auth->iab_timestamp) || !buf_put32(bp, auth->iab_spi_len) || !buf_put(bp, auth->iab_spi, auth->iab_spi_len) || !buf_put(bp, auth->iab_sig, auth->iab_sig_len)) return 0; return 1; } open-iscsi-2.0.873/utils/open-isns/bitvector.c000066400000000000000000000300541175631155400211760ustar00rootroot00000000000000/* * Handle bit vector as a run length encoded array of * 32bit words. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "util.h" struct isns_bitvector { unsigned int ib_count; uint32_t * ib_words; }; void isns_bitvector_init(isns_bitvector_t *bv) { memset(bv, 0, sizeof(*bv)); } void isns_bitvector_destroy(isns_bitvector_t *bv) { isns_free(bv->ib_words); memset(bv, 0, sizeof(*bv)); } isns_bitvector_t * isns_bitvector_alloc(void) { return isns_calloc(1, sizeof(isns_bitvector_t)); } void isns_bitvector_free(isns_bitvector_t *bv) { if (bv) { isns_free(bv->ib_words); memset(bv, 0xa5, sizeof(*bv)); isns_free(bv); } } /* * Helper function to locate bit */ uint32_t * __isns_bitvector_find_word(const isns_bitvector_t *bv, unsigned int bit) { uint32_t *wp, *end; if (bv->ib_words == NULL) return NULL; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = wp[0]; rlen = wp[1]; isns_assert(!(base % 32)); if (base <= bit && bit < base + rlen * 32) return wp + 2 + ((bit - base) / 32); wp += 2 + rlen; isns_assert(wp <= end); } return NULL; } /* * Insert words in the middle of the array */ static inline void __isns_bitvector_insert_words(isns_bitvector_t *bv, unsigned int offset, unsigned int count) { bv->ib_words = isns_realloc(bv->ib_words, (bv->ib_count + count) * sizeof(uint32_t)); /* If we insert in the middle, shift out the tail * to make room for the new range. */ isns_assert(offset <= bv->ib_count); if (offset < bv->ib_count) { memmove(bv->ib_words + offset + count, bv->ib_words + offset, (bv->ib_count - offset) * sizeof(uint32_t)); } memset(bv->ib_words + offset, 0, count * sizeof(uint32_t)); bv->ib_count += count; } /* * Insert a new range */ static inline uint32_t * __isns_bitvector_insert_range(isns_bitvector_t *bv, unsigned int offset, unsigned int base) { uint32_t *pos; __isns_bitvector_insert_words(bv, offset, 3); pos = bv->ib_words + offset; *pos++ = base & ~31; *pos++ = 1; return pos; } /* * Extend an existing range * @offset marks the beginning of the existing range. */ static inline uint32_t * __isns_bitvector_extend_range(isns_bitvector_t *bv, unsigned int offset, unsigned int count) { uint32_t *pos, rlen; /* Find the end of the range */ pos = bv->ib_words + offset; rlen = pos[1]; __isns_bitvector_insert_words(bv, offset + 2 + rlen, count); pos = bv->ib_words + offset; pos[1] += count; /* Return pointer to the last word of the new range. */ return pos + 2 + rlen + count - 1; } /* * Find a suitable range for insertion */ static uint32_t * __isns_bitvector_find_insert_word(isns_bitvector_t *bv, unsigned int bit) { uint32_t *wp, *end; if (bv->ib_words == NULL) return __isns_bitvector_insert_range(bv, 0, bit); wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen, distance; base = wp[0]; rlen = wp[1]; isns_assert(!(base % 32)); if (bit < base) { return __isns_bitvector_insert_range(bv, wp - bv->ib_words, bit); } distance = (bit - base) / 32; if (distance < rlen) { /* This bit is within range */ return wp + 2 + distance; } /* Is it efficient to extend this range? * The break even point is if we have to add * 3 words to extend the range, because a new * range would be at least that much. */ if (distance + 1 <= rlen + 3) { return __isns_bitvector_extend_range(bv, wp - bv->ib_words, distance + 1 - rlen); } wp += 2 + rlen; isns_assert(wp <= end); } /* No suitable range found. Append one at the end */ return __isns_bitvector_insert_range(bv, bv->ib_count, bit); } /* * After clearing a bit, check if the bitvector can be * compacted. */ static void __isns_bitvector_compact(isns_bitvector_t *bv) { uint32_t *src, *dst, *end; unsigned int dst_base = 0, dst_len = 0; if (bv->ib_words == NULL) return; src = dst = bv->ib_words; end = src + bv->ib_count; while (src < end) { unsigned int base, rlen; base = *src++; rlen = *src++; /* Consume leading NUL words */ while (rlen && *src == 0) { base += 32; src++; rlen--; } /* Consume trailing NUL words */ while (rlen && src[rlen-1] == 0) rlen--; if (rlen != 0) { if (dst_len && dst_base + 32 * dst_len == base) { /* We can extend the previous run */ } else { /* New run. Close off the previous one, * if we had one. */ if (dst_len != 0) { dst[0] = dst_base; dst[1] = dst_len; dst += 2 + dst_len; } dst_base = base; dst_len = 0; } while (rlen--) dst[2 + dst_len++] = *src++; } isns_assert(src <= end); } if (dst_len != 0) { dst[0] = dst_base; dst[1] = dst_len; dst += 2 + dst_len; } bv->ib_count = dst - bv->ib_words; if (bv->ib_count == 0) isns_bitvector_destroy(bv); } /* * Test the value of a single bit */ int isns_bitvector_test_bit(const isns_bitvector_t *bv, unsigned int bit) { const uint32_t *pos; uint32_t mask; pos = __isns_bitvector_find_word(bv, bit); if (pos == NULL) return 0; mask = 1 << (bit % 32); return !!(*pos & mask); } int isns_bitvector_clear_bit(isns_bitvector_t *bv, unsigned int bit) { uint32_t *pos, oldval, mask; pos = __isns_bitvector_find_word(bv, bit); if (pos == NULL) return 0; mask = 1 << (bit % 32); oldval = *pos; *pos &= ~mask; __isns_bitvector_compact(bv); return !!(oldval & mask); } int isns_bitvector_set_bit(isns_bitvector_t *bv, unsigned int bit) { uint32_t *pos, oldval = 0, mask; mask = 1 << (bit % 32); pos = __isns_bitvector_find_insert_word(bv, bit); if (pos != NULL) { oldval = *pos; *pos |= mask; return !!(oldval & mask); } return 0; } int isns_bitvector_is_empty(const isns_bitvector_t *bv) { uint32_t *wp, *end; if (bv == NULL || bv->ib_count == 0) return 1; /* In theory, we should never have a non-compacted * empty bitvector, as the only way to get one * is through clear_bit. * Better safe than sorry... */ wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen; base = *wp++; rlen = *wp++; while (rlen--) { if (*wp++) return 0; } isns_assert(wp <= end); } return 1; } int isns_bitvector_intersect(const isns_bitvector_t *a, const isns_bitvector_t *b, isns_bitvector_t *result) { const uint32_t *runa, *runb, *enda, *endb; const uint32_t *wpa = NULL, *wpb = NULL; uint32_t bita = 0, lena = 0, bitb = 0, lenb = 0; int found = -1; if (a == NULL || b == NULL) return -1; /* Returning the intersect is not implemented yet. */ isns_assert(result == NULL); runa = a->ib_words; enda = runa + a->ib_count; runb = b->ib_words; endb = runb + b->ib_count; while (1) { unsigned int skip; if (lena == 0) { next_a: if (runa >= enda) break; bita = *runa++; lena = *runa++; wpa = runa; runa += lena; lena *= 32; } if (lenb == 0) { next_b: if (runb >= endb) break; bitb = *runb++; lenb = *runb++; wpb = runb; runb += lenb; lenb *= 32; } if (bita < bitb) { skip = bitb - bita; /* range A ends before range B starts. * Proceed to next run in vector A. */ if (skip >= lena) goto next_a; bita += skip; lena -= skip; wpa += skip / 32; } else if (bitb < bita) { skip = bita - bitb; /* range B ends before range A starts. * Proceed to next run in vector B. */ if (skip >= lenb) goto next_b; bitb += skip; lenb -= skip; wpb += skip / 32; } isns_assert(bita == bitb); while (lena && lenb) { uint32_t intersect; intersect = *wpa & *wpb; if (!intersect) goto next_word; /* Find the bit */ if (found < 0) { uint32_t mask = intersect; found = bita; while (!(mask & 1)) { found++; mask >>= 1; } } if (result == NULL) return found; /* Append to result vector */ /* FIXME: TBD */ next_word: bita += 32; lena -= 32; wpa++; bitb += 32; lenb -= 32; wpb++; } } return found; } /* * Iterate over the bit vector */ void isns_bitvector_foreach(const isns_bitvector_t *bv, int (*cb)(uint32_t, void *), void *user_data) { uint32_t *wp, *end; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen, bits; base = wp[0]; rlen = wp[1]; bits = rlen * 32; wp += 2; while (rlen--) { uint32_t mask, word; word = *wp++; for (mask = 1; mask; mask <<= 1, ++base) { if (word & mask) cb(base, user_data); } } isns_assert(wp <= end); } } void isns_bitvector_dump(const isns_bitvector_t *bv, isns_print_fn_t *fn) { uint32_t *wp, *end; fn("Bit Vector %p (%u words):", bv, bv->ib_count); wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen, bits; base = wp[0]; rlen = wp[1]; bits = rlen * 32; wp += 2; fn(" <%u:", base); while (rlen--) fn(" 0x%x", *wp++); fn(">"); isns_assert(wp <= end); } if (bv->ib_count == 0) fn(""); fn("\n"); } static inline void __isns_bitvector_print_next(uint32_t first, uint32_t last, isns_print_fn_t *fn) { switch (last - first) { case 0: return; case 1: fn(", %u", last); break; default: fn("-%u", last); break; } } void isns_bitvector_print(const isns_bitvector_t *bv, isns_print_fn_t *fn) { uint32_t *wp, *end, first = 0, next = 0; const char *sepa = ""; wp = bv->ib_words; end = wp + bv->ib_count; while (wp < end) { unsigned int base, rlen, bits; base = wp[0]; rlen = wp[1]; bits = rlen * 32; wp += 2; while (rlen--) { uint32_t mask, word; word = *wp++; for (mask = 1; mask; mask <<= 1, ++base) { if (word & mask) { if (next++) continue; fn("%s%u", sepa, base); sepa = ", "; first = base; next = base + 1; } else { if (next) __isns_bitvector_print_next(first, next - 1, fn); first = next = 0; } } } isns_assert(wp <= end); } if (next) __isns_bitvector_print_next(first, next - 1, fn); if (*sepa == '\0') fn(""); fn("\n"); } #ifdef TEST int main(void) { isns_bitvector_t a, b; int i; isns_bitvector_init(&a); isns_bitvector_set_bit(&a, 0); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 1); isns_bitvector_set_bit(&a, 16); isns_bitvector_set_bit(&a, 32); isns_bitvector_set_bit(&a, 64); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 8192); isns_bitvector_set_bit(&a, 8196); isns_bitvector_set_bit(&a, 8194); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_set_bit(&a, 2052); isns_bitvector_set_bit(&a, 2049); isns_bitvector_set_bit(&a, 2051); isns_bitvector_set_bit(&a, 2050); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); for (i = 127; i >= 0; --i) isns_bitvector_set_bit(&a, i); isns_bitvector_dump(&a, isns_print_stdout); printf("[Compacting]\n"); __isns_bitvector_compact(&a); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); for (i = 0; i < 128; ++i) isns_bitvector_set_bit(&a, i); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); isns_bitvector_init(&a); isns_bitvector_init(&b); isns_bitvector_set_bit(&a, 0); isns_bitvector_set_bit(&a, 77); isns_bitvector_set_bit(&a, 249); isns_bitvector_set_bit(&a, 102); isns_bitvector_set_bit(&b, 1); isns_bitvector_set_bit(&b, 76); isns_bitvector_set_bit(&b, 250); isns_bitvector_set_bit(&b, 102); i = isns_bitvector_intersect(&a, &b, NULL); if (i != 102) fprintf(stderr, "*** BAD: Intersect should return 102 (got %d)! ***\n", i); else printf("Intersect okay: %d\n", i); isns_bitvector_destroy(&a); isns_bitvector_destroy(&b); isns_bitvector_init(&a); isns_bitvector_set_bit(&a, 0); isns_bitvector_set_bit(&a, 1); isns_bitvector_clear_bit(&a, 1); isns_bitvector_clear_bit(&a, 0); isns_bitvector_dump(&a, isns_print_stdout); isns_bitvector_print(&a, isns_print_stdout); isns_bitvector_destroy(&a); return 0; } #endif open-iscsi-2.0.873/utils/open-isns/buffer.c000066400000000000000000000135001175631155400204430ustar00rootroot00000000000000/* * Buffer handling functions * * Copyright (C) 2003-2007, Olaf Kirch */ #include #include #include #include #include #include #include /* ntohl&htonl */ #include "buffer.h" #include "util.h" /* htonll */ static int buf_drain(buf_t *bp); buf_t * buf_alloc(size_t size) { buf_t *bp; bp = isns_calloc(1, sizeof(*bp)); buf_init_empty(bp, size); return bp; } buf_t * buf_open(const char *filename, int flags) { static const unsigned int buflen = 4096; buf_t *bp; int oerr; if (!(bp = isns_calloc(1, sizeof(*bp) + buflen))) return NULL; buf_init(bp, (bp + 1), buflen); switch (flags & O_ACCMODE) { case O_RDONLY: bp->write_mode = 0; break; case O_WRONLY: bp->write_mode = 1; break; default: errno = EINVAL; goto failed; } if (!filename || !strcmp(filename, "-")) { bp->fd = dup(bp->write_mode? 1 : 0); } else { bp->fd = open(filename, flags, 0666); } if (bp->fd < 0) goto failed; return bp; failed: oerr = errno; isns_free(bp); errno = oerr; return NULL; } buf_t * buf_dup(const buf_t *src) { buf_t *bp; bp = buf_alloc(src->max_size); buf_put(bp, src->base + src->head, src->tail - src->head); bp->addr = src->addr; bp->addrlen = src->addrlen; return bp; } void buf_close(buf_t *bp) { if (bp->write_mode) buf_drain(bp); if (bp->fd >= 0) close(bp->fd); bp->fd = -1; isns_free(bp); } void buf_free(buf_t *bp) { if (!bp) return; if (bp->allocated) isns_free(bp->base); isns_free(bp); } void buf_list_free(buf_t *bp) { buf_t *next; while (bp) { next = bp->next; buf_free(bp); bp = next; } } void buf_init(buf_t *bp, void *mem, size_t len) { memset(bp, 0, sizeof(*bp)); bp->base = (unsigned char *) mem; bp->size = len; bp->max_size = len; bp->fd = -1; } void buf_init_empty(buf_t *bp, size_t len) { memset(bp, 0, sizeof(*bp)); bp->max_size = len; bp->fd = -1; } void buf_set(buf_t *bp, void *mem, size_t len) { buf_init(bp, mem, len); bp->tail = len; } void buf_clear(buf_t *bp) { bp->head = bp->tail = 0; } int buf_fill(buf_t *bp) { int n; if (bp->head || bp->tail) buf_compact(bp); if (bp->write_mode || bp->fd < 0) return 0; n = read(bp->fd, bp->base + bp->tail, buf_tailroom(bp)); if (n < 0) { warn("read error"); return 0; } bp->tail += n; return n; } int buf_drain(buf_t *bp) { int n; if (!bp->write_mode || bp->fd < 0) return 0; n = write(bp->fd, bp->base + bp->head, buf_avail(bp)); if (n < 0) { warn("write error"); return 0; } bp->head += n; return n; } int __buf_resize(buf_t *bp, size_t new_size) { void *new_base; if (new_size > bp->max_size) return 0; isns_assert(bp->allocated || bp->base == NULL); new_size = (new_size + 127) & ~127; if (new_size > bp->max_size) new_size = bp->max_size; new_base = isns_realloc(bp->base, new_size); if (new_base == NULL) return 0; bp->base = new_base; bp->size = new_size; bp->allocated = 1; return new_size; } buf_t * buf_split(buf_t **to_split, size_t size) { buf_t *old = *to_split, *new; size_t avail; avail = buf_avail(old); if (size > avail) return NULL; if (size == avail) { *to_split = NULL; return old; } new = buf_alloc(size); buf_put(new, buf_head(old), size); buf_pull(old, size); return new; } int buf_seek(buf_t *bp, off_t offset) { if (bp->write_mode && !buf_drain(bp)) return 0; if (lseek(bp->fd, offset, SEEK_SET) < 0) { warn("cannot seek to offset %ld", (long) offset); return 0; } return 1; } int buf_get(buf_t *bp, void *mem, size_t len) { caddr_t dst = (caddr_t) mem; unsigned int total = len, copy; while (len) { if ((copy = buf_avail(bp)) > len) copy = len; if (copy == 0) { if (!buf_fill(bp)) return 0; continue; } if (dst) { memcpy(dst, bp->base + bp->head, copy); dst += copy; } bp->head += copy; len -= copy; } return total; } int buf_get32(buf_t *bp, uint32_t *vp) { if (!buf_get(bp, vp, 4)) return 0; *vp = ntohl(*vp); return 1; } int buf_get64(buf_t *bp, uint64_t *vp) { if (!buf_get(bp, vp, 8)) return 0; *vp = ntohll(*vp); return 1; } int buf_gets(buf_t *bp, char *stringbuf, size_t size) { uint32_t len, copy; if (size == 0) return 0; if (!buf_get32(bp, &len)) return 0; if ((copy = len) >= size) copy = size - 1; if (!buf_get(bp, stringbuf, copy)) return 0; stringbuf[copy] = '\0'; /* Pull remaining bytes */ if (copy != len && !buf_pull(bp, len - copy)) return 0; return copy + 1; } int buf_put(buf_t *bp, const void *mem, size_t len) { caddr_t src = (caddr_t) mem; unsigned int total = len, copy; while (len) { if ((copy = bp->size - bp->tail) > len) copy = len; if (copy == 0) { if (buf_drain(bp)) { buf_compact(bp); continue; } if (__buf_resize(bp, bp->tail + len)) { buf_compact(bp); continue; } return 0; } if (src) { memcpy(bp->base + bp->tail, src, copy); src += copy; } bp->tail += copy; len -= copy; } return total; } int buf_putc(buf_t *bp, int byte) { unsigned char c = byte; return buf_put(bp, &c, 1); } int buf_put32(buf_t *bp, uint32_t val) { val = htonl(val); if (!buf_put(bp, &val, 4)) return 0; return 1; } int buf_put64(buf_t *bp, uint64_t val) { val = htonll(val); return buf_put(bp, &val, 8); } int buf_puts(buf_t *bp, const char *sp) { uint32_t len = 0; if (sp) len = strlen(sp); return buf_put32(bp, len) && buf_put(bp, sp, len); } void buf_compact(buf_t *bp) { unsigned int count; if (bp->head == 0) return; count = bp->tail - bp->head; memmove(bp->base, bp->base + bp->head, count); bp->tail -= bp->head; bp->head = 0; } void buf_list_append(buf_t **list, buf_t *bp) { bp->next = NULL; while (*list) list = &(*list)->next; *list = bp; } int buf_truncate(buf_t *bp, size_t len) { if (bp->head + len > bp->tail) return 0; bp->tail = bp->head + len; return 1; } open-iscsi-2.0.873/utils/open-isns/buffer.h000066400000000000000000000054711175631155400204600ustar00rootroot00000000000000/* * Buffer handling functions * * Copyright (C) 2003-2006, Olaf Kirch */ #ifndef BUFFER_H #define BUFFER_H #include #include #include typedef struct isns_buf { struct isns_buf * next; unsigned char * base; unsigned int head, tail, size, max_size; unsigned int write_mode : 1, allocated : 1; int fd; /* Anonymous union for misc stuff */ union { struct { struct sockaddr_storage addr; socklen_t addrlen; }; }; } buf_t; extern buf_t * buf_open(const char *, int); extern buf_t * buf_alloc(size_t); extern buf_t * buf_dup(const buf_t *); extern void buf_init(buf_t *, void *, size_t); extern void buf_init_empty(buf_t *, size_t); extern void buf_set(buf_t *, void *, size_t); extern void buf_clear(buf_t *); extern void buf_close(buf_t *); extern void buf_destroy(buf_t *); extern void buf_free(buf_t *); extern void buf_list_free(buf_t *); extern int buf_get(buf_t *, void *, size_t); extern int buf_get32(buf_t *, uint32_t *); extern int buf_get64(buf_t *, uint64_t *); extern int buf_gets(buf_t *, char *, size_t); extern int buf_put(buf_t *, const void *, size_t); extern int buf_put32(buf_t *, uint32_t); extern int buf_put64(buf_t *, uint64_t); extern int buf_puts(buf_t *, const char *); extern int buf_putc(buf_t *, int); extern int buf_read(buf_t *, int); extern int buf_seek(buf_t *bp, off_t offset); extern int buf_truncate(buf_t *, size_t); extern void buf_compact(buf_t *); extern buf_t * buf_split(buf_t **to_split, size_t len); extern int __buf_resize(buf_t *, size_t); extern void buf_list_append(buf_t **, buf_t *); static inline size_t buf_avail(const buf_t *bp) { return bp->tail - bp->head; } static inline size_t buf_tailroom(const buf_t *bp) { return bp->max_size - bp->tail; } static inline size_t buf_size(const buf_t *bp) { return bp->size; } static inline void * buf_head(const buf_t *bp) { return bp->base + bp->head; } static inline void * buf_tail(const buf_t *bp) { return bp->base + bp->tail; } static inline int buf_reserve(buf_t *bp, size_t len) { if (bp->head != bp->tail) return 0; if (bp->max_size - bp->head < len) return 0; bp->head += len; bp->tail += len; return 1; } static inline int buf_pull(buf_t *bp, size_t len) { if (len > buf_avail(bp)) return 0; bp->head += len; return 1; } static inline void * buf_push(buf_t *bp, size_t len) { if (bp->max_size - bp->tail < len) return NULL; if (bp->tail + len > bp->size && !__buf_resize(bp, bp->tail + len)) return NULL; bp->tail += len; return bp->base + bp->tail - len; } static inline void * buf_push_head(buf_t *bp, size_t len) { if (bp->head < len) return NULL; if (bp->tail > bp->size && !__buf_resize(bp, bp->tail)) return NULL; bp->head -= len; return bp->base + bp->head; } #endif /* BUFFER_H */ open-iscsi-2.0.873/utils/open-isns/callback.c000066400000000000000000000062451175631155400207360ustar00rootroot00000000000000/* * iSNS object callbacks for SCN and other stuff * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "objects.h" #include "vendor.h" #include "attrs.h" #include "util.h" typedef struct isns_object_notifier isns_object_notifier_t; struct isns_object_notifier { isns_list_t list; isns_db_callback_t * func; void * data; }; typedef struct isns_cb_event isns_cb_event_t; struct isns_cb_event { isns_list_t list; isns_db_event_t info; }; static ISNS_LIST_DECLARE(notifiers); static ISNS_LIST_DECLARE(events); static inline void __isns_db_event(isns_object_t *dst, isns_object_t *obj, unsigned int bits, isns_object_t *trigger) { isns_cb_event_t *ev; ev = isns_calloc(1, sizeof(*ev)); ev->info.ie_recipient = isns_object_get(dst); ev->info.ie_object = isns_object_get(obj); ev->info.ie_bits = bits; ev->info.ie_trigger = isns_object_get(trigger); isns_list_append(&events, &ev->list); } void isns_object_event(isns_object_t *obj, unsigned int bits, isns_object_t *trigger) { __isns_db_event(NULL, obj, bits, trigger); } void isns_unicast_event(isns_object_t *dst, isns_object_t *obj, unsigned int bits, isns_object_t *trigger) { __isns_db_event(dst, obj, bits, trigger); } /* * Given an object pair and an event bitmask, * invoke all callbacks */ static inline void isns_call_callbacks(isns_db_event_t *ev) { isns_object_t *obj = ev->ie_object; isns_list_t *pos, *next; ev->ie_bits |= obj->ie_scn_bits; if (ev->ie_bits == 0) return; isns_list_foreach(¬ifiers, pos, next) { isns_object_notifier_t *not; not = isns_list_item(isns_object_notifier_t, list, pos); not->func(ev, not->data); } obj->ie_scn_bits = 0; } void isns_flush_events(void) { while (!isns_list_empty(&events)) { isns_cb_event_t *ev = isns_list_item(isns_cb_event_t, list, events.next); isns_call_callbacks(&ev->info); isns_object_release(ev->info.ie_recipient); isns_object_release(ev->info.ie_object); isns_object_release(ev->info.ie_trigger); isns_list_del(&ev->list); isns_free(ev); } } void isns_register_callback(isns_db_callback_t *func, void *user_data) { isns_object_notifier_t *not; not = isns_calloc(1, sizeof(*not)); not->func = func; not->data = user_data; isns_list_append(¬ifiers, ¬->list); } const char * isns_event_string(unsigned int bits) { static const char *names[16] = { [ISNS_SCN_DD_MEMBER_ADDED] = "member added", [ISNS_SCN_DD_MEMBER_REMOVED] = "member removed", [ISNS_SCN_OBJECT_UPDATED] = "updated", [ISNS_SCN_OBJECT_ADDED] = "added", [ISNS_SCN_OBJECT_REMOVED] = "removed", [ISNS_SCN_MANAGEMENT_REGISTRATION]= "mgmt registration", [ISNS_SCN_TARGET_AND_SELF_ONLY] = "target+self", [ISNS_SCN_INITIATOR_AND_SELF_ONLY]= "initiator+self", }; static char buffer[128]; unsigned int pos = 0, i; for (i = 0; i < 16; ++i, bits >>= 1) { if (!(bits & 1)) continue; if (names[i]) { snprintf(buffer + pos, sizeof(buffer) - pos, "%s%s", pos? ", " : "", names[i]); } else { snprintf(buffer + pos, sizeof(buffer) - pos, "%sevent %u", pos? ", " : "", i); } pos = strlen(buffer); } if (pos == 0) return ""; return buffer; } open-iscsi-2.0.873/utils/open-isns/client.c000066400000000000000000000112221175631155400204470ustar00rootroot00000000000000/* * Client functions * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include #include "security.h" #include "util.h" #include "internal.h" #include "config.h" static isns_client_t * __isns_create_default_client(isns_socket_t *sock, isns_security_t *ctx, const char *source_name) { isns_client_t *clnt; clnt = isns_calloc(1, sizeof(*clnt)); if (!source_name) source_name = isns_config.ic_source_name; clnt->ic_source = isns_source_create_iscsi(source_name); clnt->ic_socket = sock; isns_socket_set_security_ctx(clnt->ic_socket, ctx); return clnt; } isns_client_t * isns_create_client(isns_security_t *ctx, const char *source_name) { isns_socket_t *sock; const char *server_name; server_name = isns_config.ic_server_name; if (!strcasecmp(server_name, "SLP:") && !(server_name = isns_slp_find())) { isns_error("Unable to locate iSNS server through SLP\n"); return NULL; } sock = isns_create_bound_client_socket( isns_config.ic_bind_address, server_name, "isns", 0, SOCK_STREAM); if (sock == NULL) { isns_error("Unable to create socket for host \"%s\"\n", isns_config.ic_server_name); return NULL; } return __isns_create_default_client(sock, ctx? : isns_default_security_context(0), source_name); } isns_client_t * isns_create_default_client(isns_security_t *ctx) { return isns_create_client(ctx, isns_config.ic_source_name); } isns_client_t * isns_create_local_client(isns_security_t *ctx, const char *source_name) { isns_socket_t *sock; if (isns_config.ic_control_socket == NULL) isns_fatal("Cannot use local mode: no local control socket\n"); sock = isns_create_client_socket(isns_config.ic_control_socket, NULL, 0, SOCK_STREAM); if (sock == NULL) { isns_error("Unable to create control socket (%s)\n", isns_config.ic_control_socket); return NULL; } return __isns_create_default_client(sock, ctx, source_name); } int isns_client_call(isns_client_t *clnt, isns_simple_t **inout) { return isns_simple_call(clnt->ic_socket, inout); } void isns_client_destroy(isns_client_t *clnt) { if (clnt->ic_socket) isns_socket_free(clnt->ic_socket); if (clnt->ic_source) isns_source_release(clnt->ic_source); isns_free(clnt); } /* * Get the local address */ int isns_client_get_local_address(const isns_client_t *clnt, isns_portal_info_t *portal_info) { return isns_socket_get_portal_info(clnt->ic_socket, portal_info); } /* * Create a security context */ static isns_security_t * __create_security_context(const char *name, const char *auth_key, const char *server_key) { #ifdef WITH_SECURITY isns_security_t *ctx; isns_principal_t *princ; #endif /* WITH_SECURITY */ if (!isns_config.ic_security) return NULL; #ifndef WITH_SECURITY isns_error("Cannot create security context: security disabled at build time\n"); return NULL; #else /* WITH_SECURITY */ ctx = isns_create_dsa_context(); if (ctx == NULL) isns_fatal("Unable to create security context\n"); /* Load my own key */ princ = isns_security_load_privkey(ctx, auth_key); if (!princ) isns_fatal("Unable to load private key from %s\n", auth_key); isns_principal_set_name(princ, name); isns_security_set_identity(ctx, princ); if (server_key) { /* We're a client, and we want to load the * server's public key in order to authenticate * the server's responses. */ princ = isns_security_load_pubkey(ctx, server_key); if (!princ) isns_fatal("Unable to load public key from %s\n", server_key); /* Do *not* set a name for this principal - * this will be the default principal used when * verifying the server's reply, which is a good thing * because we don't know what SPI the server will * be using. */ isns_add_principal(ctx, princ); /* But set a policy for the server which allows it to send ESI and SCN messages */ isns_principal_set_policy(princ, isns_policy_server()); } return ctx; #endif /* WITH_SECURITY */ } /* * Create the default security context */ isns_security_t * isns_default_security_context(int server_only) { static isns_security_t *ctx; if (ctx == NULL) ctx = __create_security_context(isns_config.ic_auth_name, isns_config.ic_auth_key_file, server_only? NULL : isns_config.ic_server_key_file); return ctx; } /* * Create the control security context */ isns_security_t * isns_control_security_context(int server_only) { static isns_security_t *ctx; if (ctx == NULL) ctx = __create_security_context(isns_config.ic_control_name, isns_config.ic_control_key_file, server_only? NULL : isns_config.ic_server_key_file); return ctx; } open-iscsi-2.0.873/utils/open-isns/compat/000077500000000000000000000000001175631155400203125ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/compat/my_getopt.c000066400000000000000000000212741175631155400224730ustar00rootroot00000000000000/* * my_getopt.c - my re-implementation of getopt. * Copyright 1997, 2000, 2001, 2002, Benjamin Sittler * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include #include #include #include #include "my_getopt.h" int my_optind=1, my_opterr=1, my_optopt=0; char *my_optarg=0; /* this is the plain old UNIX getopt, with GNU-style extensions. */ /* if you're porting some piece of UNIX software, this is all you need. */ /* this supports GNU-style permution and optional arguments */ int my_getopt(int argc, char * argv[], const char *opts) { static int charind=0; const char *s; char mode, colon_mode; int off = 0, opt = -1; if(getenv("POSIXLY_CORRECT")) colon_mode = mode = '+'; else { if((colon_mode = *opts) == ':') off ++; if(((mode = opts[off]) == '+') || (mode == '-')) { off++; if((colon_mode != ':') && ((colon_mode = opts[off]) == ':')) off ++; } } my_optarg = 0; if(charind) { my_optopt = argv[my_optind][charind]; for(s=opts+off; *s; s++) if(my_optopt == *s) { charind++; if((*(++s) == ':') || ((my_optopt == 'W') && (*s == ';'))) { if(argv[my_optind][charind]) { my_optarg = &(argv[my_optind++][charind]); charind = 0; } else if(*(++s) != ':') { charind = 0; if(++my_optind >= argc) { if(my_opterr) fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], my_optopt); opt = (colon_mode == ':') ? ':' : '?'; goto my_getopt_ok; } my_optarg = argv[my_optind++]; } } opt = my_optopt; goto my_getopt_ok; } if(my_opterr) fprintf(stderr, "%s: illegal option -- %c\n", argv[0], my_optopt); opt = '?'; if(argv[my_optind][++charind] == '\0') { my_optind++; charind = 0; } my_getopt_ok: if(charind && ! argv[my_optind][charind]) { my_optind++; charind = 0; } } else if((my_optind >= argc) || ((argv[my_optind][0] == '-') && (argv[my_optind][1] == '-') && (argv[my_optind][2] == '\0'))) { my_optind++; opt = -1; } else if((argv[my_optind][0] != '-') || (argv[my_optind][1] == '\0')) { char *tmp; int i, j, k; if(mode == '+') opt = -1; else if(mode == '-') { my_optarg = argv[my_optind++]; charind = 0; opt = 1; } else { for(i=j=my_optind; i j) { tmp=argv[--i]; for(k=i; k+1 argc) my_optind = argc; return opt; } /* this is the extended getopt_long{,_only}, with some GNU-like * extensions. Implements _getopt_internal in case any programs * expecting GNU libc getopt call it. */ int _my_getopt_internal(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind, int long_only) { char mode, colon_mode = *shortopts; int shortoff = 0, opt = -1; if(getenv("POSIXLY_CORRECT")) colon_mode = mode = '+'; else { if((colon_mode = *shortopts) == ':') shortoff ++; if(((mode = shortopts[shortoff]) == '+') || (mode == '-')) { shortoff++; if((colon_mode != ':') && ((colon_mode = shortopts[shortoff]) == ':')) shortoff ++; } } my_optarg = 0; if((my_optind >= argc) || ((argv[my_optind][0] == '-') && (argv[my_optind][1] == '-') && (argv[my_optind][2] == '\0'))) { my_optind++; opt = -1; } else if((argv[my_optind][0] != '-') || (argv[my_optind][1] == '\0')) { char *tmp; int i, j, k; opt = -1; if(mode == '+') return -1; else if(mode == '-') { my_optarg = argv[my_optind++]; return 1; } for(i=j=my_optind; i j) { tmp=argv[--i]; for(k=i; k+1= argc) { opt = (colon_mode == ':') ? ':' : '?'; if(my_opterr) fprintf(stderr, "%s: option `--%s' requires an argument\n", argv[0], longopts[found].name); } else my_optarg = argv[my_optind]; } if(!opt) { if (longind) *longind = found; if(!longopts[found].flag) opt = longopts[found].val; else *(longopts[found].flag) = longopts[found].val; } my_optind++; } else if(!hits) { if(offset == 1) opt = my_getopt(argc, argv, shortopts); else { opt = '?'; if(my_opterr) fprintf(stderr, "%s: unrecognized option `%s'\n", argv[0], argv[my_optind++]); } } else { opt = '?'; if(my_opterr) fprintf(stderr, "%s: option `%s' is ambiguous\n", argv[0], argv[my_optind++]); } } if (my_optind > argc) my_optind = argc; return opt; } int my_getopt_long(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind) { return _my_getopt_internal(argc, argv, shortopts, longopts, longind, 0); } int my_getopt_long_only(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind) { return _my_getopt_internal(argc, argv, shortopts, longopts, longind, 1); } open-iscsi-2.0.873/utils/open-isns/compat/my_getopt.h000066400000000000000000000044751175631155400225040ustar00rootroot00000000000000/* * my_getopt.h - interface to my re-implementation of getopt. * Copyright 1997, 2000, 2001, 2002, Benjamin Sittler * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef MY_GETOPT_H_INCLUDED #define MY_GETOPT_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* UNIX-style short-argument parser */ extern int my_getopt(int argc, char * argv[], const char *opts); extern int my_optind, my_opterr, my_optopt; extern char *my_optarg; struct option { const char *name; int has_arg; int *flag; int val; }; /* human-readable values for has_arg */ #undef no_argument #define no_argument 0 #undef required_argument #define required_argument 1 #undef optional_argument #define optional_argument 2 /* GNU-style long-argument parsers */ extern int my_getopt_long(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind); extern int my_getopt_long_only(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind); extern int _my_getopt_internal(int argc, char * argv[], const char *shortopts, const struct option *longopts, int *longind, int long_only); #ifdef __cplusplus } #endif #endif /* MY_GETOPT_H_INCLUDED */ open-iscsi-2.0.873/utils/open-isns/config.c000066400000000000000000000164501175631155400204460ustar00rootroot00000000000000/* * Config file reader * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include "isns.h" #include "util.h" #include "paths.h" /* * iSNS configuration */ struct isns_config isns_config = { /* Security parameters */ .ic_security = -1, .ic_auth_key_file = ISNS_ETCDIR "/auth_key", .ic_server_key_file = ISNS_ETCDIR "/server_key.pub", .ic_client_keystore = "DB:", .ic_control_socket = ISNS_RUNDIR "/isnsctl", .ic_pidfile = ISNS_RUNDIR "/isnsd.pid", .ic_local_registry_file = ISNS_DEFAULT_LOCAL_REGISTRY, .ic_control_name = "isns.control", .ic_control_key_file = ISNS_ETCDIR "/control.key", .ic_registration_period = 3600, /* 1 hour */ .ic_scn_timeout = 60, .ic_scn_retries = 3, .ic_esi_max_interval = 600, /* 10 minutes */ .ic_esi_min_interval = 60, /* 1 minute */ .ic_esi_retries = 3, .ic_auth = { .replay_window = 300, /* 5 min clock skew */ .timestamp_jitter = 1, /* 1 sec timestamp jitter */ .allow_unknown_peers = 1, }, .ic_network = { .max_sockets = 1024, .connect_timeout = 5, .reconnect_timeout = 10, .call_timeout = 60, .udp_retrans_timeout = 10, .tcp_retrans_timeout = 60, .idle_timeout = 300, }, .ic_dsa = { .param_file = ISNS_ETCDIR "/dsa.params", }, }; /* * Default string values need to be dup'ed, * so that later assignment does't try to free * these strings. */ static inline void __isns_config_defaults(void) { static int defaults_init = 1; if (!defaults_init) return; #define DUP(member) \ if (isns_config.member) \ isns_config.member = isns_strdup(isns_config.member) DUP(ic_source_name); DUP(ic_database); DUP(ic_server_name); DUP(ic_bind_address); DUP(ic_auth_key_file); DUP(ic_server_key_file); DUP(ic_client_keystore); DUP(ic_control_socket); DUP(ic_pidfile); DUP(ic_control_name); DUP(ic_control_key_file); DUP(ic_local_registry_file); DUP(ic_dsa.param_file); #undef DUP defaults_init = 0; } /* * Read the iSNS configuration file */ int isns_read_config(const char *filename) { FILE *fp; char *name, *pos; __isns_config_defaults(); if ((fp = fopen(filename, "r")) == NULL) { perror(filename); return -1; } while ((pos = parser_get_next_line(fp)) != NULL) { pos[strcspn(pos, "#")] = '\0'; if (!(name = parser_get_next_word(&pos))) continue; isns_config_set(name, pos); } fclose(fp); /* Massage the config file */ if (isns_config.ic_security < 0) { /* By default, we will enable authentication * whenever we find our private key, and * the server's public key. */ if (access(isns_config.ic_auth_key_file, R_OK) == 0 && access(isns_config.ic_server_key_file, R_OK) == 0) isns_config.ic_security = 1; else isns_config.ic_security = 0; } isns_init_names(); return 0; } int isns_config_set(const char *name, char *pos) { char *value; value = parser_get_rest_of_line(&pos); if (value) while (isspace(*value) || *value == '=') ++value; if (!strcasecmp(name, "HostName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_host_name, value); } else if (!strcasecmp(name, "SourceName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_source_name, value); } else if (!strcasecmp(name, "AuthName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_auth_name, value); } else if (!strcasecmp(name, "Database")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_database, value); } else if (!strcasecmp(name, "ServerAddress")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_server_name, value); } else if (!strcasecmp(name, "BindAddress")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_bind_address, value); } else if (!strcasecmp(name, "ControlSocket")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_socket, value); } else if (!strcasecmp(name, "PIDFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_pidfile, value); } else if (!strcasecmp(name, "LocalRegistry")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_local_registry_file, value); } else if (!strcasecmp(name, "RegistrationPeriod")) { if (!value) goto no_value; isns_config.ic_registration_period = parse_timeout(value); } else if (!strcasecmp(name, "SCNTimeout")) { if (!value) goto no_value; isns_config.ic_scn_timeout = parse_timeout(value); } else if (!strcasecmp(name, "SCNRetries")) { if (!value) goto no_value; isns_config.ic_scn_retries = parse_int(value); } else if (!strcasecmp(name, "SCNCallout")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_scn_callout, value); } else if (!strcasecmp(name, "ESIMinInterval")) { if (!value) goto no_value; isns_config.ic_esi_min_interval = parse_timeout(value); } else if (!strcasecmp(name, "ESIMaxInterval")) { if (!value) goto no_value; isns_config.ic_esi_max_interval = parse_timeout(value); } else if (!strcasecmp(name, "ESIRetries")) { if (!value) goto no_value; isns_config.ic_esi_retries = parse_int(value); } else if (!strcasecmp(name, "DefaultDiscoveryDomain")) { if (!value) goto no_value; isns_config.ic_use_default_domain = parse_int(value); } else if (!strcasecmp(name, "SLPRegister")) { if (!value) goto no_value; isns_config.ic_slp_register = parse_int(value); } else if (!strcasecmp(name, "Security")) { if (!value) goto no_value; isns_config.ic_security = parse_int(value); } else if (!strcasecmp(name, "AuthKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_auth_key_file, value); } else if (!strcasecmp(name, "ServerKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_server_key_file, value); } else if (!strcasecmp(name, "ClientKeyStore") || !strcasecmp(name, "KeyStore")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_client_keystore, value); } else if (!strcasecmp(name, "Control.SourceName")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_name, value); } else if (!strcasecmp(name, "Control.AuthKeyFile")) { if (!value) goto no_value; isns_assign_string(&isns_config.ic_control_key_file, value); } else if (!strcasecmp(name, "Auth.ReplayWindow")) { if (!value) goto no_value; isns_config.ic_auth.replay_window = parse_timeout(value); } else if (!strcasecmp(name, "Auth.TimestampJitter")) { if (!value) goto no_value; isns_config.ic_auth.timestamp_jitter = parse_timeout(value); } else if (!strcasecmp(name, "Network.MaxSockets")) { if (!value) goto no_value; isns_config.ic_network.max_sockets = parse_timeout(value); } else if (!strcasecmp(name, "Network.ConnectTimeout")) { if (!value) goto no_value; isns_config.ic_network.connect_timeout = parse_timeout(value); } else if (!strcasecmp(name, "Network.ReconnectTimeout")) { if (!value) goto no_value; isns_config.ic_network.reconnect_timeout = parse_timeout(value); } else if (!strcasecmp(name, "Network.CallTimeout")) { if (!value) goto no_value; isns_config.ic_network.call_timeout = parse_timeout(value); } else { fprintf(stderr, "Unknown config item %s=%s\n", name, value); } return 0; no_value: fprintf(stderr, "*** Missing value in configuration assignment for %s ***\n", name); return -1; } open-iscsi-2.0.873/utils/open-isns/config.h.in000066400000000000000000000054351175631155400210610ustar00rootroot00000000000000/* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Define to 1 if you have the header file. */ #undef HAVE_ERRNO_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define if you have the header file. */ #undef HAVE_GETOPT_H /* Define if you have the `getopt_long' function. */ #undef HAVE_GETOPT_LONG /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_LOCALE_H /* Define to 1 if you have the header file. */ #undef HAVE_MALLOC_H /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_OPENSSL_CRYPTO_H /* Define to 1 if you have the header file. */ #undef HAVE_SLP_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have that is POSIX.1 compatible. */ #undef HAVE_SYS_WAIT_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define if you want to support iSNS authentication */ #undef WITH_SECURITY /* Define if you want to support SLP discovery */ #undef WITH_SLP /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif open-iscsi-2.0.873/utils/open-isns/configure000077500000000000000000005611151175631155400207470ustar00rootroot00000000000000#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.63 for open-isns 0.90. # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, # 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # PATH needs CR # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then as_unset=unset else as_unset=false fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. case $0 in *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi # Work around bugs in pre-3.0 UWIN ksh. for as_var in ENV MAIL MAILPATH do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi # Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # CDPATH. $as_unset CDPATH if test "x$CONFIG_SHELL" = x; then if (eval ":") 2>/dev/null; then as_have_required=yes else as_have_required=no fi if test $as_have_required = yes && (eval ": (as_func_return () { (exit \$1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = \"\$1\" ); then : else exitcode=1 echo positional parameters were not saved. fi test \$exitcode = 0) || { (exit 1); exit 1; } ( as_lineno_1=\$LINENO as_lineno_2=\$LINENO test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } ") 2> /dev/null; then : else as_candidate_shells= as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. case $as_dir in /*) for as_base in sh bash ksh sh5; do as_candidate_shells="$as_candidate_shells $as_dir/$as_base" done;; esac done IFS=$as_save_IFS for as_shell in $as_candidate_shells $SHELL; do # Try only shells that exist, to save several forks. if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { ("$as_shell") 2> /dev/null <<\_ASEOF if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi : _ASEOF }; then CONFIG_SHELL=$as_shell as_have_required=yes if { "$as_shell" 2> /dev/null <<\_ASEOF if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi : (as_func_return () { (exit $1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = "$1" ); then : else exitcode=1 echo positional parameters were not saved. fi test $exitcode = 0) || { (exit 1); exit 1; } ( as_lineno_1=$LINENO as_lineno_2=$LINENO test "x$as_lineno_1" != "x$as_lineno_2" && test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } _ASEOF }; then break fi fi done if test "x$CONFIG_SHELL" != x; then for as_var in BASH_ENV ENV do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var done export CONFIG_SHELL exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi if test $as_have_required = no; then echo This script requires a shell more modern than all the echo shells that I found on your system. Please install a echo modern shell, or manually run the script under such a echo shell if you do have one. { (exit 1); exit 1; } fi fi fi (eval "as_func_return () { (exit \$1) } as_func_success () { as_func_return 0 } as_func_failure () { as_func_return 1 } as_func_ret_success () { return 0 } as_func_ret_failure () { return 1 } exitcode=0 if as_func_success; then : else exitcode=1 echo as_func_success failed. fi if as_func_failure; then exitcode=1 echo as_func_failure succeeded. fi if as_func_ret_success; then : else exitcode=1 echo as_func_ret_success failed. fi if as_func_ret_failure; then exitcode=1 echo as_func_ret_failure succeeded. fi if ( set x; as_func_ret_success y && test x = \"\$1\" ); then : else exitcode=1 echo positional parameters were not saved. fi test \$exitcode = 0") || { echo No shell found that supports shell functions. echo Please tell bug-autoconf@gnu.org about your system, echo including any error possibly output before this message. echo This can help us improve future autoconf versions. echo Configuration will now proceed without shell functions. } as_lineno_1=$LINENO as_lineno_2=$LINENO test "x$as_lineno_1" != "x$as_lineno_2" && test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a # line-number line after each line using $LINENO; the second 'sed' # does the real work. The second script uses 'N' to pair each # line-number line with the line containing $LINENO, and appends # trailing '-' during substitution so that $LINENO is not a special # case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the # scripts with optimization help from Paolo Bonzini. Blame Lee # E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in -n*) case `echo 'x\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. *) ECHO_C='\c';; esac;; *) ECHO_N='-n';; esac if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -p'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p=: else test -d ./-p && rmdir ./-p as_mkdir_p=false fi if test -x / >/dev/null 2>&1; then as_test_x='test -x' else if ls -dL / >/dev/null 2>&1; then as_ls_L_option=L else as_ls_L_option= fi as_test_x=' eval sh -c '\'' if test -d "$1"; then test -d "$1/."; else case $1 in -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi '\'' sh ' fi as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='open-isns' PACKAGE_TARNAME='open-isns' PACKAGE_VERSION='0.90' PACKAGE_STRING='open-isns 0.90' PACKAGE_BUGREPORT='' ac_unique_file="isnsd.c" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS OPTIMIZE SLPLIBS SECLIBS GETOPTSRC SH SET_MAKE LN_S INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM EGREP GREP CPP host_os host_vendor host_cpu host build_os build_vendor build_cpu build OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking with_security with_slp enable_memdebug ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) { $as_echo "$as_me: error: unrecognized option: $ac_option Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` { $as_echo "$as_me: error: missing argument to $ac_option" >&2 { (exit 1); exit 1; }; } fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 { (exit 1); exit 1; }; } ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; } done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || { $as_echo "$as_me: error: working directory cannot be determined" >&2 { (exit 1); exit 1; }; } test "X$ac_ls_di" = "X$ac_pwd_ls_di" || { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 { (exit 1); exit 1; }; } # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 { (exit 1); exit 1; }; } pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures open-isns 0.90 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/open-isns] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of open-isns 0.90:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-memdebug Enable malloc debugging Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-security Enable iSNS authentication - requires OpenSSL --with-slp Enable SLP for server discovery - requires OpenSLP Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF open-isns configure 0.90 generated by GNU Autoconf 2.63 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by open-isns $as_me 0.90, which was generated by GNU Autoconf 2.63. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; 2) ac_configure_args1="$ac_configure_args1 '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac done done $as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } $as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo cat <<\_ASBOX ## ---------------- ## ## Cache variables. ## ## ---------------- ## _ASBOX echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo cat <<\_ASBOX ## ----------------- ## ## Output variables. ## ## ----------------- ## _ASBOX echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then cat <<\_ASBOX ## ------------------- ## ## File substitutions. ## ## ------------------- ## _ASBOX echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then cat <<\_ASBOX ## ----------- ## ## confdefs.h. ## ## ----------- ## _ASBOX echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then ac_site_file1=$CONFIG_SITE elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test -r "$ac_site_file"; then { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special # files actually), so we avoid doing that. if test -f "$cache_file"; then { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 $as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} { (exit 1); exit 1; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_aux_dir= for ac_dir in aclocal "$srcdir"/aclocal; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in aclocal \"$srcdir\"/aclocal" >&5 $as_echo "$as_me: error: cannot find install-sh or install.sh in aclocal \"$srcdir\"/aclocal" >&2;} { (exit 1); exit 1; }; } fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. ac_config_headers="$ac_config_headers config.h" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:$LINENO: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:$LINENO: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:$LINENO: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:$LINENO: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&5 $as_echo "$as_me: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } # Provide some information about the compiler. $as_echo "$as_me:$LINENO: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 { (ac_try="$ac_compiler --version >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compiler --version >&5") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -v >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -v >&5") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -V >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -V >&5") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { (ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi { $as_echo "$as_me:$LINENO: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } if test -z "$ac_file"; then $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables See \`config.log' for more details." >&5 $as_echo "$as_me: error: C compiler cannot create executables See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; }; } fi ac_exeext=$ac_cv_exeext # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } # FIXME: These cross compiler hacks should be removed for Autoconf 3.0 # If not cross compiling, check that we can run a simple program. if test "$cross_compiling" != yes; then if { ac_try='./$ac_file' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&5 $as_echo "$as_me: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } fi fi fi { $as_echo "$as_me:$LINENO: result: yes" >&5 $as_echo "yes" >&6; } rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } { $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } { $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&5 $as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } fi rm -f conftest$ac_cv_exeext { $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT { $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if test "${ac_cv_objext+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&5 $as_echo "$as_me: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if test "${ac_cv_c_compiler_gnu+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_compiler_gnu=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if test "${ac_cv_prog_cc_g+set}" = set; then $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 CFLAGS="" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if test "${ac_cv_prog_cc_c89+set}" = set; then $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_c89=$ac_arg else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:$LINENO: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:$LINENO: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || { { $as_echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5 $as_echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;} { (exit 1); exit 1; }; } { $as_echo "$as_me:$LINENO: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if test "${ac_cv_build+set}" = set; then $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && { { $as_echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 $as_echo "$as_me: error: cannot guess build type; you must specify one" >&2;} { (exit 1); exit 1; }; } ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || { { $as_echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5 $as_echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;} { (exit 1); exit 1; }; } fi { $as_echo "$as_me:$LINENO: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) { { $as_echo "$as_me:$LINENO: error: invalid value of canonical build" >&5 $as_echo "$as_me: error: invalid value of canonical build" >&2;} { (exit 1); exit 1; }; };; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:$LINENO: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if test "${ac_cv_host+set}" = set; then $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || { { $as_echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 $as_echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} { (exit 1); exit 1; }; } fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) { { $as_echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 $as_echo "$as_me: error: invalid value of canonical host" >&2;} { (exit 1); exit 1; }; };; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if test "${ac_cv_prog_CPP+set}" = set; then $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then # Broken: success on invalid input. continue else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:$LINENO: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then # Broken: success on invalid input. continue else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&5 $as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if test "${ac_cv_path_GREP+set}" = set; then $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break ac_count=`expr $ac_count + 1` if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then { { $as_echo "$as_me:$LINENO: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 $as_echo "$as_me: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} { (exit 1); exit 1; }; } fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:$LINENO: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if test "${ac_cv_path_EGREP+set}" = set; then $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break ac_count=`expr $ac_count + 1` if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then { { $as_echo "$as_me:$LINENO: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 $as_echo "$as_me: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} { (exit 1); exit 1; }; } fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if test "${ac_cv_header_stdc+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_stdc=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF rm -f conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then : else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_header_stdc=no fi rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then cat >>confdefs.h <<\_ACEOF #define STDC_HEADERS 1 _ACEOF fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } as_val=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } if test "${ac_cv_c_bigendian+set}" = set; then $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler #endif typedef int dummy; _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then # Check for potential -arch flags. It is not universal unless # there are some -arch flags. Note that *ppc* also matches # ppc64. This check is also rather less than ideal. case "${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS}" in #( *-arch*ppc*|*-arch*i386*|*-arch*x86_64*) ac_cv_c_bigendian=universal;; esac else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include int main () { #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ && LITTLE_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then # It does; now see whether it defined to BIG_ENDIAN or not. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include int main () { #if BYTE_ORDER != BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_bigendian=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include int main () { #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then # It does; now see whether it defined to _BIG_ENDIAN or not. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include int main () { #ifndef _BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_bigendian=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. if test "$cross_compiling" = yes; then # Try to guess by grepping values from an object file. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } extern int foo; int main () { return use_ascii (foo) == use_ebcdic (foo); ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then ac_cv_c_bigendian=yes fi if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else # finding both strings is unlikely to happen, but who knows? ac_cv_c_bigendian=unknown fi fi else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default int main () { /* Are we little or big endian? From Harbison&Steele. */ union { long int l; char c[sizeof (long int)]; } u; u.l = 1; return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF rm -f conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_c_bigendian=no else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_c_bigendian=yes fi rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 $as_echo "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) cat >>confdefs.h <<\_ACEOF #define WORDS_BIGENDIAN 1 _ACEOF ;; #( no) ;; #( universal) cat >>confdefs.h <<\_ACEOF #define AC_APPLE_UNIVERSAL_BUILD 1 _ACEOF ;; #( *) { { $as_echo "$as_me:$LINENO: error: unknown endianness presetting ac_cv_c_bigendian=no (or yes) will help" >&5 $as_echo "$as_me: error: unknown endianness presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} { (exit 1); exit 1; }; } ;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if test "${ac_cv_prog_CPP+set}" = set; then $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then # Broken: success on invalid input. continue else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:$LINENO: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then # Broken: success on invalid input. continue else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&5 $as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if test "${ac_cv_path_install+set}" = set; then $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in ./ | .// | /cC/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:$LINENO: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:$LINENO: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:$LINENO: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi { $as_echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:$LINENO: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi # Extract the first word of "sh", so it can be a program name with args. set dummy sh; ac_word=$2 { $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_path_SH+set}" = set; then $as_echo_n "(cached) " >&6 else case $SH in [\\/]* | ?:[\\/]*) ac_cv_path_SH="$SH" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_SH="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi SH=$ac_cv_path_SH if test -n "$SH"; then { $as_echo "$as_me:$LINENO: result: $SH" >&5 $as_echo "$SH" >&6; } else { $as_echo "$as_me:$LINENO: result: no" >&5 $as_echo "no" >&6; } fi { $as_echo "$as_me:$LINENO: checking for inline" >&5 $as_echo_n "checking for inline... " >&6; } if test "${ac_cv_c_inline+set}" = set; then $as_echo_n "(cached) " >&6 else ac_cv_c_inline=no for ac_kw in inline __inline__ __inline; do cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifndef __cplusplus typedef int foo_t; static $ac_kw foo_t static_foo () {return 0; } $ac_kw foo_t foo () {return 0; } #endif _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_inline=$ac_kw else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext test "$ac_cv_c_inline" != no && break done fi { $as_echo "$as_me:$LINENO: result: $ac_cv_c_inline" >&5 $as_echo "$ac_cv_c_inline" >&6; } case $ac_cv_c_inline in inline | yes) ;; *) case $ac_cv_c_inline in no) ac_val=;; *) ac_val=$ac_cv_c_inline;; esac cat >>confdefs.h <<_ACEOF #ifndef __cplusplus #define inline $ac_val #endif _ACEOF ;; esac if test "$GCC" = "yes"; then CFLAGS="-Wall -fno-strict-aliasing $CFLAGS" CPPFLAGS="$CPPFLAGS -D_GNU_SOURCE" fi { $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if test "${ac_cv_header_stdc+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_stdc=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF rm -f conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then : else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_header_stdc=no fi rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi fi { $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then cat >>confdefs.h <<\_ACEOF #define STDC_HEADERS 1 _ACEOF fi { $as_echo "$as_me:$LINENO: checking for sys/wait.h that is POSIX.1 compatible" >&5 $as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } if test "${ac_cv_header_sys_wait_h+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif int main () { int s; wait (&s); s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_sys_wait_h=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_sys_wait_h=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_wait_h" >&5 $as_echo "$ac_cv_header_sys_wait_h" >&6; } if test $ac_cv_header_sys_wait_h = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_SYS_WAIT_H 1 _ACEOF fi for ac_header in errno.h fcntl.h malloc.h stdlib.h string.h strings.h sys/time.h unistd.h locale.h getopt.h do as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 $as_echo_n "checking $ac_header usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 $as_echo_n "checking $ac_header presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include <$ac_header> _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 $as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ;; esac { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi as_val=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done # Check if socket() is in libsocket { $as_echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 $as_echo_n "checking for socket in -lsocket... " >&6; } if test "${ac_cv_lib_socket_socket+set}" = set; then $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsocket $LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char socket (); int main () { return socket (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || $as_test_x conftest$ac_exeext }; then ac_cv_lib_socket_socket=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_socket_socket=no fi rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 $as_echo "$ac_cv_lib_socket_socket" >&6; } if test "x$ac_cv_lib_socket_socket" = x""yes; then LIBS="$LIBS -lsocket" fi { $as_echo "$as_me:$LINENO: checking for getopt_long" >&5 $as_echo_n "checking for getopt_long... " >&6; } if test "${ac_cv_func_getopt_long+set}" = set; then $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define getopt_long to an innocuous variant, in case declares getopt_long. For example, HP-UX 11i declares gettimeofday. */ #define getopt_long innocuous_getopt_long /* System header to define __stub macros and hopefully few prototypes, which can conflict with char getopt_long (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef getopt_long /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char getopt_long (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_getopt_long || defined __stub___getopt_long choke me #endif int main () { return getopt_long (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || $as_test_x conftest$ac_exeext }; then ac_cv_func_getopt_long=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_getopt_long=no fi rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi { $as_echo "$as_me:$LINENO: result: $ac_cv_func_getopt_long" >&5 $as_echo "$ac_cv_func_getopt_long" >&6; } if test "x$ac_cv_func_getopt_long" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_GETOPT_LONG 1 _ACEOF else GETOPTSRC="$GETOPTSRC \$(top_srcdir)/compat/my_getopt.c" CPPFLAGS="-I\$(top_srcdir)/compat/ $CPPFLAGS" cat >>confdefs.h <<\_ACEOF #define HAVE_GETOPT_H 1 _ACEOF fi WITH_SECURITY=maybe # Check whether --with-security was given. if test "${with_security+set}" = set; then withval=$with_security; if test "x$withval" = "xno" -o "x$withval" = "xyes"; then WITH_SECURITY=$withval else WITH_SECURITY=yes CPPFLAGS="$CPPFLAGS -I${withval}" LDFLAGS="$LDFLAGS -L${withval}" fi fi if test "x$WITH_SECURITY" != "xno" ; then # Check for openssl support - very primitive, we just # check for the presence of crypto.h for ac_header in openssl/crypto.h do as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 $as_echo_n "checking $ac_header usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 $as_echo_n "checking $ac_header presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include <$ac_header> _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 $as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ;; esac { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi as_val=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF else have_libcrypto=no fi done { $as_echo "$as_me:$LINENO: checking for EVP_PKEY_new in -lcrypto" >&5 $as_echo_n "checking for EVP_PKEY_new in -lcrypto... " >&6; } if test "${ac_cv_lib_crypto_EVP_PKEY_new+set}" = set; then $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcrypto $LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char EVP_PKEY_new (); int main () { return EVP_PKEY_new (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || $as_test_x conftest$ac_exeext }; then ac_cv_lib_crypto_EVP_PKEY_new=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_crypto_EVP_PKEY_new=no fi rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:$LINENO: result: $ac_cv_lib_crypto_EVP_PKEY_new" >&5 $as_echo "$ac_cv_lib_crypto_EVP_PKEY_new" >&6; } if test "x$ac_cv_lib_crypto_EVP_PKEY_new" = x""yes; then SECLIBS="-lcrypto" else have_libcrypto=no fi if test "x$have_libcrypto" != "xno" ; then cat >>confdefs.h <<\_ACEOF #define WITH_SECURITY 1 _ACEOF else if test "x$WITH_SECURITY" = "xyes" ; then { { $as_echo "$as_me:$LINENO: error: Security requested, but unable to find libcrypto" >&5 $as_echo "$as_me: error: Security requested, but unable to find libcrypto" >&2;} { (exit 1); exit 1; }; } fi fi fi WITH_SLP=maybe # Check whether --with-slp was given. if test "${with_slp+set}" = set; then withval=$with_slp; if test "x$withval" = "xno" -o "x$withval" = "xyes"; then WITH_SLP=$withval else WITH_SLP=yes CPPFLAGS="$CPPFLAGS -I${withval}" LDFLAGS="$LDFLAGS -L${withval}" fi fi if test "x$WITH_SLP" != "xno" ; then # Check for openslp support - very primitive for ac_header in slp.h do as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 $as_echo_n "checking $ac_header usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 $as_echo_n "checking $ac_header presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include <$ac_header> _ACEOF if { (ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext { $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 $as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 $as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ;; esac { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 $as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then $as_echo_n "(cached) " >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi ac_res=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi as_val=`eval 'as_val=${'$as_ac_Header'} $as_echo "$as_val"'` if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF else have_openslp=no fi done { $as_echo "$as_me:$LINENO: checking for SLPOpen in -lslp" >&5 $as_echo_n "checking for SLPOpen in -lslp... " >&6; } if test "${ac_cv_lib_slp_SLPOpen+set}" = set; then $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lslp $LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char SLPOpen (); int main () { return SLPOpen (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" $as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || $as_test_x conftest$ac_exeext }; then ac_cv_lib_slp_SLPOpen=yes else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_slp_SLPOpen=no fi rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:$LINENO: result: $ac_cv_lib_slp_SLPOpen" >&5 $as_echo "$ac_cv_lib_slp_SLPOpen" >&6; } if test "x$ac_cv_lib_slp_SLPOpen" = x""yes; then SLPLIBS="-lslp" else have_openslp=no fi if test "x$have_openslp" != "xno" ; then cat >>confdefs.h <<\_ACEOF #define WITH_SLP 1 _ACEOF else if test "x$WITH_SLP" = "xyes" ; then { { $as_echo "$as_me:$LINENO: error: SLP requested, but unable to find openslp" >&5 $as_echo "$as_me: error: SLP requested, but unable to find openslp" >&2;} { (exit 1); exit 1; }; } fi fi fi MEMDEBUG= # Check whether --enable-memdebug was given. if test "${enable_memdebug+set}" = set; then enableval=$enable_memdebug; if test "x$enableval" = "xyes" ; then CPPFLAGS="$CPPFLAGS -DMEMDEBUG" fi fi ac_config_files="$ac_config_files Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes (double-quote # substitution turns \\\\ into \\, and sed turns \\ into \). sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : ${CONFIG_STATUS=./config.status} ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # PATH needs CR # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then as_unset=unset else as_unset=false fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. case $0 in *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi # Work around bugs in pre-3.0 UWIN ksh. for as_var in ENV MAIL MAILPATH do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi # Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # CDPATH. $as_unset CDPATH as_lineno_1=$LINENO as_lineno_2=$LINENO test "x$as_lineno_1" != "x$as_lineno_2" && test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a # line-number line after each line using $LINENO; the second 'sed' # does the real work. The second script uses 'N' to pair each # line-number line with the line containing $LINENO, and appends # trailing '-' during substitution so that $LINENO is not a special # case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the # scripts with optimization help from Paolo Bonzini. Blame Lee # E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in -n*) case `echo 'x\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. *) ECHO_C='\c';; esac;; *) ECHO_N='-n';; esac if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -p'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p=: else test -d ./-p && rmdir ./-p as_mkdir_p=false fi if test -x / >/dev/null 2>&1; then as_test_x='test -x' else if ls -dL / >/dev/null 2>&1; then as_ls_L_option=L else as_ls_L_option= fi as_test_x=' eval sh -c '\'' if test -d "$1"; then test -d "$1/."; else case $1 in -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi '\'' sh ' fi as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 # Save the log message, to keep $[0] and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by open-isns $as_me 0.90, which was generated by GNU Autoconf 2.63. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files from templates according to the current configuration. Usage: $0 [OPTION]... [FILE]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_version="\\ open-isns config.status 0.90 configured by $0, generated by GNU Autoconf 2.63, with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" Copyright (C) 2008 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header { $as_echo "$as_me: error: ambiguous option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; };; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) { $as_echo "$as_me: error: unrecognized option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; *) ac_config_targets="$ac_config_targets $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 $as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} { (exit 1); exit 1; }; };; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= trap 'exit_status=$? { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status ' 0 trap '{ (exit 1); exit 1; }' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || { $as_echo "$as_me: cannot create a temporary directory in ." >&2 { (exit 1); exit 1; } } # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=' ' ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 $as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 $as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 $as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\).*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\).*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 $as_echo "$as_me: error: could not setup config files machinery" >&2;} { (exit 1); exit 1; }; } _ACEOF # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=/{ s/:*\$(srcdir):*/:/ s/:*\${srcdir}:*/:/ s/:*@srcdir@:*/:/ s/^\([^=]*=[ ]*\):*/\1/ s/:*$// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_t=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_t"; then break elif $ac_last_try; then { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_HEADERS" >&5 $as_echo "$as_me: error: could not make $CONFIG_HEADERS" >&2;} { (exit 1); exit 1; }; } else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 $as_echo "$as_me: error: could not setup config headers machinery" >&2;} { (exit 1); exit 1; }; } fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: invalid tag $ac_tag" >&5 $as_echo "$as_me: error: invalid tag $ac_tag" >&2;} { (exit 1); exit 1; }; };; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 $as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} { (exit 1); exit 1; }; };; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac ac_file_inputs="$ac_file_inputs '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$tmp/stdin" \ || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 $as_echo "$as_me: error: could not create $ac_file" >&2;} { (exit 1); exit 1; }; } ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` { as_dir="$ac_dir" case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 $as_echo "$as_me: error: cannot create directory $as_dir" >&2;} { (exit 1); exit 1; }; }; } ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p ' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 $as_echo "$as_me: error: could not create $ac_file" >&2;} { (exit 1); exit 1; }; } test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} rm -f "$tmp/stdin" case $ac_file in -) cat "$tmp/out" && rm -f "$tmp/out";; *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; esac \ || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 $as_echo "$as_me: error: could not create $ac_file" >&2;} { (exit 1); exit 1; }; } ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" } >"$tmp/config.h" \ || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 $as_echo "$as_me: error: could not create $ac_file" >&2;} { (exit 1); exit 1; }; } if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$tmp/config.h" "$ac_file" \ || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 $as_echo "$as_me: error: could not create $ac_file" >&2;} { (exit 1); exit 1; }; } fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 $as_echo "$as_me: error: could not create -" >&2;} { (exit 1); exit 1; }; } fi ;; esac done # for ac_tag { (exit 0); exit 0; } _ACEOF chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 $as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || { (exit 1); exit 1; } fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:$LINENO: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi open-iscsi-2.0.873/utils/open-isns/configure.ac000066400000000000000000000054271175631155400213250ustar00rootroot00000000000000AC_INIT(open-isns, [0.90]) AC_CONFIG_SRCDIR([isnsd.c]) AC_CONFIG_AUX_DIR([aclocal]) AC_CONFIG_HEADER(config.h) AC_PROG_CC AC_CANONICAL_HOST AC_C_BIGENDIAN AC_PROG_CPP AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_MAKE_SET AC_PATH_PROG(SH, sh) dnl C Compiler features AC_C_INLINE if test "$GCC" = "yes"; then CFLAGS="-Wall -fno-strict-aliasing $CFLAGS" CPPFLAGS="$CPPFLAGS -D_GNU_SOURCE" fi dnl Checks for header files. AC_HEADER_STDC AC_HEADER_SYS_WAIT AC_CHECK_HEADERS([errno.h fcntl.h malloc.h stdlib.h string.h strings.h sys/time.h unistd.h locale.h getopt.h]) # Check if socket() is in libsocket AC_CHECK_LIB(socket, socket, [LIBS="$LIBS -lsocket"]) AC_SUBST(GETOPTSRC) AC_CHECK_FUNC(getopt_long, AC_DEFINE(HAVE_GETOPT_LONG, 1, [Define if you have the `getopt_long' function.]), [GETOPTSRC="$GETOPTSRC \$(top_srcdir)/compat/my_getopt.c" CPPFLAGS="-I\$(top_srcdir)/compat/ $CPPFLAGS" AC_DEFINE(HAVE_GETOPT_H, 1, [Define if you have the header file.])]) WITH_SECURITY=maybe AC_ARG_WITH(security, [ --with-security Enable iSNS authentication - requires OpenSSL], [ if test "x$withval" = "xno" -o "x$withval" = "xyes"; then WITH_SECURITY=$withval else WITH_SECURITY=yes CPPFLAGS="$CPPFLAGS -I${withval}" LDFLAGS="$LDFLAGS -L${withval}" fi ] ) if test "x$WITH_SECURITY" != "xno" ; then # Check for openssl support - very primitive, we just # check for the presence of crypto.h AC_CHECK_HEADERS([openssl/crypto.h], , [have_libcrypto=no]) AC_CHECK_LIB(crypto, EVP_PKEY_new, [SECLIBS="-lcrypto"], [have_libcrypto=no]) if test "x$have_libcrypto" != "xno" ; then AC_DEFINE(WITH_SECURITY, 1, [Define if you want to support iSNS authentication]) else if test "x$WITH_SECURITY" = "xyes" ; then AC_MSG_ERROR([Security requested, but unable to find libcrypto]) fi fi fi AC_SUBST(SECLIBS) WITH_SLP=maybe AC_ARG_WITH(slp, [ --with-slp Enable SLP for server discovery - requires OpenSLP], [ if test "x$withval" = "xno" -o "x$withval" = "xyes"; then WITH_SLP=$withval else WITH_SLP=yes CPPFLAGS="$CPPFLAGS -I${withval}" LDFLAGS="$LDFLAGS -L${withval}" fi ] ) if test "x$WITH_SLP" != "xno" ; then # Check for openslp support - very primitive AC_CHECK_HEADERS([slp.h],, [have_openslp=no]) AC_CHECK_LIB(slp, SLPOpen, [SLPLIBS="-lslp"], [have_openslp=no]) if test "x$have_openslp" != "xno" ; then AC_DEFINE(WITH_SLP, 1, [Define if you want to support SLP discovery]) else if test "x$WITH_SLP" = "xyes" ; then AC_MSG_ERROR([SLP requested, but unable to find openslp]) fi fi fi AC_SUBST(SLPLIBS) MEMDEBUG= AC_ARG_ENABLE(memdebug, [ --enable-memdebug Enable malloc debugging], [ if test "x$enableval" = "xyes" ; then CPPFLAGS="$CPPFLAGS -DMEMDEBUG" fi ] ) AC_SUBST(OPTIMIZE) AC_OUTPUT(Makefile) open-iscsi-2.0.873/utils/open-isns/db-file.c000066400000000000000000000323061175631155400205010ustar00rootroot00000000000000/* * iSNS object database * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include #include #include "isns.h" #include "objects.h" #include "message.h" #include "util.h" #include "db.h" #define DBE_FILE_VERSION 1 struct isns_db_file_info { uint32_t db_version; uint32_t db_last_eid; uint32_t db_last_index; }; struct isns_db_object_info { uint32_t db_version; char db_type[64]; uint32_t db_parent; uint32_t db_state; uint32_t db_flags; uint32_t db_scn_mask; /* reserved bytes */ uint32_t __db_reserved[15]; }; static int isns_dbe_file_sync(isns_db_t *); static int isns_dbe_file_reload(isns_db_t *); static int isns_dbe_file_store(isns_db_t *, const isns_object_t *); static int isns_dbe_file_remove(isns_db_t *, const isns_object_t *); static int __dbe_file_load_all(const char *, isns_object_list_t *); /* * Helper functions */ static const char * __path_concat(const char *dirname, const char *basename) { static char pathname[PATH_MAX]; snprintf(pathname, sizeof(pathname), "%s/%s", dirname, basename); return pathname; } static const char * __print_index(uint32_t index) { static char namebuf[32]; snprintf(namebuf, sizeof(namebuf), "%08x", index); return namebuf; } static int __get_index(const char *name, uint32_t *result) { char *end; *result = strtoul(name, &end, 16); if (*end) return ISNS_INTERNAL_ERROR; return ISNS_SUCCESS; } /* * Build path names for an object */ static const char * __dbe_file_object_path(const char *dirname, const isns_object_t *obj) { return __path_concat(dirname, __print_index(obj->ie_index)); } /* * Build a path name for a temporary file. * Cannot use __path_concat, because we need both names * when storing objects */ static const char * __dbe_file_object_temp(const char *dirname, const isns_object_t *obj) { static char pathname[PATH_MAX]; snprintf(pathname, sizeof(pathname), "%s/.%s", dirname, __print_index(obj->ie_index)); return pathname; } /* * Recursively create a directory */ static int __dbe_mkdir_path(const char *dirname) { unsigned int true_len = strlen(dirname); char *copy, *s; copy = isns_strdup(dirname); /* Walk up until we find a directory that exists */ while (1) { s = strrchr(copy, '/'); if (s == NULL) break; *s = '\0'; if (access(copy, F_OK) == 0) break; } while (strcmp(dirname, copy)) { unsigned int len = strlen(copy); /* Better safe than sorry */ isns_assert(len < true_len); /* Put the next slash back in */ copy[len] = '/'; /* and try to create the directory */ if (mkdir(copy, 0700) < 0) return -1; } return 0; } /* * Write an object to a file */ static int __dbe_file_store_object(const char *dirname, const isns_object_t *obj) { struct isns_db_object_info info; const char *path = __dbe_file_object_path(dirname, obj); const char *temp = __dbe_file_object_temp(dirname, obj); buf_t *bp = NULL; int status = ISNS_INTERNAL_ERROR; isns_debug_state("DB: Storing object %u -> %s\n", obj->ie_index, path); if (access(dirname, F_OK) < 0 && (errno != ENOENT || __dbe_mkdir_path(dirname) < 0)) { isns_error("DB: Unable to create %s: %m\n", dirname); goto out; } bp = buf_open(temp, O_CREAT|O_TRUNC|O_WRONLY); if (bp == NULL) { isns_error("Unable to open %s: %m\n", temp); goto out; } /* Encode the header info ... */ memset(&info, 0, sizeof(info)); info.db_version = htonl(DBE_FILE_VERSION); info.db_state = htonl(obj->ie_state); info.db_flags = htonl(obj->ie_flags); info.db_scn_mask = htonl(obj->ie_scn_mask); strcpy(info.db_type, obj->ie_template->iot_name); if (obj->ie_container) info.db_parent = htonl(obj->ie_container->ie_index); if (!buf_put(bp, &info, sizeof(info))) goto out; /* ... and attributes */ status = isns_attr_list_encode(bp, &obj->ie_attrs); if (status != ISNS_SUCCESS) goto out; /* Renaming an open file. NFS will hate this */ if (rename(temp, path) < 0) { isns_error("Cannot rename %s -> %s: %m\n", temp, path); unlink(temp); status = ISNS_INTERNAL_ERROR; } out: if (bp) buf_close(bp); return status; } /* * Store all children of an object */ static int __dbe_file_store_children(const char *dirname, const isns_object_t *obj) { int status = ISNS_SUCCESS; unsigned int i; for (i = 0; i < obj->ie_children.iol_count; ++i) { isns_object_t *child; child = obj->ie_children.iol_data[i]; status = __dbe_file_store_object(dirname, child); if (status) break; status = __dbe_file_store_children(dirname, child); if (status) break; } return status; } /* * Remove object and children */ static int __dbe_file_remove_object(const char *dirname, const isns_object_t *obj) { const char *path = __dbe_file_object_path(dirname, obj); isns_debug_state("DB: Purging object %u (%s)\n", obj->ie_index, path); if (unlink(path) < 0) isns_error("DB: Cannot remove %s: %m\n", path); return ISNS_SUCCESS; } static int __dbe_file_remove_children(const char *dirname, const isns_object_t *obj) { const isns_object_list_t *list = &obj->ie_children; unsigned int i; for (i = 0; i < list->iol_count; ++i) __dbe_file_remove_object(dirname, list->iol_data[i]); return ISNS_SUCCESS; } /* * Load an object from file */ static int __dbe_file_load_object(const char *filename, const char *basename, isns_object_list_t *result) { struct isns_db_object_info info; isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_object_template_t *tmpl; isns_object_t *obj = NULL; buf_t *bp = NULL; uint32_t index; int status; bp = buf_open(filename, O_RDONLY); if (bp == NULL) { isns_error("Unable to open %s: %m\n", filename); goto internal_error; } /* Decode the header ... */ if (!buf_get(bp, &info, sizeof(info))) goto internal_error; if (info.db_version != htonl(DBE_FILE_VERSION)) { /* If we ever have to deal with a DB version * upgrade, we could do it here. */ isns_fatal("Found iSNS database version %u; not supported\n", ntohl(info.db_version)); } /* ... and attributes */ status = isns_attr_list_decode(bp, &attrs); if (status != ISNS_SUCCESS) goto out; /* Get the index from the file name */ status = __get_index(basename, &index); if (status != ISNS_SUCCESS) goto out; tmpl = isns_object_template_by_name(info.db_type); if (tmpl == NULL) { isns_error("DB: Bad type name \"%s\" in object file\n", info.db_type); goto internal_error; } obj = isns_create_object(tmpl, &attrs, NULL); if (obj == NULL) goto internal_error; obj->ie_state = ntohl(info.db_state); obj->ie_flags = ntohl(info.db_flags) & ~(ISNS_OBJECT_DIRTY); obj->ie_scn_mask = ntohl(info.db_scn_mask); obj->ie_index = index; /* Stash away the parent's index; we resolve them later on * once we've loaded all objects */ obj->ie_container_idx = ntohl(info.db_parent); isns_object_list_append(result, obj); out: if (bp) buf_close(bp); if (obj) isns_object_release(obj); isns_attr_list_destroy(&attrs); return status; internal_error: isns_error("Unable to load %s: Internal error\n", filename); status = ISNS_INTERNAL_ERROR; goto out; } /* * Load contents of directory into our database. * * We take two passes over the directory. In the first pass, we load * all regular files containing objects. The file names correspond to * the DB index. * * In the second pass, we load all directories, containing children of * an object. The directories names are formed by the object's index, * with ".d" appended to it. */ static int __dbe_file_load_all(const char *dirpath, isns_object_list_t *result) { struct dirent *dp; DIR *dir; int status = ISNS_SUCCESS; if ((dir = opendir(dirpath)) == NULL) { isns_error("DB: cannot open %s: %m\n", dirpath); return ISNS_INTERNAL_ERROR; } while ((dp = readdir(dir)) != NULL) { struct stat stb; const char *path; if (dp->d_name[0] == '.' || !strcmp(dp->d_name, "DB")) continue; path = __path_concat(dirpath, dp->d_name); if (lstat(path, &stb) < 0) { isns_error("DB: cannot stat %s: %m\n", path); status = ISNS_INTERNAL_ERROR; } else if (S_ISREG(stb.st_mode)) { status = __dbe_file_load_object(path, dp->d_name, result); } else { isns_debug_state("DB: ignoring %s\n", path); } if (status != ISNS_SUCCESS) break; } closedir(dir); return status; } /* * Load and store DB metadata */ static int __dbe_file_write_info(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; const char *path; buf_t *bp; int status = ISNS_INTERNAL_ERROR; path = __path_concat(back->idb_name, "DB"); if ((bp = buf_open(path, O_CREAT|O_TRUNC|O_WRONLY)) == NULL) { isns_error("Unable to write %s: %m\n", path); goto out; } if (buf_put32(bp, DBE_FILE_VERSION) && buf_put32(bp, db->id_last_eid) && buf_put32(bp, db->id_last_index)) status = ISNS_SUCCESS; out: if (bp) buf_close(bp); return status; } static int __dbe_file_load_info(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; struct isns_db_file_info info; const char *path; buf_t *bp = NULL; int status; path = __path_concat(back->idb_name, "DB"); if ((bp = buf_open(path, O_RDONLY)) == NULL) { status = ISNS_NO_SUCH_ENTRY; goto out; } status = ISNS_INTERNAL_ERROR; if (!buf_get32(bp, &info.db_version)) goto out; if (info.db_version != DBE_FILE_VERSION) { isns_error("DB file from unsupported version %04x\n", info.db_version); goto out; } if (buf_get32(bp, &info.db_last_eid) && buf_get32(bp, &info.db_last_index)) { db->id_last_eid = info.db_last_eid; db->id_last_index = info.db_last_index; status = ISNS_SUCCESS; } out: if (bp) buf_close(bp); return status; } /* * Find object with the given index. */ static isns_object_t * __dbe_find_object(isns_object_list_t *list, uint32_t index) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_index == index) return obj; } return NULL; } int isns_dbe_file_reload(isns_db_t *db) { isns_db_backend_t *back = db->id_backend; int status; unsigned int i; isns_debug_state("DB: loading all objects from %s\n", back->idb_name); if (access(back->idb_name, R_OK) < 0) { if (errno == ENOENT) { /* Empty database is okay */ return ISNS_NO_SUCH_ENTRY; } isns_error("Cannot open database %s: %m\n", back->idb_name); return ISNS_INTERNAL_ERROR; } status = __dbe_file_load_info(db); if (status) return status; status = __dbe_file_load_all(back->idb_name, db->id_objects); if (status) return status; /* Resolve parent/child relationship for all nodes */ for (i = 0; i < db->id_objects->iol_count; ++i) { isns_object_t *obj = db->id_objects->iol_data[i]; uint32_t index = obj->ie_container_idx; isns_object_t *parent; if (index == 0) continue; obj->ie_container = NULL; parent = __dbe_find_object(db->id_objects, index); if (parent == NULL) { isns_warning("DB: object %u references " "unknown container %u\n", obj->ie_index, index); } else { isns_object_attach(obj, parent); } } /* Add objects to the appropriate lists */ for (i = 0; i < db->id_objects->iol_count; ++i) { isns_object_template_t *tmpl; isns_object_t *obj = db->id_objects->iol_data[i]; switch (obj->ie_state) { case ISNS_OBJECT_STATE_MATURE: isns_scope_add(db->id_global_scope, obj); obj->ie_references++; tmpl = obj->ie_template; if (tmpl->iot_build_relation && !tmpl->iot_build_relation(db, obj, NULL)) isns_warning("DB: cannot build relation for " "object %u\n", obj->ie_index); if (obj->ie_relation) isns_relation_add(db->id_relations, obj->ie_relation); if (ISNS_IS_ENTITY(obj)) isns_esi_register(obj); break; case ISNS_OBJECT_STATE_LIMBO: isns_object_list_append(&db->id_limbo, obj); break; default: isns_error("Unexpected object state %d in object %u " "loaded from %s\n", obj->ie_state, obj->ie_index, back->idb_name); } /* Clear the dirty flag, which will be set when the object is created. */ obj->ie_flags &= ~ISNS_OBJECT_DIRTY; } return ISNS_SUCCESS; } int isns_dbe_file_sync(isns_db_t *db) { return __dbe_file_write_info(db); } int isns_dbe_file_store(isns_db_t *db, const isns_object_t *obj) { isns_db_backend_t *back = db->id_backend; int status; if (obj->ie_index == 0) { isns_error("DB: Refusing to store object with index 0\n"); return ISNS_INTERNAL_ERROR; } status = __dbe_file_store_object(back->idb_name, obj); if (status == ISNS_SUCCESS) status = __dbe_file_store_children(back->idb_name, obj); return status; } int isns_dbe_file_remove(isns_db_t *db, const isns_object_t *obj) { isns_db_backend_t *back = db->id_backend; int status; status = __dbe_file_remove_object(back->idb_name, obj); if (status == ISNS_SUCCESS) status = __dbe_file_remove_children(back->idb_name, obj); return status; } /* * Create the file backend */ isns_db_backend_t * isns_create_file_db_backend(const char *pathname) { isns_db_backend_t *back; isns_debug_state("Creating file DB backend (%s)\n", pathname); back = isns_calloc(1, sizeof(*back)); back->idb_name = isns_strdup(pathname); back->idb_reload = isns_dbe_file_reload; back->idb_sync = isns_dbe_file_sync; back->idb_store = isns_dbe_file_store; back->idb_remove = isns_dbe_file_remove; return back; } open-iscsi-2.0.873/utils/open-isns/db-policy.c000066400000000000000000000105771175631155400210670ustar00rootroot00000000000000/* * Use database as policy and keystore * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #ifdef WITH_SECURITY #include #include #endif #include "isns.h" #include "security.h" #include "objects.h" #include "vendor.h" #include "util.h" #include "config.h" /* * DB keystore */ typedef struct isns_db_keystore isns_db_keystore_t; struct isns_db_keystore { isns_keystore_t sd_base; isns_db_t * sd_db; isns_object_t * sd_control; }; /* * Look up the policy object given its SPI */ isns_object_t * __isns_db_keystore_lookup(isns_db_keystore_t *store, const char *name, size_t namelen) { isns_attr_list_t keys = ISNS_ATTR_LIST_INIT; char namebuf[256]; if (namelen >= sizeof(namebuf)) return NULL; memcpy(namebuf, name, namelen); namebuf[namelen] = '\0'; isns_attr_list_append_string(&keys, OPENISNS_TAG_POLICY_SPI, namebuf); return isns_db_lookup(store->sd_db, NULL, &keys); } /* * Load a DSA key from the DB store */ static EVP_PKEY * __isns_db_keystore_find(isns_keystore_t *store_base, const char *name, size_t namelen) { #ifdef WITH_SECURITY isns_db_keystore_t *store = (isns_db_keystore_t *) store_base; isns_object_t *obj; const void *key_data; size_t key_size; obj = __isns_db_keystore_lookup(store, name, namelen); if (obj == NULL) return NULL; if (!isns_object_get_opaque(obj, OPENISNS_TAG_POLICY_KEY, &key_data, &key_size)) return NULL; return isns_dsa_decode_public(key_data, key_size); #else return NULL; #endif } /* * Retrieve policy from database */ static void __isns_db_keystore_copy_policy_string(isns_object_t *obj, uint32_t tag, char **var) { const char *value; if (!isns_object_get_string(obj, tag, &value)) return; isns_assign_string(var, value); } static void __isns_db_keystore_copy_policy_strings(isns_object_t *obj, uint32_t tag, struct string_array *array) { isns_attr_list_t *attrs = &obj->ie_attrs; unsigned int i; for (i = 0; i < attrs->ial_count; ++i) { isns_attr_t *attr = attrs->ial_data[i]; if (attr->ia_tag_id != tag || !ISNS_ATTR_IS_STRING(attr)) continue; isns_string_array_append(array, attr->ia_value.iv_string); } } static isns_policy_t * __isns_db_keystore_get_policy(isns_keystore_t *store_base, const char *name, size_t namelen) { isns_db_keystore_t *store = (isns_db_keystore_t *) store_base; isns_policy_t *policy; isns_object_t *obj; uint32_t intval; obj = __isns_db_keystore_lookup(store, name, namelen); if (obj == NULL) return NULL; policy = __isns_policy_alloc(name, namelen); /* retrieve policy bits from object */ #if 0 __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_SOURCE_NAME, &policy->ip_source); #endif __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_ENTITY, &policy->ip_entity); __isns_db_keystore_copy_policy_string(obj, OPENISNS_TAG_POLICY_DEFAULT_DD, &policy->ip_dd_default); __isns_db_keystore_copy_policy_strings(obj, OPENISNS_TAG_POLICY_NODE_NAME, &policy->ip_node_names); if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_OBJECT_TYPE, &intval)) policy->ip_object_types = intval; if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_NODE_TYPE, &intval)) policy->ip_node_types = intval; if (isns_object_get_uint32(obj, OPENISNS_TAG_POLICY_FUNCTIONS, &intval)) policy->ip_functions = intval; return policy; } void __isns_db_keystore_change_notify(const isns_db_event_t *ev, void *handle) { isns_db_keystore_t *store = handle; isns_object_t *obj = ev->ie_object; if (isns_object_get_entity(obj) == store->sd_control) { isns_debug_auth("DB keystore: policy data was modified\n"); store->sd_base.ic_generation++; } } isns_keystore_t * isns_create_db_keystore(isns_db_t *db) { isns_db_keystore_t *store; isns_object_t *entity; isns_debug_auth("Creating DB keystore\n"); if (!(entity = isns_db_get_control(db))) { isns_error("Could not create control entity in database\n"); return NULL; } isns_debug_auth("Control entity is 0x%08x\n", entity->ie_index); store = isns_calloc(1, sizeof(*store)); store->sd_base.ic_name = "database key store"; store->sd_base.ic_find = __isns_db_keystore_find; store->sd_base.ic_get_policy = __isns_db_keystore_get_policy; store->sd_control = entity; store->sd_db = db; isns_register_callback(__isns_db_keystore_change_notify, store); return (isns_keystore_t *) store; } open-iscsi-2.0.873/utils/open-isns/db.c000066400000000000000000000537021175631155400175670ustar00rootroot00000000000000/* * iSNS object database * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include "isns.h" #include "objects.h" #include "db.h" #include "util.h" enum { IDT_INSERT, IDT_REMOVE, IDT_UPDATE }; struct isns_db_trans { struct isns_db_trans * idt_next; int idt_action; isns_object_t * idt_object; }; /* Internal helpers */ static int isns_db_sanity_check(isns_db_t *); static int isns_db_get_key_tags(const isns_attr_list_t *, uint32_t *, unsigned int); static int isns_db_keyed_compare(const isns_object_t *, const isns_attr_list_t *, const uint32_t *, unsigned int); /* * Open a database */ static isns_db_t * isns_db_create(isns_db_backend_t *backend) { isns_db_t *db; db = isns_calloc(1, sizeof(*db)); db->id_last_index = 1; db->id_last_eid = 1; db->id_backend = backend; db->id_global_scope = isns_scope_alloc(db); db->id_relations = isns_relation_soup_alloc(); db->id_objects = &db->__id_objects; if (backend && backend->idb_reload) { int status; status = backend->idb_reload(db); /* "No such entry" is returned when the DB * is still empty. */ if (status != ISNS_SUCCESS && status != ISNS_NO_SUCH_ENTRY) { isns_error("Error loading database: %s\n", isns_strerror(status)); /* FIXME: isns_db_free(db); */ return NULL; } isns_db_sanity_check(db); } return db; } isns_db_t * isns_db_open(const char *location) { isns_db_backend_t *backend; if (location == NULL) { isns_debug_state("Using in-memory DB\n"); return isns_db_create(NULL); } if (location[0] == '/') { backend = isns_create_file_db_backend(location); } else if (!strncmp(location, "file:", 5)) { backend = isns_create_file_db_backend(location + 5); } else { isns_error("Unsupported database type \"%s\"\n", location); return NULL; } return isns_db_create(backend); } isns_db_t * isns_db_open_shadow(isns_object_list_t *list) { isns_db_t *db; if ((db = isns_db_create(NULL)) != NULL) db->id_objects = list; return db; } int isns_db_sanity_check(isns_db_t *db) { unsigned int i; i = 0; while (i < db->id_objects->iol_count) { isns_object_t *obj = db->id_objects->iol_data[i]; switch (obj->ie_state) { case ISNS_OBJECT_STATE_MATURE: /* Nothing yet. */ break; case ISNS_OBJECT_STATE_LIMBO: if (!ISNS_IS_ISCSI_NODE(obj) && !ISNS_IS_PORTAL(obj)) { isns_error("Unexpected object %u (%s) in limbo\n", obj->ie_index, obj->ie_template->iot_name); isns_db_remove(db, obj); } break; default: isns_error("Unexpected object state %d in object %u (%s)\n", obj->ie_state, obj->ie_index, obj->ie_template->iot_name); isns_db_remove(db, obj); break; } i += 1; } return 1; } isns_object_t * isns_db_lookup(isns_db_t *db, isns_object_template_t *tmpl, const isns_attr_list_t *keys) { return isns_object_list_lookup(db->id_objects, tmpl, keys); } int isns_db_gang_lookup(isns_db_t *db, isns_object_template_t *tmpl, const isns_attr_list_t *keys, isns_object_list_t *result) { return isns_object_list_gang_lookup(db->id_objects, tmpl, keys, result); } /* * Look up the storage node for the given source. */ isns_object_t * isns_db_lookup_source_node(isns_db_t *db, const isns_source_t *source) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_object_t *node; isns_attr_list_append_attr(&attrs, isns_source_attr(source)); node = isns_db_lookup(db, NULL, &attrs); isns_attr_list_destroy(&attrs); return node; } isns_object_t * isns_db_vlookup(isns_db_t *db, isns_object_template_t *tmpl, ...) { isns_attr_list_t keys = ISNS_ATTR_LIST_INIT; isns_object_t *obj = NULL; va_list ap; va_start(ap, tmpl); while (1) { const isns_tag_type_t *tag_type; isns_value_t value; uint32_t tag; tag = va_arg(ap, unsigned int); if (tag == 0) break; tag_type = isns_tag_type_by_id(tag); if (tag_type == NULL) { isns_error("isns_db_vlookup: unknown tag %u\n", tag); goto out; } memset(&value, 0, sizeof(value)); value.iv_type = tag_type->it_type; switch (tag_type->it_type->it_id) { case ISNS_ATTR_TYPE_STRING: value.iv_string = va_arg(ap, char *); break; case ISNS_ATTR_TYPE_INT32: value.iv_int32 = va_arg(ap, int32_t); break; case ISNS_ATTR_TYPE_UINT32: value.iv_int32 = va_arg(ap, uint32_t); break; case ISNS_ATTR_TYPE_IPADDR: value.iv_ipaddr = *va_arg(ap, struct in6_addr *); break; default: isns_error("isns_db_vlookup: unsupported tag type %s\n", value.iv_type->it_name); goto out; } isns_attr_list_append_value(&keys, tag, tag_type, &value); } obj = isns_db_lookup(db, tmpl, &keys); out: isns_attr_list_destroy(&keys); va_end(ap); return obj; } /* * Find the next matching object * * This implementation could be a lot simpler if the * RFC didn't make things so awfully complicated. * It could simply have mandated the use of the object * index attribute, period. */ isns_object_t * __isns_db_get_next(const isns_object_list_t *list, isns_object_template_t *tmpl, const isns_attr_list_t *current, const isns_attr_list_t *scope) { isns_object_t *next = NULL; uint32_t tags[16]; unsigned int i; int num_tags; if (!tmpl) return NULL; /* Get the search attribute tags, and sort them. * Note, these don't have to be the standard key * attributes for a given object type; the RFC * also permits index attributes. */ num_tags = isns_db_get_key_tags(current, tags, 16); if (num_tags < 0) return NULL; /* * 5.6.5.3. * If the TLV length of the Message Key Attribute(s) is zero, * then the first object entry in the iSNS database matching the * Message Key type SHALL be returned in the Message Key of the * corresponding DevGetNextRsp message. */ for (i = 0; i < current->ial_count; ++i) { isns_attr_t *attr = current->ial_data[i]; if (!ISNS_ATTR_IS_NIL(attr)) goto non_nil; } current = NULL; non_nil: for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template != tmpl) continue; if (scope && !isns_object_match(obj, scope)) continue; /* compare returns -1 if the first list * is "before" the second list, in terms of * implicit ordering. */ if (current && isns_db_keyed_compare(obj, current, tags, num_tags) <= 0) { /* obj less than or equal to current */ continue; } if (next == NULL || isns_db_keyed_compare(obj, &next->ie_attrs, tags, num_tags) < 0) next = obj; } if (next) isns_object_get(next); return next; } isns_object_t * isns_db_get_next(isns_db_t *db, isns_object_template_t *tmpl, const isns_attr_list_t *current, const isns_attr_list_t *scope, const isns_source_t *source) { return __isns_db_get_next(db->id_objects, tmpl, current, scope); } /* * Get the search key tags */ static int isns_db_get_key_tags(const isns_attr_list_t *keys, uint32_t *tags, unsigned int max_tags) { unsigned int i; /* Get the search attribute tags, and sort them */ for (i = 0; i < keys->ial_count; ++i) { if (i >= 16) return -1; tags[i] = keys->ial_data[i]->ia_tag_id; } /* FIXME: qsort the list */ return i; } /* * Helper function for GetNext */ static int isns_db_keyed_compare(const isns_object_t *obj, const isns_attr_list_t *attrs, const uint32_t *tags, unsigned int num_tags) { int ind = 0; unsigned int i; for (i = 0; i < num_tags; ++i) { isns_attr_t *attr1, *attr2; uint32_t tag = tags[i]; if (!isns_attr_list_get_attr(&obj->ie_attrs, tag, &attr1)) attr1 = NULL; if (!isns_attr_list_get_attr(attrs, tag, &attr2)) attr2 = NULL; if (attr1 == attr2) { ind = 0; } else if (attr1 && attr2) { ind = isns_attr_compare(attr1, attr2); } else if (attr1 == NULL) { ind = -1; } else { ind = 1; } if (ind) break; } return ind; } uint32_t isns_db_allocate_index(isns_db_t *db) { return db->id_last_index++; } /* * Insert an object into the database. */ void __isns_db_insert(isns_db_t *db, isns_object_t *obj, unsigned int state) { uint32_t idx_tag = obj->ie_template->iot_index; switch (obj->ie_state) { case ISNS_OBJECT_STATE_LIMBO: /* The object was in limbo; now it goes * live (again). It should have an index, * and it should be on the global id_objects * list too. */ isns_assert(state == ISNS_OBJECT_STATE_MATURE); isns_assert(obj->ie_index); isns_assert(obj->ie_users > 1); isns_object_list_remove(&db->id_limbo, obj); break; case ISNS_OBJECT_STATE_DEAD: /* A DevAttrReg with the F_REPLACE bit set will cause * the key object to be removed from the DB, which may * kill it for good. * The subsequent call to db_insert will assign a new * index, and re-add it to the database. */ case ISNS_OBJECT_STATE_LARVAL: /* Larval objects can go either to mature or * limbo state. */ obj->ie_index = db->id_last_index++; if (idx_tag) isns_object_set_uint32(obj, idx_tag, obj->ie_index); isns_object_list_append(db->id_objects, obj); break; case ISNS_OBJECT_STATE_MATURE: /* If we call db_insert on a mature object, treat this as a NOP. */ isns_assert(state == ISNS_OBJECT_STATE_MATURE); return; default: isns_error("Internal error: unexpected object %u (%s) " "state %u in db_insert\n", obj->ie_index, obj->ie_template->iot_name, obj->ie_state); return; } obj->ie_state = state; /* Add it to the global scope */ if (state == ISNS_OBJECT_STATE_MATURE) { isns_scope_add(db->id_global_scope, obj); obj->ie_references++; /* See if this object represents a relationship * (eg a portal group). */ if (obj->ie_template->iot_relation_type) { if (!obj->ie_relation) { isns_warning("DB: inserting %s object " "without relation\n", obj->ie_template->iot_name); } else { isns_relation_add(db->id_relations, obj->ie_relation); } } isns_mark_object(obj, ISNS_SCN_OBJECT_ADDED); } isns_debug_state("DB: added object %u (%s) state %u\n", obj->ie_index, obj->ie_template->iot_name, obj->ie_state); if (db->id_backend) { db->id_backend->idb_store(db, obj); db->id_backend->idb_sync(db); } } void isns_db_insert(isns_db_t *db, isns_object_t *obj) { __isns_db_insert(db, obj, ISNS_OBJECT_STATE_MATURE); } void isns_db_insert_limbo(isns_db_t *db, isns_object_t *obj) { isns_assert(obj->ie_state == ISNS_OBJECT_STATE_LARVAL); __isns_db_insert(db, obj, ISNS_OBJECT_STATE_LIMBO); } /* * Save an object after updating it */ void isns_db_sync(isns_db_t *db) { isns_object_list_t *list = db->id_objects; unsigned int i, saved = 0; if (!db->id_backend) return; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_flags & ISNS_OBJECT_DIRTY) { db->id_backend->idb_store(db, obj); obj->ie_flags &= ~ISNS_OBJECT_DIRTY; saved++; } } if (saved) db->id_backend->idb_sync(db); } /* * Remove an object from the database. * This is slow and inefficient, due to the use * of an object array. We should at least use * a linked list, or maybe even a hash one day. */ static void __isns_db_prepare_removal(isns_db_t *db, isns_object_t *obj) { isns_object_t *child; obj->ie_flags |= ISNS_OBJECT_DEAD; isns_object_get(obj); /* The node is dead; it's no longer interested in SCNs */ obj->ie_scn_mask = 0; /* Trigger an SCN event. */ if (obj->ie_state == ISNS_OBJECT_STATE_MATURE) isns_mark_object(obj, ISNS_SCN_OBJECT_REMOVED); /* If the object represents a relation between * two other objects, sever that relationship. */ if (obj->ie_relation) { isns_relation_remove(db->id_relations, obj->ie_relation); isns_relation_sever(obj->ie_relation); isns_relation_release(obj->ie_relation); obj->ie_relation = NULL; } /* Detach the object from its container */ isns_object_detach(obj); /* Remove it from the database */ if (isns_scope_remove(db->id_global_scope, obj)) { obj->ie_references--; } else { isns_warning("Unable to remove object from scope\n"); } /* Recursively remove all children */ while (obj->ie_children.iol_count) { child = obj->ie_children.iol_data[0]; __isns_db_prepare_removal(db, child); } isns_debug_state("DB: removed object %u (%s)\n", obj->ie_index, obj->ie_template->iot_name); isns_object_list_append(&db->id_deferred, obj); isns_object_release(obj); } int isns_db_remove(isns_db_t *db, isns_object_t *obj) { isns_object_t *entity; unsigned int i; /* Don't even bother if the object was never added */ if (obj->ie_index == 0) goto out; /* Obtain the containing entity before removal */ entity = isns_object_get_entity(obj); /* We don't remove the object for real yet; * this will happen later during db_purge */ __isns_db_prepare_removal(db, obj); /* * 5.6.5.4. * If all Nodes and Portals associated with a Network Entity are * deregistered, then the Network Entity SHALL also be removed. * * If both the Portal and iSCSI Storage Node objects associated * with a Portal Group object are removed, then that Portal Group * object SHALL also be removed. The Portal Group object SHALL * remain registered as long as either of its associated Portal * or iSCSI Storage Node objects remain registered. If a deleted * Storage Node or Portal object is subsequently re-registered, * then a relationship between the re- registered object and * an existing Portal or Storage Node object registration, * indicated by the PG object, SHALL be restored. */ if (ISNS_IS_ENTITY(obj)) goto out; if (entity == NULL || !ISNS_IS_ENTITY(entity)) goto out; /* Don't do this for the CONTROL entity. */ if (entity->ie_flags & ISNS_OBJECT_PRIVATE) goto out; /* Step 1: Purge all relationship objects (read: portal groups) * where both referenced objects are dead. */ for (i = 0; i < entity->ie_children.iol_count; ) { isns_object_t *child = entity->ie_children.iol_data[i]; if (child->ie_relation && isns_relation_is_dead(child->ie_relation)) { __isns_db_prepare_removal(db, child); continue; } i += 1; } /* Step 2: If all portals, nodes and PGs have been unregistered, * the list of children should be empty. */ if (entity->ie_children.iol_count == 0) { isns_debug_state("Last portal/node unregistered, removing entity\n"); __isns_db_prepare_removal(db, entity); } out: return ISNS_SUCCESS; } /* * Purge deregistered objects. * If we find they're still part of some discovery * domain, they're moved to id_limbo; otherwise we'll * destroy them for good. */ void isns_db_purge(isns_db_t *db) { isns_object_list_t *list = &db->id_deferred; unsigned int i; while (list->iol_count) { isns_object_t *obj = list->iol_data[0]; if (obj->ie_references == 0) { isns_debug_state("DB: destroying object %u (%s)\n", obj->ie_index, obj->ie_template->iot_name); if (db->id_backend) { db->id_backend->idb_remove(db, obj); /* db->id_backend->idb_sync(db); */ } isns_object_list_remove(db->id_objects, obj); obj->ie_state = ISNS_OBJECT_STATE_DEAD; } else if (obj->ie_state != ISNS_OBJECT_STATE_LIMBO) { isns_debug_state("DB: moving object %u (%s) to purgatory - " "%u references left\n", obj->ie_index, obj->ie_template->iot_name, obj->ie_references); isns_object_list_append(&db->id_limbo, obj); obj->ie_state = ISNS_OBJECT_STATE_LIMBO; isns_object_prune_attrs(obj); if (db->id_backend) { db->id_backend->idb_store(db, obj); db->id_backend->idb_sync(db); } } isns_object_list_remove(list, obj); } /* Brute force - look at all objects in limbo and kill those * that went out of scope */ for (i = 0; i < db->id_limbo.iol_count; ) { isns_object_t *obj = db->id_limbo.iol_data[i]; if (obj->ie_references == 0) { isns_debug_state("DB: destroying object %u (%s)\n", obj->ie_index, obj->ie_template->iot_name); if (db->id_backend) { db->id_backend->idb_remove(db, obj); /* db->id_backend->idb_sync(db); */ } obj->ie_state = ISNS_OBJECT_STATE_DEAD; isns_object_list_remove(&db->id_limbo, obj); isns_object_list_remove(db->id_objects, obj); continue; } i += 1; } } /* * Expire old entities * * This code is still rather simple, but once we start * using ESI things get rather complex quickly. */ time_t isns_db_expire(isns_db_t *db) { isns_object_list_t *list = db->id_objects; time_t now = time(NULL), next_timeout; unsigned int i = 0; next_timeout = now + 3600; if (isns_config.ic_registration_period == 0) return next_timeout; while (i < list->iol_count) { isns_object_t *obj; uint64_t stamp; uint32_t period; obj = list->iol_data[i]; if (!ISNS_IS_ENTITY(obj)) goto next; if (!isns_object_get_uint32(obj, ISNS_TAG_REGISTRATION_PERIOD, &period)) { isns_debug_state("No registration period for entity %u\n", obj->ie_index); goto next; } if (!isns_object_get_uint64(obj, ISNS_TAG_TIMESTAMP, &stamp)) { isns_debug_state("No timestamp for entity %u\n", obj->ie_index); goto next; } stamp += period; if (stamp <= now) { /* removing the object will move one * object from the tail to the free * slot in the list. So don't increment * the index here. */ isns_debug_state("Expiring entity %u\n", obj->ie_index); isns_db_remove(db, obj); goto next; } else { isns_debug_state("Entity %u will expire in %u sec\n", obj->ie_index, (int) (stamp - now)); if (stamp < next_timeout) next_timeout = stamp; } next: i += 1; } /* Send out SCN notifications. * This makes sure we won't have extraneous references * on expired objects when we reach db_purge. */ isns_flush_events(); return next_timeout; } /* * Very special function to make sure we always have a * CONTROL entity. */ isns_object_t * isns_db_get_control(isns_db_t *db) { isns_attr_list_t keys = ISNS_ATTR_LIST_INIT; isns_object_list_t *list = db->id_objects; isns_object_t *found = NULL; unsigned int i; isns_attr_list_append_string(&keys, ISNS_TAG_ENTITY_IDENTIFIER, ISNS_ENTITY_CONTROL); for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj; obj = list->iol_data[i]; if (!ISNS_IS_ENTITY(obj)) continue; if (isns_object_match(obj, &keys)) { obj->ie_users++; found = obj; goto done; } } found = isns_create_object(&isns_entity_template, &keys, NULL); found->ie_flags |= ISNS_OBJECT_PRIVATE; isns_db_insert(db, found); isns_db_sync(db); done: return found; } void isns_db_get_domainless(isns_db_t *db, isns_object_template_t *tmpl, isns_object_list_t *result) { isns_object_list_t *list = db->id_objects; unsigned int i; if (!tmpl) return; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template == tmpl && isns_bitvector_is_empty(obj->ie_membership)) isns_object_list_append(result, obj); } } /* * Create a relationship and store it in the DB */ void isns_db_create_relation(isns_db_t *db, isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2) { isns_relation_t *rel; rel = isns_create_relation(relating_object, relation_type, subordinate_object1, subordinate_object2); if (rel) { isns_relation_add(db->id_relations, rel); isns_relation_release(rel); } } /* * Get all objects related to @left through a relation * of type @type. */ void isns_db_get_relationship_objects(isns_db_t *db, const isns_object_t *left, unsigned int relation_type, isns_object_list_t *result) { isns_relation_get_edge_objects(db->id_relations, left, relation_type, result); } /* * Get the object relating left and right. * Usually called to find the portal group connecting * a portal and a storage node, or a DD connecting * two storage nodes. */ isns_object_t * isns_db_get_relationship_object(isns_db_t *db, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type) { isns_relation_t *rel; /* Find a relation of the given type, connecting * the two objects. */ rel = isns_relation_find_edge(db->id_relations, left, right, relation_type); if (rel == NULL) return NULL; return isns_object_get(rel->ir_object); } /* * See if a relationship exists */ int isns_db_relation_exists(isns_db_t *db, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type) { return isns_relation_exists(db->id_relations, relating_object, left, right, relation_type); } /* * Debug helper */ void isns_db_print(isns_db_t *db, isns_print_fn_t *fn) { const isns_object_list_t *list = db->id_objects; unsigned int i; fn("Dumping database contents\n" "Backend: %s\n" "Last EID: %u\n" "Last Index: %u\n" , db->id_backend->idb_name, db->id_last_eid, db->id_last_index); for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; fn("--------------\n" "Object: index=%u type=<%s> state=%s", obj->ie_index, obj->ie_template->iot_name, isns_object_state_string(obj->ie_state)); if (obj->ie_container) fn(" parent=%u", obj->ie_container->ie_index); if (obj->ie_flags & ISNS_OBJECT_DIRTY) fn(" DIRTY"); if (obj->ie_flags & ISNS_OBJECT_PRIVATE) fn(" PRIVATE"); fn("\n"); isns_attr_list_print(&obj->ie_attrs, fn); } } /* * Generate a "random" entity identifier. This is used when * a DevAttrReg request does not specify an entity, and the * client's policy doesn't specify one either. */ const char * isns_db_generate_eid(isns_db_t *db, char *buf, size_t size) { snprintf(buf, size, "isns.entity.%04d", db->id_last_eid); db->id_last_eid++; return buf; } /* * Highly primitive transaction handling. * This is really just a hack for the iSNS server code, * which wants to go along creating objects, and back out * if something goes wrong. */ void isns_db_begin_transaction(isns_db_t *db) { if (db->id_in_transaction) { isns_error("isns_db_begin_transaction: running into pending transaction\n"); isns_db_rollback(db); } db->id_in_transaction = 1; } void isns_db_commit(isns_db_t *db) { /* Nothing yet */ db->id_in_transaction = 0; } void isns_db_rollback(isns_db_t *db) { /* Nothing yet */ db->id_in_transaction = 0; } open-iscsi-2.0.873/utils/open-isns/db.h000066400000000000000000000110431175631155400175640ustar00rootroot00000000000000/* * iSNS object database * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_DB_H #define ISNS_DB_H #include "attrs.h" typedef struct isns_db_backend isns_db_backend_t; /* * In-memory portion of object database. * Stable storage is provided by different * backends. */ struct isns_db { isns_object_list_t * id_objects; isns_object_list_t __id_objects; isns_relation_soup_t * id_relations; uint32_t id_last_eid; uint32_t id_last_index; isns_scope_t * id_global_scope; isns_scope_t * id_default_scope; isns_db_backend_t * id_backend; unsigned int id_in_transaction : 1; struct isns_db_trans * id_transact; /* This is for objects in limbo. When a client * calls DevAttrDereg, the object will first be * placed on the id_deferred list. * When we're done processing the message, we * invoke isns_db_purge, which looks at these * objects. * - if the reference count is 1, the object * is deleted. * - otherwise, we assume the object is referenced * by a discovery domain. In this case, we prune * the attribute list down to the key attr(s) * plus the index attribute, and move it to * the id_limbo list. */ isns_object_list_t id_deferred; isns_object_list_t id_limbo; }; struct isns_db_backend { char * idb_name; int (*idb_reload)(isns_db_t *); int (*idb_sync)(isns_db_t *); int (*idb_store)(isns_db_t *, const isns_object_t *); int (*idb_remove)(isns_db_t *, const isns_object_t *); }; extern isns_db_backend_t *isns_create_file_db_backend(const char *); extern isns_object_t * __isns_db_get_next(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *, const isns_attr_list_t *); extern isns_relation_soup_t *isns_relation_soup_alloc(void); extern isns_relation_t *isns_create_relation(isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2); extern void isns_relation_sever(isns_relation_t *); extern void isns_relation_release(isns_relation_t *); extern void isns_relation_add(isns_relation_soup_t *, isns_relation_t *); extern void isns_relation_remove(isns_relation_soup_t *, isns_relation_t *); extern isns_object_t * isns_relation_get_other(const isns_relation_t *, const isns_object_t *); extern isns_relation_t *isns_relation_find_edge(isns_relation_soup_t *, const isns_object_t *, const isns_object_t *, unsigned int); extern void isns_relation_halfspace(isns_relation_soup_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern void isns_relation_get_edge_objects(isns_relation_soup_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern int isns_relation_exists(isns_relation_soup_t *, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type); extern int isns_relation_is_dead(const isns_relation_t *); extern void isns_db_create_relation(isns_db_t *db, isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2); extern void isns_db_get_relationship_objects(isns_db_t *, const isns_object_t *, unsigned int relation_type, isns_object_list_t *); extern isns_object_t * isns_db_get_relationship_object(isns_db_t *, const isns_object_t *, const isns_object_t *, unsigned int relation_type); extern int isns_db_relation_exists(isns_db_t *db, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type); extern int isns_db_create_pg_relation(isns_db_t *, isns_object_t *); extern isns_scope_t * isns_scope_for_call(isns_db_t *, const isns_simple_t *); extern isns_scope_t * isns_scope_alloc(isns_db_t *); extern void isns_scope_release(isns_scope_t *); extern void isns_scope_add(isns_scope_t *, isns_object_t *); extern int isns_scope_remove(isns_scope_t *, isns_object_t *); extern int isns_scope_gang_lookup(isns_scope_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern isns_object_t * isns_scope_get_next(isns_scope_t *, isns_object_template_t *, const isns_attr_list_t *current, const isns_attr_list_t *scope); extern void isns_scope_get_related(isns_scope_t *, const isns_object_t *, unsigned int, isns_object_list_t *); extern isns_db_t * isns_scope_get_db(const isns_scope_t *); #endif /* ISNS_DB_H */ open-iscsi-2.0.873/utils/open-isns/dd.c000066400000000000000000000770401175631155400175720ustar00rootroot00000000000000/* * Handle DD registration/deregistration * * Discovery domains are weird, even in the context of * iSNS. For once thing, all other objects have unique * attributes; DDs attributes can appear several times. * They should really have made each DD member an object * in its own right. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" #define DD_DEBUG enum { ISNS_DD_MEMBER_ISCSI_NODE = 1, ISNS_DD_MEMBER_IFCP_NODE, ISNS_DD_MEMBER_PORTAL, }; /* Must be zero/one: */ enum { NOTIFY_MEMBER_ADDED = 0, NOTIFY_MEMBER_REMOVED = 1 }; typedef struct isns_dd isns_dd_t; typedef struct isns_dd_list isns_dd_list_t; typedef struct isns_dd_member isns_dd_member_t; struct isns_dd { uint32_t dd_id; char * dd_name; uint32_t dd_features; isns_dd_member_t * dd_members; unsigned int dd_inserted : 1; isns_object_t * dd_object; }; struct isns_dd_member { isns_dd_member_t * ddm_next; unsigned int ddm_type; isns_object_ref_t ddm_object; unsigned int ddm_added : 1; union { uint32_t ddm_index; /* Index must be first in all structs below. * Yeah, I know. Aliasing is bad. */ struct isns_dd_portal { uint32_t index; isns_portal_info_t info; } ddm_portal; struct isns_dd_iscsi_node { uint32_t index; char * name; } ddm_iscsi_node; struct isns_dd_ifcp_node { uint32_t index; char * name; } ddm_ifcp_node; }; }; struct isns_dd_list { unsigned int ddl_count; isns_dd_t ** ddl_data; }; /* * List of all discovery domains. * This duplicates the DD information from the database, * but unfortunately this can't be helped - we need to * have fast algorithms to compute the membership of a * node, and the relative visibility of two nodes. */ static int isns_dd_list_initialized = 0; static isns_dd_list_t isns_dd_list; static uint32_t isns_dd_next_id = 1; static isns_dd_t * isns_dd_alloc(void); static isns_dd_t * isns_dd_clone(const isns_dd_t *); static void isns_dd_release(isns_dd_t *); static int isns_dd_parse_attrs(isns_dd_t *, isns_db_t *, const isns_attr_list_t *, const isns_dd_t *, int); static int isns_dd_remove_members(isns_dd_t *, isns_db_t *, isns_dd_t *); static void isns_dd_notify(const isns_dd_t *, isns_dd_member_t *, isns_dd_member_t *, int); static void isns_dd_add_members(isns_dd_t *, isns_db_t *, isns_dd_t *); static void isns_dd_store(isns_db_t *, const isns_dd_t *, int); static void isns_dd_destroy(isns_db_t *, isns_dd_t *); static void isns_dd_insert(isns_dd_t *); static isns_dd_t * isns_dd_by_id(uint32_t); static isns_dd_t * isns_dd_by_name(const char *); static isns_dd_member_t * isns_dd_create_member(isns_object_t *); static inline void isns_dd_member_free(isns_dd_member_t *); static int isns_dd_remove_member(isns_dd_t *, isns_object_t *); static void isns_dd_list_resize(isns_dd_list_t *, unsigned int); static void isns_dd_list_insert(isns_dd_list_t *, isns_dd_t *); static void isns_dd_list_remove(isns_dd_list_t *, isns_dd_t *); static isns_object_t * isns_dd_get_member_object(isns_db_t *, const isns_attr_t *, const isns_attr_t *, int); /* * Create DDReg messages */ isns_simple_t * isns_create_dd_registration(isns_client_t *clnt, const isns_attr_list_t *attrs) { isns_simple_t *msg; isns_attr_t *id_attr; msg = isns_simple_create(ISNS_DD_REGISTER, clnt->ic_source, NULL); if (msg == NULL) return NULL; /* If the caller specified a DD_ID, use it in the * message key. */ if (isns_attr_list_get_attr(attrs, ISNS_TAG_DD_ID, &id_attr)) isns_attr_list_append_attr(&msg->is_message_attrs, id_attr); isns_attr_list_copy(&msg->is_operating_attrs, attrs); return msg; } isns_simple_t * isns_create_dd_deregistration(isns_client_t *clnt, uint32_t dd_id, const isns_attr_list_t *attrs) { isns_simple_t *msg; msg = isns_simple_create(ISNS_DD_DEREGISTER, clnt->ic_source, NULL); if (msg == NULL) return NULL; isns_attr_list_append_uint32(&msg->is_message_attrs, ISNS_TAG_DD_ID, dd_id); isns_attr_list_copy(&msg->is_operating_attrs, attrs); return msg; } /* * Process a DD registration */ int isns_process_dd_registration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_attr_t *attr; uint32_t id = 0; int status; /* * 5.6.5.9. * The Message Key, if used, contains the DD_ID of the Discovery * Domain to be registered. If the Message Key contains a DD_ID * of an existing DD entry in the iSNS database, then the DDReg * message SHALL attempt to update the existing entry. If the * DD_ID in the Message Key (if used) does not match an existing * DD entry, then the iSNS server SHALL reject the DDReg message * with a status code of 3 (Invalid Registration). */ switch (keys->ial_count) { case 0: /* Security: check if the client is allowed to * create a discovery domain */ if (!isns_policy_validate_object_creation(call->is_policy, call->is_source, &isns_dd_template, keys, attrs, call->is_function)) goto unauthorized; break; case 1: attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_DD_ID) goto reject; if (ISNS_ATTR_IS_NIL(attr)) break; if (!ISNS_ATTR_IS_UINT32(attr)) goto reject; id = attr->ia_value.iv_uint32; if (id == 0) goto reject; dd = isns_dd_by_id(id); if (dd == NULL) { isns_debug_state("DDReg for unknown ID=%u\n", id); goto reject; } /* Security: check if the client is allowed to * mess with this DD. */ isns_assert(dd->dd_object); if (!isns_policy_validate_object_update(call->is_policy, call->is_source, dd->dd_object, attrs, call->is_function)) goto unauthorized; break; default: goto reject; } temp_dd = isns_dd_alloc(); /* Parse the attributes and build a DD object. */ status = isns_dd_parse_attrs(temp_dd, db, attrs, dd, 1); if (status != ISNS_SUCCESS) goto out; if (dd == NULL) { /* Create the DD, and copy the general information * such asn features and symbolic name from temp_dd */ dd = isns_dd_clone(temp_dd); /* Don't assign the attrs to the DD right away. * First and foremost, they may be unsorted. Second, * we really want to hand-pick through them due to * the weird semantics mandated by the RFC. */ dd->dd_object = isns_create_object(&isns_dd_template, NULL, NULL); if (dd->dd_object == NULL) goto reject; /* Insert new domain into database */ isns_db_insert(db, dd->dd_object); /* Add it to the internal list. Assign DD_ID and * symbolic name if none were given. */ isns_dd_insert(dd); } else { if (!dd->dd_id) dd->dd_id = temp_dd->dd_id; dd->dd_features = temp_dd->dd_features; isns_assign_string(&dd->dd_name, temp_dd->dd_name); } /* Send notifications. This must be done before merging * the list of new members into the DD. */ isns_dd_notify(dd, dd->dd_members, temp_dd->dd_members, NOTIFY_MEMBER_ADDED); /* Update the DD */ isns_dd_add_members(dd, db, temp_dd); /* And add it to the database. */ isns_dd_store(db, dd, 0); reply = isns_simple_create(ISNS_DD_REGISTER, srv->is_source, NULL); isns_object_extract_all(dd->dd_object, &reply->is_operating_attrs); status = ISNS_SUCCESS; out: isns_dd_release(temp_dd); isns_dd_release(dd); *result = reply; return status; reject: status = ISNS_INVALID_REGISTRATION; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Process a DD deregistration */ int isns_process_dd_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_attr_t *attr; uint32_t id = 0; int status; /* * 5.6.5.10. * The Message Key Attribute for a DDDereg message is the DD * ID for the Discovery Domain being removed or having members * removed. */ if (keys->ial_count != 1) goto reject; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_DD_ID || ISNS_ATTR_IS_NIL(attr) || !ISNS_ATTR_IS_UINT32(attr)) goto reject; id = attr->ia_value.iv_uint32; if (id == 0) goto reject; dd = isns_dd_by_id(id); if (dd == NULL) goto reject; /* Security: check if the client is permitted to * modify the DD object. */ if (!isns_policy_validate_object_update(call->is_policy, call->is_source, dd->dd_object, attrs, call->is_function)) goto unauthorized; /* * 5.6.5.10. * If the DD ID matches an existing DD and there are * no Operating Attributes, then the DD SHALL be removed and a * success Status Code returned. Any existing members of that * DD SHALL remain in the iSNS database without membership in * the just-removed DD. */ if (attrs->ial_count == 0) { isns_dd_member_t *mp; /* Zap the membership bit */ for (mp = dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; isns_object_clear_membership(obj, dd->dd_id); } /* Notify all DD members that they will lose the other * nodes. */ isns_dd_notify(dd, NULL, dd->dd_members, NOTIFY_MEMBER_REMOVED); isns_dd_destroy(db, dd); } else { /* Parse the attributes and build a temporary DD object. */ temp_dd = isns_dd_alloc(); status = isns_dd_parse_attrs(temp_dd, db, attrs, dd, 0); if (status != ISNS_SUCCESS) goto out; /* Update the DD object */ status = isns_dd_remove_members(dd, db, temp_dd); if (status != ISNS_SUCCESS) goto out; /* Send notifications. This must be done before after * updating the DD. */ isns_dd_notify(dd, dd->dd_members, temp_dd->dd_members, NOTIFY_MEMBER_REMOVED); /* Store it in the database. */ isns_dd_store(db, dd, 1); } reply = isns_simple_create(ISNS_DD_DEREGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: isns_dd_release(temp_dd); isns_dd_release(dd); *result = reply; return status; reject: status = ISNS_INVALID_DEREGISTRATION; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } static isns_dd_t * isns_dd_alloc(void) { return isns_calloc(1, sizeof(isns_dd_t)); } /* * Allocate a clone of the orig_dd, but without * copying the members. */ static isns_dd_t * isns_dd_clone(const isns_dd_t *orig_dd) { isns_dd_t *dd; dd = isns_dd_alloc(); dd->dd_id = orig_dd->dd_id; dd->dd_features = orig_dd->dd_features; dd->dd_object = isns_object_get(orig_dd->dd_object); isns_assign_string(&dd->dd_name, orig_dd->dd_name); return dd; } static void isns_dd_release(isns_dd_t *dd) { isns_dd_member_t *member; if (dd == NULL || dd->dd_inserted) return; while ((member = dd->dd_members) != NULL) { dd->dd_members = member->ddm_next; isns_dd_member_free(member); } if (dd->dd_object) isns_object_release(dd->dd_object); isns_free(dd->dd_name); isns_free(dd); } static isns_dd_member_t * isns_dd_create_member(isns_object_t *obj) { isns_dd_member_t *new; new = isns_calloc(1, sizeof(*new)); new->ddm_added = 1; if (ISNS_IS_ISCSI_NODE(obj)) new->ddm_type = ISNS_DD_MEMBER_ISCSI_NODE; else if (ISNS_IS_PORTAL(obj)) new->ddm_type = ISNS_DD_MEMBER_PORTAL; else if (ISNS_IS_FC_NODE(obj)) new->ddm_type = ISNS_DD_MEMBER_IFCP_NODE; else { isns_free(new); return NULL; } isns_object_reference_set(&new->ddm_object, obj); return new; } static inline void isns_dd_member_free(isns_dd_member_t *member) { switch (member->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: isns_free(member->ddm_iscsi_node.name); break; case ISNS_DD_MEMBER_IFCP_NODE: isns_free(member->ddm_ifcp_node.name); break; } isns_object_reference_drop(&member->ddm_object); isns_free(member); } void isns_dd_get_members(uint32_t dd_id, isns_object_list_t *list, int active_only) { isns_dd_t *dd; isns_dd_member_t *mp; dd = isns_dd_by_id(dd_id); if (dd == NULL) return; for (mp = dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; if (active_only && obj->ie_state != ISNS_OBJECT_STATE_MATURE) continue; isns_object_list_append(list, obj); } } /* * Helper function to remove a member referencing the given object */ static int isns_dd_remove_member(isns_dd_t *dd, isns_object_t *obj) { isns_dd_member_t *mp, **pos; pos = &dd->dd_members; while ((mp = *pos) != NULL) { if (mp->ddm_object.obj == obj) { *pos = mp->ddm_next; isns_dd_member_free(mp); return 1; } else { pos = &mp->ddm_next; } } return 0; } static void isns_dd_insert(isns_dd_t *dd) { if (dd->dd_inserted) return; if (dd->dd_id == 0) { uint32_t id = isns_dd_next_id; unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *cur = isns_dd_list.ddl_data[i]; if (cur->dd_id > id) break; if (cur->dd_id == id) ++id; } isns_debug_state("Allocated new DD_ID %d\n", id); dd->dd_id = id; isns_dd_next_id = id + 1; } /* * When creating a new DD, if the DD_Symbolic_Name is * not included in the Operating Attributes, or if it * is included with a zero-length TLV, then the iSNS * server SHALL provide a unique DD_Symbolic_Name value * for the created DD. The assigned DD_Symbolic_Name * value SHALL be returned in the DDRegRsp message. */ if (dd->dd_name == NULL) { char namebuf[64]; snprintf(namebuf, sizeof(namebuf), "isns.dd%u", dd->dd_id); isns_assign_string(&dd->dd_name, namebuf); } isns_dd_list_insert(&isns_dd_list, dd); dd->dd_inserted = 1; #ifdef DD_DEBUG /* Safety first - make sure domains are sorted by DD_ID */ { unsigned int i, prev_id = 0; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *cur = isns_dd_list.ddl_data[i]; isns_assert(cur->dd_id > prev_id); prev_id = cur->dd_id; } } #endif } /* * Resize the DD list */ #define LIST_SIZE(n) (((n) + 15) & ~15) void isns_dd_list_resize(isns_dd_list_t *list, unsigned int last_index) { unsigned int new_size, cur_size; isns_dd_t **new_data; cur_size = LIST_SIZE(list->ddl_count); new_size = LIST_SIZE(last_index + 1); if (new_size < list->ddl_count) return; /* We don't use realloc here because we need * to zero the new pointers anyway. */ new_data = isns_calloc(new_size, sizeof(void *)); isns_assert(new_data); memcpy(new_data, list->ddl_data, list->ddl_count * sizeof(void *)); isns_free(list->ddl_data); list->ddl_data = new_data; list->ddl_count = last_index + 1; } /* * Find the insert position for a given DD ID. * returns true iff the DD was found in the list. */ static int __isns_dd_list_find_pos(isns_dd_list_t *list, unsigned int id, unsigned int *where) { unsigned int hi, lo, md; lo = 0; hi = list->ddl_count; /* binary search */ while (lo < hi) { isns_dd_t *cur; md = (lo + hi) / 2; cur = list->ddl_data[md]; if (id == cur->dd_id) { *where = md; return 1; } if (id < cur->dd_id) { hi = md; } else { lo = md + 1; } } *where = hi; return 0; } /* * In-order insert */ static void isns_dd_list_insert(isns_dd_list_t *list, isns_dd_t *dd) { unsigned int pos; if (__isns_dd_list_find_pos(list, dd->dd_id, &pos)) { isns_error("Internal error in %s: DD already listed\n", __FUNCTION__); return; } isns_dd_list_resize(list, list->ddl_count); /* Shift the tail of the list to make room for new entry. */ memmove(list->ddl_data + pos + 1, list->ddl_data + pos, (list->ddl_count - pos - 1) * sizeof(void *)); list->ddl_data[pos] = dd; } /* * Remove DD from list */ void isns_dd_list_remove(isns_dd_list_t *list, isns_dd_t *dd) { unsigned int pos; if (!__isns_dd_list_find_pos(list, dd->dd_id, &pos)) return; /* Shift the tail of the list */ memmove(list->ddl_data + pos, list->ddl_data + pos + 1, (list->ddl_count - pos - 1) * sizeof(void *)); list->ddl_count -= 1; } isns_dd_t * isns_dd_by_id(uint32_t id) { unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *dd = isns_dd_list.ddl_data[i]; if (dd && dd->dd_id == id) return dd; } return NULL; } static isns_dd_t * isns_dd_by_name(const char *name) { unsigned int i; for (i = 0; i < isns_dd_list.ddl_count; ++i) { isns_dd_t *dd = isns_dd_list.ddl_data[i]; if (dd && !strcmp(dd->dd_name, name)) return dd; } return NULL; } /* * Validate the operating attributes, which is surprisingly * tedious for DDs. It appears as if the whole DD/DDset * stuff has been slapped onto iSNS as an afterthought. * * DDReg has some funky rules about how eg iSCSI nodes * can be identified by either name or index, and how they * relate to each other. Unfortunately, the RFC is very vague * in describing how to treat DDReg message that mix these * two types of identification, except by saying they * need to be consistent. */ static int isns_dd_parse_attrs(isns_dd_t *dd, isns_db_t *db, const isns_attr_list_t *attrs, const isns_dd_t *orig_dd, int is_registration) { isns_dd_member_t **tail; const isns_dd_t *conflict; unsigned int i; int rv = ISNS_SUCCESS; if (orig_dd) { dd->dd_id = orig_dd->dd_id; dd->dd_features = orig_dd->dd_features; isns_assign_string(&dd->dd_name, orig_dd->dd_name); } isns_assert(dd->dd_members == NULL); tail = &dd->dd_members; for (i = 0; i < attrs->ial_count; ++i) { isns_object_t *obj = NULL; isns_attr_t *attr, *next = NULL; const char *name; uint32_t id; attr = attrs->ial_data[i]; if (!isns_object_attr_valid(&isns_dd_template, attr->ia_tag_id)) return ISNS_INVALID_REGISTRATION; switch (attr->ia_tag_id) { case ISNS_TAG_DD_ID: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * 5.6.5.9. * A DDReg message with no Message Key SHALL result * in the attempted creation of a new Discovery Domain * (DD). If the DD_ID attribute (with non-zero length) * is included among the Operating Attributes in the * DDReg message, then the new Discovery Domain SHALL be * assigned the value contained in that DD_ID attribute. * * If the DD_ID is included in both the Message * Key and Operating Attributes, then the DD_ID * value in the Message Key MUST be the same as * the DD_ID value in the Operating Attributes. * * Implementer's note: It's not clear why the standard * makes an exception for the DD_ID, while all other * index attributes are read-only. */ if (ISNS_ATTR_IS_NIL(attr)) break; id = attr->ia_value.iv_uint32; if (dd->dd_id != 0) { if (dd->dd_id != id) goto invalid; } else if ((conflict = isns_dd_by_id(id)) != NULL) { isns_debug_state("DDReg: requested ID %d " "clashes with existing DD (%s)\n", id, conflict->dd_name); goto invalid; } dd->dd_id = id; break; case ISNS_TAG_DD_SYMBOLIC_NAME: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * If the DD_Symbolic_Name is an operating * attribute and its value is unique (i.e., it * does not match the registered DD_Symbolic_Name * for another DD), then the value SHALL be stored * in the iSNS database as the DD_Symbolic_Name * for the specified Discovery Domain. If the * value for the DD_Symbolic_Name is not unique, * then the iSNS server SHALL reject the attempted * DD registration with a status code of 3 * (Invalid Registration). */ if (ISNS_ATTR_IS_NIL(attr)) break; name = attr->ia_value.iv_string; if (dd->dd_name && strcmp(name, dd->dd_name)) { isns_debug_state("DDReg: symbolic name conflict: " "id=%d name=%s requested=%s\n", dd->dd_id, dd->dd_name, name); goto invalid; } if (dd->dd_name) break; if ((conflict = isns_dd_by_name(name)) != NULL) { isns_debug_state("DDReg: requested symbolic name (%s) " "clashes with existing DD (id=%d)\n", name, conflict->dd_id); goto invalid; } isns_assign_string(&dd->dd_name, name); break; case ISNS_TAG_DD_FEATURES: /* Ignore this attribute in DDDereg messages */ if (!is_registration) continue; /* * When creating a new DD, if the DD_Features * attribute is not included in the Operating * Attributes, then the iSNS server SHALL assign * the default value. The default value for * DD_Features is 0. */ if (ISNS_ATTR_IS_UINT32(attr)) dd->dd_features = attr->ia_value.iv_uint32; break; case ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR: /* portal address must be followed by port */ if (i + 1 >= attrs->ial_count) goto invalid; next = attrs->ial_data[i + 1]; if (next->ia_tag_id != ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT) goto invalid; i += 1; /* fallthru to normal case */ case ISNS_TAG_DD_MEMBER_PORTAL_INDEX: case ISNS_TAG_DD_MEMBER_ISCSI_INDEX: case ISNS_TAG_DD_MEMBER_ISCSI_NAME: case ISNS_TAG_DD_MEMBER_FC_PORT_NAME: if (ISNS_ATTR_IS_NIL(attr)) goto invalid; obj = isns_dd_get_member_object(db, attr, next, is_registration); /* For a DD deregistration, it's okay if the * object does not exist. */ if (obj == NULL && is_registration) goto invalid; break; invalid: rv = ISNS_INVALID_REGISTRATION; continue; } if (obj) { if (is_registration && isns_object_test_membership(obj, dd->dd_id)) { /* Duplicates are ignored */ isns_debug_state("Ignoring duplicate DD registration " "for %s %u\n", obj->ie_template->iot_name, obj->ie_index); } else { /* This just adds the member to the temporary DD object, * without changing any state in the database. */ isns_dd_member_t *new; new = isns_dd_create_member(obj); if (new) { *tail = new; tail = &new->ddm_next; } } isns_object_release(obj); } } return rv; } /* * Helper function: extract live nodes from the DD member list */ static inline void isns_dd_get_member_nodes(isns_dd_member_t *members, isns_object_list_t *result) { isns_dd_member_t *mp; /* Extract iSCSI nodes from both list. */ for (mp = members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; if (ISNS_IS_ISCSI_NODE(obj) && obj->ie_state == ISNS_OBJECT_STATE_MATURE) isns_object_list_append(result, obj); } } void isns_dd_notify(const isns_dd_t *dd, isns_dd_member_t *unchanged, isns_dd_member_t *changed, int removed) { isns_object_list_t dd_objects = ISNS_OBJECT_LIST_INIT; isns_object_list_t changed_objects = ISNS_OBJECT_LIST_INIT; unsigned int i, j, event; /* Extract iSCSI nodes from both list. */ isns_dd_get_member_nodes(unchanged, &dd_objects); isns_dd_get_member_nodes(changed, &changed_objects); /* Send a management SCN multicast to all * control nodes that care. */ event = removed? ISNS_SCN_DD_MEMBER_REMOVED_MASK : ISNS_SCN_DD_MEMBER_ADDED_MASK; for (i = 0; i < changed_objects.iol_count; ++i) { isns_object_t *obj = changed_objects.iol_data[i]; isns_object_event(obj, event | ISNS_SCN_MANAGEMENT_REGISTRATION_MASK, dd->dd_object); } #ifdef notagoodidea /* Not sure - it may be good to send OBJECT ADDED/REMOVED instead * of the DD membership messages. However, right now the SCN code * will nuke all SCN registrations for a node when it sees a * REMOVE event for it. */ event = removed? ISNS_SCN_OBJECT_REMOVED_MASK : ISNS_SCN_OBJECT_ADDED_MASK; #endif /* If we added an iscsi node, loop over all members * and send unicast events to each iscsi node, * informing them that a new member has been added/removed. */ for (j = 0; j < changed_objects.iol_count; ++j) { isns_object_t *changed = changed_objects.iol_data[j]; for (i = 0; i < dd_objects.iol_count; ++i) { isns_object_t *obj = dd_objects.iol_data[i]; /* For member removal, do not send notifications * if the two nodes are still visible to each * other through a different discovery domain */ if (removed && isns_object_test_visibility(obj, changed)) continue; /* Inform the old node that the new node was * added/removed. */ isns_unicast_event(obj, changed, event, NULL); /* Inform the new node that the old node became * (in)accessible to it. */ isns_unicast_event(changed, obj, event, NULL); } /* Finally, inform each changed node of the other * DD members that became (in)accessible to it. */ for (i = 0; i < changed_objects.iol_count; ++i) { isns_object_t *obj = changed_objects.iol_data[i]; if (obj == changed) continue; if (removed && isns_object_test_visibility(obj, changed)) continue; isns_unicast_event(changed, obj, event, NULL); } } } void isns_dd_add_members(isns_dd_t *dd, isns_db_t *db, isns_dd_t *new_dd) { isns_dd_member_t *mp, **tail; for (mp = new_dd->dd_members; mp; mp = mp->ddm_next) { const char *node_name; isns_object_t *obj = mp->ddm_object.obj; /* * If the Operating Attributes contain a DD * Member iSCSI Name value for a Storage Node * that is currently not registered in the iSNS * database, then the iSNS server MUST allocate an * unused iSCSI Node Index for that Storage Node. * The assigned iSCSI Node Index SHALL be returned * in the DDRegRsp message as the DD Member iSCSI * Node Index. The allocated iSCSI Node Index * value SHALL be assigned to the Storage Node * if and when it registers in the iSNS database. * [And likewise for portals] */ if (obj->ie_index == 0) isns_db_insert_limbo(db, obj); mp->ddm_index = obj->ie_index; /* Record the fact that the object is a member of * this DD */ isns_object_mark_membership(obj, dd->dd_id); switch (mp->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: if (isns_object_get_string(obj, ISNS_TAG_ISCSI_NAME, &node_name)) isns_assign_string(&mp->ddm_iscsi_node.name, node_name); break; case ISNS_DD_MEMBER_IFCP_NODE: if (isns_object_get_string(obj, ISNS_TAG_FC_PORT_NAME_WWPN, &node_name)) isns_assign_string(&mp->ddm_ifcp_node.name, node_name); break; case ISNS_DD_MEMBER_PORTAL: isns_portal_from_object(&mp->ddm_portal.info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, obj); break; } } /* Find the tail of the DD member list */ tail = &dd->dd_members; while ((mp = *tail) != NULL) tail = &mp->ddm_next; /* Append the new list of members */ *tail = new_dd->dd_members; new_dd->dd_members = NULL; } /* * Remove members from a DD */ int isns_dd_remove_members(isns_dd_t *dd, isns_db_t *db, isns_dd_t *temp_dd) { isns_dd_member_t *mp; for (mp = temp_dd->dd_members; mp; mp = mp->ddm_next) { isns_object_t *obj = mp->ddm_object.obj; /* Clear the membership bit. If the object wasn't in this * DD to begin with, bail out right away. */ if (!isns_object_clear_membership(obj, dd->dd_id)) { isns_debug_state("DD dereg: object %d is not in this DD\n", obj->ie_index); continue; } if (!isns_dd_remove_member(dd, obj)) isns_error("%s: DD member not found in internal list\n", __FUNCTION__); } return ISNS_SUCCESS; } void isns_dd_store(isns_db_t *db, const isns_dd_t *dd, int rewrite) { isns_object_t *obj = dd->dd_object; isns_dd_member_t *member; if (rewrite) isns_object_prune_attrs(obj); isns_object_set_uint32(obj, ISNS_TAG_DD_ID, dd->dd_id); isns_object_set_string(obj, ISNS_TAG_DD_SYMBOLIC_NAME, dd->dd_name); isns_object_set_uint32(obj, ISNS_TAG_DD_FEATURES, dd->dd_features); for (member = dd->dd_members; member; member = member->ddm_next) { struct isns_dd_iscsi_node *node; struct isns_dd_portal *portal; if (!member->ddm_added && !rewrite) continue; switch (member->ddm_type) { case ISNS_DD_MEMBER_ISCSI_NODE: node = &member->ddm_iscsi_node; isns_object_set_uint32(obj, ISNS_TAG_DD_MEMBER_ISCSI_INDEX, node->index); if (node->name) isns_object_set_string(obj, ISNS_TAG_DD_MEMBER_ISCSI_NAME, node->name); break; case ISNS_DD_MEMBER_PORTAL: portal = &member->ddm_portal; isns_object_set_uint32(obj, ISNS_TAG_DD_MEMBER_PORTAL_INDEX, portal->index); if (portal->info.addr.sin6_family != AF_UNSPEC) { isns_portal_to_object(&portal->info, ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR, ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT, obj); } break; } member->ddm_added = 0; } } /* * Destroy a DD * The caller should call isns_dd_release to free the DD object. */ void isns_dd_destroy(isns_db_t *db, isns_dd_t *dd) { isns_db_remove(db, dd->dd_object); isns_dd_list_remove(&isns_dd_list, dd); dd->dd_inserted = 0; } int isns_dd_load_all(isns_db_t *db) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; unsigned int i; int rc; if (isns_dd_list_initialized) return ISNS_SUCCESS; rc = isns_db_gang_lookup(db, &isns_dd_template, NULL, &list); if (rc != ISNS_SUCCESS) return rc; for (i = 0; i < list.iol_count; ++i) { isns_object_t *obj = list.iol_data[i]; isns_dd_t *dd = NULL, *temp_dd = NULL; isns_dd_member_t *mp; temp_dd = isns_dd_alloc(); rc = isns_dd_parse_attrs(temp_dd, db, &obj->ie_attrs, NULL, 1); if (rc) { if (temp_dd->dd_id == 0) { isns_error("Problem converting DD object (index 0x%x). No DD_ID\n", obj->ie_index); goto next; } isns_error("Problem converting DD %u. Proceeding anyway.\n", temp_dd->dd_id); } else { isns_debug_state("Loaded DD %d from database\n", temp_dd->dd_id); } dd = isns_dd_clone(temp_dd); dd->dd_object = isns_object_get(obj); isns_dd_insert(dd); isns_dd_add_members(dd, db, temp_dd); /* Clear the ddm_added flag for all members, to * prevent all information from being duplicated * to the DB on the next DD modification. */ for (mp = dd->dd_members; mp; mp = mp->ddm_next) mp->ddm_added = 0; next: isns_dd_release(temp_dd); } isns_object_list_destroy(&list); isns_dd_list_initialized = 1; return ISNS_SUCCESS; } isns_object_t * isns_dd_get_member_object(isns_db_t *db, const isns_attr_t *key1, const isns_attr_t *key2, int create) { isns_attr_list_t query = ISNS_ATTR_LIST_INIT; isns_object_template_t *tmpl = NULL; isns_object_t *obj; isns_portal_info_t portal_info; const char *key_string = NULL; uint32_t key_index = 0; switch (key1->ia_tag_id) { case ISNS_TAG_DD_MEMBER_ISCSI_INDEX: key_index = key1->ia_value.iv_uint32; isns_attr_list_append_uint32(&query, ISNS_TAG_ISCSI_NODE_INDEX, key_index); tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_DD_MEMBER_ISCSI_NAME: key_string = key1->ia_value.iv_string; isns_attr_list_append_string(&query, ISNS_TAG_ISCSI_NAME, key_string); tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_DD_MEMBER_FC_PORT_NAME: key_string = key1->ia_value.iv_string; isns_attr_list_append_string(&query, ISNS_TAG_FC_PORT_NAME_WWPN, key_string); tmpl = &isns_fc_port_template; break; case ISNS_TAG_DD_MEMBER_PORTAL_INDEX: key_index = key1->ia_value.iv_uint32; isns_attr_list_append_uint32(&query, ISNS_TAG_PORTAL_INDEX, key_index); tmpl = &isns_portal_template; break; case ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR: if (!isns_portal_from_attr_pair(&portal_info, key1, key2) || !isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, &query)) return NULL; key_string = isns_portal_string(&portal_info); tmpl = &isns_portal_template; break; default: return NULL; } obj = isns_db_lookup(db, tmpl, &query); if (!obj && create) { if (!key_string) { isns_debug_state("Attempt to register %s DD member " "with unknown index %u\n", tmpl->iot_name, key_index); goto out; } obj = isns_create_object(tmpl, &query, NULL); if (obj != NULL) isns_debug_state("Created limbo object for " "%s DD member %s\n", tmpl->iot_name, key_string); } out: isns_attr_list_destroy(&query); return obj; } open-iscsi-2.0.873/utils/open-isns/deregister.c000066400000000000000000000170511175631155400213340ustar00rootroot00000000000000/* * Handle iSNS Device Deregistration * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" extern isns_source_t * isns_server_source; /* * Create a registration, and set the source name */ static isns_simple_t * __isns_create_deregistration(isns_source_t *source, const isns_attr_list_t *attrs) { isns_simple_t *simp; simp = isns_simple_create(ISNS_DEVICE_DEREGISTER, source, NULL); if (simp && attrs) isns_attr_list_copy(&simp->is_operating_attrs, attrs); return simp; } isns_simple_t * isns_create_deregistration(isns_client_t *clnt, const isns_attr_list_t *attrs) { return __isns_create_deregistration(clnt->ic_source, attrs); } /* * Get the next object identified by the operating attrs. */ static int isns_deregistration_get_next_object(isns_db_t *db, struct isns_attr_list_scanner *st, isns_object_list_t *result) { isns_object_t *current; int status; status = isns_attr_list_scanner_next(st); if (status) return status; /* * 5.6.5.4. * Valid Operating Attributes for DevDereg * --------------------------------------- * Entity Identifier * Portal IP-Address & Portal TCP/UDP Port * Portal Index * iSCSI Name * iSCSI Index * FC Port Name WWPN * FC Node Name WWNN * * In other words, deregistration is restricted to Entity, * portal, and node */ if (st->tmpl != &isns_entity_template && st->tmpl != &isns_iscsi_node_template && st->tmpl != &isns_portal_template) return ISNS_INVALID_DEREGISTRATION; /* Only key attrs allowed */ if (st->attrs.ial_count) { /* MS Initiators send the Entity protocol along * with the Entity Identifier. */ isns_debug_protocol("Client included invalid operating attrs " "with %s:\n", st->tmpl->iot_name); isns_attr_list_print(&st->attrs, isns_debug_protocol); /* return ISNS_INVALID_DEREGISTRATION; */ } /* * 5.6.5.4 * Attempted deregistration of non-existing entries SHALL not * be considered an isns_error. */ current = isns_db_lookup(db, st->tmpl, &st->keys); if (current != NULL) { isns_object_list_append(result, current); isns_object_release(current); } return ISNS_SUCCESS; } /* * Extract the list of objects to be deregistered from * the list of operating attributes. */ static int isns_deregistration_get_objects(isns_simple_t *reg, isns_db_t *db, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, NULL, ®->is_operating_attrs); state.index_acceptable = 1; state.source = reg->is_source; while (state.pos < state.orig_attrs.ial_count) { status = isns_deregistration_get_next_object(db, &state, result); if (status == 0) continue; /* Translate error codes */ if (status == ISNS_NO_SUCH_ENTRY) status = ISNS_SUCCESS; else if (status == ISNS_INVALID_REGISTRATION) status = ISNS_INVALID_DEREGISTRATION; break; } isns_attr_list_scanner_destroy(&state); return status; } /* * Process a deregistration * * Normally, you would expect that a deregistration removes the * object from the database, and that's the end of the story. * Unfortunately, someone added Discovery Domains to the protocol, * requiring _some_ information to survive as long as an object * is referenced by a discovery domain. Specifically, we need to * retain the relationship between key attributes (eg iscsi node * name) and the object index. * * Thus, deregistration consists of the following steps * - the object is removed from the database's global scope, * so that it's no longer visible to DB lookups. * * - the object is detached from its containing Network * Entity. * * - all attributes except the key attr(s) and the index * attribute are removed. */ int isns_process_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *reply = NULL; isns_db_t *db = srv->is_db; int status, dereg_status; unsigned int i; /* Get the objects to deregister */ status = isns_deregistration_get_objects(call, db, &objects); if (status != ISNS_SUCCESS) goto done; /* * 5.6.5.4 * * For messages that change the contents of the iSNS database, * the iSNS server MUST verify that the Source Attribute * identifies either a Control Node or a Storage Node that is * a part of the Network Entity containing the added, deleted, * or modified objects. */ /* * Implementation note: this can be implemented either by * explicitly checking the object's owner in isns_db_remove * (which is what we do right now), or by matching only * those objects that have the right owner anyway. * * The latter sounds like a better choice if the client * uses NIL attributes, because it limits the scope of * the operation; but then the RFC doesn't say whether * this kind of deregistration would be valid at all. */ /* Success: create a new simple message, and * send it in our reply. */ reply = __isns_create_deregistration(srv->is_source, NULL); if (reply == NULL) { status = ISNS_INTERNAL_ERROR; goto done; } dereg_status = ISNS_SUCCESS; for (i = 0; i < objects.iol_count; ++i) { isns_object_t *obj = objects.iol_data[i]; /* Policy: check that the client is permitted * to deregister this object */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, obj, call->is_function)) status = ISNS_SOURCE_UNAUTHORIZED; if (status == ISNS_SUCCESS) status = isns_db_remove(db, obj); if (status != ISNS_SUCCESS) { /* * 5.7.5.4 * * In the event of an error, this response message * contains the appropriate status code as well * as a list of objects from the original DevDereg * message that were not successfully deregistered * from the iSNS database. This list of objects * is contained in the Operating Attributes * of the DevDeregRsp message. Note that an * attempted deregistration of a non-existent * object does not constitute an isns_error, and * non-existent entries SHALL not be returned * in the DevDeregRsp message. */ /* * Implementation: right now this doesn't work * at all, because isns_msg_set_error will * discard the entire message except for the * status word. */ isns_debug_message("Failed to deregister object: %s (0x%04x)\n", isns_strerror(status), status); isns_object_extract_all(obj, &reply->is_operating_attrs); dereg_status = status; continue; } /* * 5.7.5.4 * If all Nodes and Portals associated with a Network * Entity are deregistered, then the Network Entity * SHALL also be removed. * [...] * If both the Portal and iSCSI Storage Node objects * associated with a Portal Group object are removed, * then that Portal Group object SHALL also be removed. * The Portal Group object SHALL remain registered * as long as either of its associated Portal or * iSCSI Storage Node objects remain registered. If a * deleted Storage Node or Portal object is subsequently * re-registered, then a relationship between the re- * registered object and an existing Portal or Storage * Node object registration, indicated by the PG object, * SHALL be restored. */ /* isns_db_remove takes care of removing dead entities, * and dead portal groups. */ } if (status == ISNS_SUCCESS) status = dereg_status; done: isns_object_list_destroy(&objects); *result = reply; return status; } open-iscsi-2.0.873/utils/open-isns/doc/000077500000000000000000000000001175631155400175745ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/doc/isns_config.5000066400000000000000000000326271175631155400221750ustar00rootroot00000000000000.TH ISNS_CONFIG 8 "11 May 2007" .SH NAME isns_config - iSNS configuration file .SH SYNOPSIS .B /etc/isns/isnsadm.conf .br .B /etc/isns/isnsd.conf .br .B /etc/isns/isnsdd.conf .SH DESCRIPTION All Open-iSNS utilities read their configuration from a file in .BR /etc/isns . There is a separate configuration file for each application, .BR isnsd ", " isnsadm ", and " isnsdd . The syntax and the set of supported options is identical, even though some options are specific to e.g. the server. Unless indicated, options are applicable to all utilities. .PP An Open-iSNS configuration file contains keyword-argument pairs, one per line. All keywords are case insensitive. .PP A .B # character introduces a comment, which extends until the end of the line. Empty lines are ignored. .PP There are no line continuations, and you cannot use quotes around arguments. .PP Some options specify timeout values, which are given in units of seconds by default. You can specify an explicit unit, however, such as .BR d " (days), .BR h " (hours), .BR m " (minutes), or .BR s " (seconds). .\" ------------------------------------------------------------------ .SS Generic Options .TP .BR HostName By default, Open-iSNS applications will retrieve the machine's hostname using the .BR gethostname (3) system call, and use a DNS lookup to look up the canonical name. Using the .BR HostName option, you can overried this. This option is rarely needed. .TP .BR SourceName This option is mandatory for all Open-iSNS applications. This should be a name which identifies the client uniquely. There are two readings of RFC 4171; one requires that this is an iSCSI qualified name such as .BR iqn.2001-04.com.example.host , whereas other language in the RFC suggests that this is pretty much a free-format string that just has to be unique (using e.g. the client's fully qualified domain name). .IP When using DSA authentication, Open-iSNS currently requires the source name to match the key identifier (SPI) of the client's public key. .IP If left empty, the source name is derived from the client's hostname. .TP .BR ServerAddress " (client): This options specifies the host name or address of the iSNS server to talk to. It can optionally be followed by a colon, and a port number. .IP Instead of a hostname, IPv4 or IPv6 addresses can be used. In order to avoid ambiguities, literal IPv6 addresses must be surrounded by square brackets, as in .BR [2001:4e5f::1] . .IP When specifying a port number, you can use either the numeric port, or a string name to be looked up in .BR /etc/services . When the port is omitted, it defaults to 3205, the IANA assigned port number of iSNS. .IP If the special string .B SLP: is used, the client will try to locate the iSNS server through SLP. .TP .BR SLPRegister " (server): If set to 1, the iSNS daemon will register itself will the SLP service. This allows clients to contact the server without having to configure its address statically. .TP .BR PIDFile " (server): This specifies the name of the server's PID file, which is .B /var/run/isnsd.pid by default. .\" ------------------------------------------------------------------ .SS Database Related Options These options apply to the iSNS server only, and control operation of the iSNS database. .TP .BR Database This option is used to specify how the database is stored. Setting this to an absolute path name will make .B isnsd keep its database in the specified directory. .IP If you leave this empty, .B isnsd will keep its database in memory. This is also the default setting. .TP .BR DefaultDiscoveryDomain iSNS scopes visibility of other nodes using so-called Discovery Domains. A storage node A will only "see" storage node B, if both are members of the same discovery domain. .IP So if a storage node is registered which is not part of any discovery domain, it will not see any other nodes. .IP By setting .BR DefaultDiscoveryDomain=1 , you can tell isnsd to create a virtual "default discovery domain", which holds all nodes that are not part of any administratively configured discovery domain. .IP By default, there is no default discovery domain. .TP .BR RegistrationPeriod The iSNS server can purge registered entities after a certain period of inactivity. This is called the registration period. Clients who register objects are supposed to refresh their registration within this period. .IP The default value is 1 hour. Setting it to 0 disables expiry of entities from the database. .TP .BR ESIRetries Open-iSNS is able to monitor the reachability of storage nodes and their portals by using a protocol feature called ESI (Entity status inquiry). Clients request ESI monitoring by registering an ESI port along with each portal. The server will send ESI messages to these portals at regular intervals. If the portal fails to reply several times in a row, it is considered dead, and will be removed from the database. .IP .B ESIRetries specifies the maximum number of attempts the server will make at contacting the portal before pronouncing it dead. If set to 0, the server will disable ESI and reject any registrations that specify an ESI port with an error code of "ESI not supported". .IP The default value is 3. .TP .BR ESIMinInterval This timeout value specifies the minimum ESI interval. If a client requests an ESI interval less than this value, it is silently rounded up. .IP The default value is 60 seconds. .TP .BR ESIMaxInterval This timeout value specifies the maximum ESI interval. If a client requests an ESI interval greater than this value, it is silently rounded down. .IP The default value is 10 minutes. .IP The maximum ESI interval must not exceed half the value of the registration period. .TP .B SCNRetries iSNS clients can register to receive State Change Notification (SCN) messages to learn about changes in the iSNS database. This value specifies how often the server will try to retransmit an SCN message until giving up. .IP The default value is 3. .TP .B SCNCallout This is the path name of a helper program that .B isnsdd will invoke whenever it processes a state change notification from the server. The helper program will be invoked with an argument indicating the type of event, being one of .BR add ", " update ", or " remove . This is followed by a list of attributes in .IB name = value notation, using the names and conventions described in .BR isnsadm (8). .\" ------------------------------------------------------------------ .SS Security Related Options The iSNS standard defines an authentication method based on the DSA algorithm. Participants in a message exchange authenticate messages by adding an "authentication block" containing a time stamp, a string identifying the key used, and a digital signature of the message. The same method is also used by SLP, the Service Location Protocol. .PP The string contained in the authentication block is referred to as the .IR "Security Policy Index" (SPI). This string can be used by the server to look up the client's public key by whatever mechanism; so the string could be used as the name of a public key file in a directory, or to retrieve an X509 certificate from LDAP. .PP From the perspective of Open-iSNS client applications, there are only two keys: the client's own (private) key, used to sign the messages it sends to the server, and the server's public key, used to verify the signatures of incoming server messages. .PP The iSNS server needs, in addition to its own private key, access to all public keys of clients that will communicate to it. The latter are kept in what is called a key store. Key stores and their operation will be discussed in section .B Key Stores and Policy below. .PP The following configuration options control authentication: .TP .BR Security This enables or disables DSA authentication. When set to 1, the client will sign all messages, and expect all server messages to be signed. .IP When enabling security in the server, incoming messages are checked for the presence of an auth block. If none is present, or if the server cannot find a public key corresponding to the SPI, the message is treated as originating from an anonymous source. If the SPI is known but the signature is incorrect, the message is dropped silently. .IP Messages from an anonymous source will be assigned a very restrictive policy that allows database queries only. .IP Setting this option to 0 will turn off authentication. .IP The default value is -1, which tells iSNS to use authentication if the required keys are installed, and use unauthenticated iSNS otherwise. .TP .BR AuthName This is the string that will be used as the SPI in all outgoing messages that have an auth block. It defaults to the host name (please refer to option .BR HostName ). .TP .BR AuthKeyFile This is the path name of a file containing a PEM encoded DSA key. This key is used to sign outgoing messages. The default is .BR /etc/isns/auth_key . .TP .BR ServerKeyFile This option is used by client applications only, and specifies the path name of a file containing a PEM encoded DSA key. This key is used to authenticate the server's replies. The default is .BR /etc/isns/server_key.pub . .TP .BR KeyStore This server-side option specifies the key store to use, described in the next section. .PP The following two options control how iSNS will verify the time stamp contained in the authentication block, which is supposed to prevent replay attacks. .TP .B Auth.ReplayWindow In order to compensate for clock drift between two hosts exchanging iSNS messages, Open-iSNS will apply a little fuzz when comparing the time stamp contained in the message to the local system time. If the difference between time stamp and local system time is less than the number of seconds given by this option, the message is acceptable. Otherwise, it is rejected. .IP The default value is .BR 5m . .TP .B Auth.TimestampJitter When verifying incoming messages, Open-iSNS checks that the time stamps sent by the peer are increasing monotonically. In order to compensate for the reordering of messages by the network (eg when using UDP as transport), a certain time stamp jitter is accepted. If the time stamp of an incoming messages is no earlier than .B TimestampJitter seconds before the last time stamp received, then the message is acceptable. Otherwise, it is rejected. .IP The default value is .BR 1s . .\" ------------------------------------------------------------------ .SS Key Stores and Policy The current implementation supports two types of key stores. .PP The simple key store uses a flat directory to store public keys, each key in a file of its own. The file is expected to hold the client's PEM-encoded public key, and it must use the client's SPI as the name. This type of key store is not really recommended, as it does not store any policy information. .PP A simple key store can be configured by setting the .B KeyStore option to the path name of the directory. .PP The recommended approach is to use the database as key store. This uses vendor-specific policy objects to tie SPI string, public key, entity name, source name and other bits of policy together, and store them in a persistent way. .PP The database key store is configured by setting the .B KeyStore option to the reserved value .BR DB: , which is also the default. .PP Currently, Open-iSNS policy objects have the following attributes, besides the SPI: .TP Source: This is the source node name the client must use. It defaults to the SPI string. .TP Functions: This is a bitmap detailing which functions the client is permitted to invoke. The bit names correspond to the shorthand names used in RFC 4711, such as .BR DevAttrReg , .BR DevAttrQry , etc. The default is to allow registration, query and deregistration, as well as SCNRegister. .TP Entity name: This is the entity name assigned to the client. If set, a registration by the client is not permitted to use a different entity name. If the client sends a registration without Entity identifier, the server will assign the entity name given in the policy. The default is to not restrict the entity name. .TP Object access: This is a bitfield describing access permissions for each object type. For each object type, you can grant Read and/or Write permissions. Read access applies to the Query and GetNext calls; all other operations require write permission. The default grants read and write access to objects of type Entity, Storage Node, Portal and Portal Group; and read access to Discovery Domains. .TP Node types: This bitfield describes which types of storage nodes a client is allowed to register; the valid bit names are .BR target ", " initiator " and " control . The default is to restrict nodes to register initiators only. .\" ------------------------------------------------------------------ .SS Network Related Options .TP .BR Network.MaxSockets This is the number of incoming connections accepted, and defaults to 1024. This usually applies to server side only, but is relevant if you create a passive TCP socket for ESI or SCN. .TP .BR Network.ConnectTimeout This is a timeout value, which specifies the time to wait for a TCP connection to be established. It defaults to .BR 60s . .TP .BR Network.ReconnectTimeout When a connection attempt failed, we wait for a short time before we try connecting again. This is intended to take the pressure off overloaded servers. The default value is .BR 10s . .TP .BR Network.CallTimeout Total amount of time to wait before timing out a call to the iSNS server. The default value is .BR 60s . .\" ------------------------------------------------------------------ .SH SEE ALSO RFC 4171, .BR isnsd (8), .BR isnsadm (8). .SH AUTHORS Olaf Kirch open-iscsi-2.0.873/utils/open-isns/doc/isnsadm.8000066400000000000000000000461551175631155400213360ustar00rootroot00000000000000'\" t .TH ISNSADM 8 "11 May 2007" .SH NAME isnsadm \- iSNS client utility .SH SYNOPSIS .B isnsadm .RI [ options... ] .RI --register " object... .PP .B isnsadm .RB [ ... ] .RI --query " attr" [= value ] .PP .B isnsadm .RB [ ... ] .RI --deregister " attr=value .PP .B isnsadm .RB [ ... ] .RI --list " type attr=value .PP .B isnsadm .RB [ ... ] .RI --dd-register " attr=value .PP .B isnsadm .RB [ ... ] .RI --enroll " client-name attr=value .PP .B isnsadm .RB [ ... ] .RI --edit-policy " attr=value .SH DESCRIPTION .B Isnsadm is a command line utility for interacting with an iSNS server. It operates in one of several modes, which are mutually exclusive. Currently, .B isnsadm supports registration, query, and deregistration. .SH OPTIONS By default, .B isnsadm will take most of its settings from the configuration file .BR /etc/isns/isnsadm.conf , with the exception of the following options: .TP .BI \--config " filename\fR, " \-c " filename This option overrides the default configuration file. .TP .BI \--debug " facility\fR, " \-d " facility enables debugging. Valid facilities are .PP .TS tab(,),box,center; lb|lr. socket,network send/receive auth,authentication and security related information message,iSNS protocol layer state,database state scn,SCN (state change notification) messages esi,ESI (entity status inquiry) messages all,all of the above .TE .PP .TP .BI \--local makes .B isnsadm use a Local (aka Unix) socket when talking to the iSNS server. This can be used by the administrator to perform management tasks, such as enrolling new clients, editing access control and so on. Local mode is only available to the super user. .TP .BI \--control makes .B isnsadm assume the identity of a control node. Control nodes are special in that they have more rights in accessing and modifying the database than normal storage nodes have. .PP When using this option, .B isnsadm will use the source name and DSA key specified by the .BR Control.SourceName " and " Control.AuthKeyFile configuration options, respectively. .PP .TP .BI \--key " attr" = value This option is recognized in registration mode only, and lets you specify an object key. For a more detailed explanation, refer to section .BR "Registration mode" . .TP .BI \--keyfile= filename When creating a policy for a new iSNS client, .B isnsadm is able to generate a DSA key for the client. The public part of the key is stored in a policy object in the iSNS server's database, whereas the private portion is stored in the file specified by the .B keyfile option. .B .TP .BI \--help This will print a help message and exit. .\"--------------------------- .SS Built-in help .B Isnsadm has built-in help functions. When invoked with .BR \--help , it will print a general help message showing all supported command modes, and exit. Specific help on an individual command mode is available by invoking that mode with a single argument of .BR help , like this: .PP .B isnsadm --register help .PP This will print a help message describing how to use this command mode, followed by a list of attributes this command supports and a help text describing the attribute. .\"--------------------------- .SS Supported attributes Most command modes take a list of attributes as arguments on the command line. The naming and syntax of these attributes as the same for all commands modes, however certain modes support only a limited set of attributes. .PP Attributes are usually given as .IB name = value pairs. Where empty (or NIL) attributes are supported, the attribute name by itself can be given. .PP The syntax of attribute .I value depends on the attribute type. For strings and numeric values, no special conventions apply, but bitfields have a special syntax described below. .PP The attribute name is usually preceded by the object type it applies to (such as .BR entity ), followed by a hyphen and the name itself. However, where the context clearly determines a specific object type, the prefix can be omitted. For instance, when editing a policy object using .BR \--edit-policy , it is acceptable to use .B node-type as shorthand for .BR policy-node-type . .PP Likewise, in a query command, it is not permitted to mix attributes from different object types. Thus, the first attribute of a query string establishes a type context, so that the following two invocations are equivalent: .PP .B isnsadm --query pg-name=iqn.com.foo pg-addr=10.1.1.1 pg-port=860/tcp .br .B isnsadm --query pg-name=iqn.com.foo addr=10.1.1.1 port=860/tcp .PP .B Isnsadm currently supports the following attributes: .PP .TS tab(,),box,center; li|lilili lt|lbrlb. Context,Attribute,iSNS tag,Aliases _ Network Entity,entity-id,1,eid \^,entity-prot,2 \^,entity-index,7 iSCSI Storage Node,iscsi-name,32 \^,iscsi-node-type,33 \^,iscsi-alias,34 \^,iscsi-idx,36 \^,iscsi-authmethod,42 Portal,portal-addr,16 \^,portal-port,17 \^,portal-name,18 \^,portal-esi-port,20 \^,portal-esi-interval,21 \^,portal-idx,22 \^,portal-scn-port,23 Portal Group,portal-group-index,52 \^,pg-name,48 \^,pg-addr,49 \^,pg-port,50 \^,pg-tag,51,pgt \^,pg-idx,52 Discovery Domain,dd-id,2065 \^,dd-name,2066 \^,dd-member-iscsi-idx,2067 \^,dd-member-name,2068 \^,dd-member-fc-name,2069, \^,dd-member-portal-idx,2070, \^,dd-member-addr,2071, \^,dd-member-port,2072, \^,dd-features,2078, Policy Object,policy-name,-,spi \^,policy-key,- \^,policy-entity,- \^,policy-node-type,- \^,policy-object-type,- \^,policy-functions,- .TE .PP .\"--------------------------- .SS Portal attributes Portal information is conveyed by two separate attributes in iSNS; an address attribute holding the IP address, and a TCP/UDP port attribute holding the port number and an indication of the protocol to be used (TCP or UDP). .PP When parsing a TCP/UDP port, Open-iSNS will expect a port number, optionally followed by a slash and the protocol. Port names such as "iscsi-target" are not supported. .PP As a convenience, .B isnsadm supports a notation representing a portal as one pseudo-attribute. Separating address and port by a colon. Thus, the following two are equivalent, with the latter being the shorthand representation of the former: .PP .BI addr=
" port=" [/ protocol ] \fR. .BI portal= : port [/ protocol ] .PP This notation can be used in any context where an .BR addr / port attribute pair can appear, and may be prefixed by a type name, as in .BR pg-portal=... . .PP When using literal IPv6 addresses, the address has to be surrounded by square brackets, otherwise the embedded colons would create ambiguity: .BR portal=[2001:5c0:0:2::24]:860/tcp .PP .\"--------------------------- .SS Bitfield attributes Some iSNS attributes are words representing a bit field. .B Isnsadm displays and parses these attributes in human-readable form rather than using the numerical value. The names of the bit values are displayed by built-in help facilities. When specifying a bitfield attribute on the command line, you can combine them using the plus (\fB+\fP) or comma (\fB,\fR) character, like this: .PP .B node-type=control+initiator .PP .\"--------------------------- .SS Registration mode Registration mode is selected by using the .B --register option, followed by a list of one or more objects to register with the iSNS server. By default, this will create a network entity for the client (if none exists), and place the new objects inside it. Usually, you register all objects for a network entity in one operation, rather than each one separately. .PP Each object is specified as a type, optionally followed by a comma-separated list of attributes, such as this: .PP .B target=iqn.2005-01.org.open-iscsi.foo:disk1,alias=disk1 .PP The following object types are currently supported: .TP .BI entity= name Tells the server to group all objects in the specified Network Entity container object. Normally, the iSNS server will automatically assign an entity name that is in line with its policies, and there is no need to specify it explicitly. .TP .BI initiator[= name ] This will register an iSCSI storage node of type initiator. By default, the name is set to the iSNS source name. .IP This can be followed by any number of iSCSI storage node attributes. .TP .BI target[= name ] This will register an iSCSI storage node of type target. By default, the name is set to the iSNS source name. .IP This object accepts the same set of attributes as .BR initiator . .TP .BI control[= name ] This will register an iSCSI storage node of type control. By default, the name is set to the iSNS source name. Only management nodes should be registered as control nodes, as this gives a node complete control over the iSNS database. .IP This object accepts the same set of attributes as .BR initiator . .TP .BI portal=[ address:port/proto ] This will register a portal using the given address, port and protocol triple. If the triple is omitted, .B isnsadm will use the client host's IP address. If the portal is preceded by an initiator registration (on the command line), the port defaults to 860/tcp; if it is preceded by a target registration, the port defaults to 3260/tcp. For multi-homed hosts, the choice of address is implementation dependant. .IP This can be followed by any number of portal attributes. .TP .B pg This will register a portal group joining the preceding portal and node. Portal groups can be used to describe the preferred portals for a given node; please refer to RFC 4711 for details. .IP This can be followed by any number of portal group attributes. The attribute list must specify a portal group tag (PGT) via the .BR pgt attribute. .PP There are two additional command line options of interest, which are used exclusively with Registration mode. One is .BR \--replace . Normally, registration mode will .I add new objects to the network entity associated with the client host. If you specify .B \--replace on the command line, the server will wipe the network entity completely, and remove all portals and storage nodes it contained. Then it will create a new network entity, and place the portals and storage nodes provided by the caller inside. .PP In addition, it is possible to replace just parts of a network entity. This is achieved by using the command line option .B \--key to specify the object that should be replaced. .PP For instance, assume a network entity contains the portal .BR 10.1.1.1:860 , and the client's network address changed to .BR 10.2.7.7 . Then the following command will atomically update the database, replacing just the portal without touching the registered storage nodes: .PP .B " isnsadm --replace --key portal=10.1.1.1:860 portal=10.2.7.7:860 .PP The .B \--key option recognizes only a subset of the usual attributes: .RS .TS tab(,),box; li|li lb|lb. Object type,Syntax _ Entity,eid=\fIidentifier Portal,portal=\fIaddress\fP:\fPport iSCSI Node,iscsi-name=\fIname .TE .RE .PP To get a list of supported attributes, invoke .BR "isnsadm --register help" . .\"--------------------------- .SS Query mode Query mode is selected by using the .B --query option. A query consists of a list of .BR attr = \fI value pairs. All attributes must belong to the same object type, i.e. queries that mix a Network Entity attribute with e.g. a Portal attribute will be rejected. .PP It is also possible to specify an attribute name without value (i.e. just .BR attr ), which will will match any object that has such an attribute, regardless of its value. This is useful when you want to query for all objects of a given type. .PP To obtain a list of supported attributes, invoke .BR "isnsadm --query help" . .\"--------------------------- .SS List Mode In this mode, .B isnsadm will display all objects of a given type, optionally restricted to those matching certain attribute values. .PP The arguments to list mode are a .IR "type name" , optionally followed by one or more .IB attr = value pairs. Only attributes pertaining to the given type are permitted; for instance, if you specify a type name of .BR portals , only portal attributes are permitted. .PP Possible type names are: .BR entities , .BR nodes , .BR portals , .BR dds , .BR ddsets , .BR portal-groups ", and " .BR policies . .PP Additional information is available via .BR "isnsadm --list help" . .\"--------------------------- .SS Deregistration mode In this mode, you can deregister objects previously registered. Only the node which registered an entity in the first place is permitted to remove it, or any of its child objects. (Control nodes are not bound by this restriction). .PP In deregistration mode, the argument list consists of a list of .IB attr = value pairs. Deregistration supports the same set of attributes as query mode. .\"--------------------------- .SS Discovery Domain Registration This mode, allows to register a discovery domain or to add new members to an existing discovery domain. Again, attributes are specified as a list of .IB attr = value pairs. Only discovery domain attributes are recognized. .PP Note, in order to add members to an existing domain, you must specify the domain's numeric ID. The domain's symbolic name is not a valid handle when referring to a discovery domain. .\"--------------------------- .SS Client Enrollment This mode only works when the server recognizes the client as having control node capabilities, which is possible in two ways: .TP Invoke .B isnsadm \--local as super user on the host .B isnsd is running on. The .B \--local options tells it to communicate with the server through the local control socket. .TP Invoke .BR "isnsadm \--control" , which tells it to assume the identity of a control node. When given this option, .B isnsadm will use the source name and DSA key specified by the .BR Control.SourceName " and " Control.AuthKeyFile configuration options, respectively. The server must be configured to grant this identity control node status. .PP To enroll a client, use the .B \--enroll option, followed by the (source) name of the client to enroll. This string will be used as the name of the security policy the client will use to identify itself. .PP This is followed by a list of attribute/value pairs, where the following set of attributes is supported: .PP .TS tab(,),box,center; li|lilili lb|lrlb. Attribute,Description,Aliases _ name,Policy Name,spi key,Client's DSA public key entity,Assigned Entity Identifier node-type,Permitted node type(s) node-name,Permitted node name(s) functions,Bitmap of permitted functions object-type,Object access mask .TE .PP The .B key attribute is used to specify the DSA public key that the server should use to authenticate messages from this client. You can either provide a file name; in which case .B isnsadm will try to read the PEM encoded public key from that file. If no .B key attribute is given, or when using .BR key=gen ", " isnsadm will generate a DSA key. The private portion of the newly generated key will be stored in the file specified by .BI --keyfile= filename \fR. .PP The .B object-type attribute is used to specify which object types the client is permitted to access. This is a comma separated list of .IB type : perm pairs, where .I type can be any of .BR entity ", " iscsi-node ", " portal ", " portal-group ", " dd ", " ddset ", and " policy . The permissions can be either .BR rw ", or " r . .PP The .B functions attribute can be used to restrict which functions the client is permitted to invoke. This is a bitfield, using the standard function names from RFC 4171, such as .BR DevAttrReg ", " DevAttrQry ", etc." .PP For a description of the open-isns security model and policies, please refer to the .BR isns_config (5) manual page. .PP .BR "Important note" : In order to generate a DSA key, you have to have a set of DSA parameters installed. By default, .B isnsadm expects to find them in .BR /etc/isns/dsa.params . These parameters are created by calling .B isnsd \--init once on the server machine. Alternatively, you can use the following command: .PP .ti +8 openssl dsaparam 1024 -out /etc/isns/dsa.params .ti -8 .PP where 1024 is the chosen DSA key size, in bits. .SH EXAMPLES If you want to use Open-iSNS in authenticated mode, you first need to initialize the server's DSA key and DSA parameters. This can be done conveniently by using .PP .B isnsd --init .PP This will create the server's private and public key, and place them in .B /etc/isns/auth_key and .BR auth_key.pub , respectively. .PP The following command will create a policy object for a node named .B isns.control , and grant it control privileges: .PP .B isnsadm --local --keyfile=control.key .B --enroll isns.control \(rs .br .B " node-type=ALL functions=ALL object-type=ALL .PP In the process of entrolling the client, this will generate a DSA key pair, and place the private key portion in the file .BR control.key . This file must be installed as .BR /etc/isns/control.key on the host you wish to use as an iSNS management station. .PP Next, you need to create a storage node object for the management station: .PP .B isnsadm --local --register control .PP On the management station, you can then enroll additional hosts: .PP .B isnsadm --control --keyfile=somehost.key .B --enroll iqn.2005-01.org.open-iscsi.somehost \(rs .br .B " node-type=target+initiator .PP Again, this will generate a DSA key pair and store the private key portion in auth_key. Note the use of the .B \--control option that tells .B isnsadm to use the identity of the control node instead of the default key and source name. .PP You then need to copy .B somehost.key to the client host and install it as .BR /etc/isns/auth_key . Likewise, the server's public key (which resides in .BR /etc/isns/auth_key.pub on the server) needs to be copied to the client machine, and placed in .BR /etc/isns/server_key.pub . .PP By default, when a client registers a storage node (be it initiator or target) with iSNS, the client will not be able to see any other storage nodes. In order for targets to be visible to a given initiator, you need to create so-called Discovery Domains (or DDs for short). .PP Currently, domain membership operations require administrator privilege. Future extensions may allow iSNS clients to add themselves to one or more DDs upon registration. .PP To create a discovery domain, and add nodes to it, you can use .PP .B isnsadm --control --dd-register dd-name=mydomain \(rs .br .B " member-name=iqn.org.bozo.client iqn.org.bozo.jbod ... .PP In order to add members to an existing DD, you have to specify the numeric domain ID - using the DD name is not sufficient, unfortunately (this is a requirement of the RFC, not an implementation issue): .PP .B isnsadm --control --dd-register dd-id=42 \(rs .br .B " member-name=iqn.com.foo member-name=iqn.com.bar .PP The DD ID can be obtained by doing a query for the DD name: .PP .B isnsadm --control --query dd-name=mydomain .PP In management mode, you can also register and deregister nodes and portals manually, in case you want to fix up an inconsisteny in the database. For instance, this will register a node and portal on a host named client.bozo.org: .PP .B isnsadm --control --register entity=client.bozo.org \(rs .br .B " initiator=iqn.org.bozo.client portal=191.168.7.1:860 .PP Note that this registration explicitly specifies the network entity in which to place the new objects. If you omit this, the new objects will be placed in an entity named .BR CONTROL , which is decidedly not what you want. .SH SEE ALSO RFC 4171, .BR isnsd (8), .BR isns_config (5). .SH AUTHORS Olaf Kirch open-iscsi-2.0.873/utils/open-isns/doc/isnsd.8000066400000000000000000000044421175631155400210110ustar00rootroot00000000000000.TH ISNSD 8 "11 May 2007" .SH NAME isnsd \- iSNS server daemon .SH SYNOPSIS .B isnsd .RB [ "\-f" ] .RB [ "\-4" ] .RB [ "\-6" ] .RB [ "\-c \fIfilename" ] .RB [ "\-d \fIdebug-facility" ] .RB [ \--dump-db ] .RB [ \--init ] .SH DESCRIPTION .B Isnsd implements the iSNS protocol as defined in RFC 4171. iSNS is a discovery protocol for iSCSI and iFCP. .SH OPTIONS By default, .B isnsd will take most of its settings from the configuration file .BR /etc/isns/isnsd.conf , with the exception of the following options: .TP .BI \--config " filename\fR, " \-c " filename This option overrides the default configuration file. .TP .BR \--foreground , \-f By default, .B isnsd will put itself into the background. By specifying this option, you can tell it to run in the foreground. Any error messages or debug output will be printed to the console rather than being sent to syslog. .TP .BI \-4 tells .B isnsd to create an IPv4 socket only. Normally, it defaults to IPv6 (which will accept both IPv4 and IPv6 connections). .TP .BI \-6 tells .B isnsd explicitly to create an IPv6 socket only. Since it defaults to IPv6 anyway, this is really a no-op. .TP .BI \--debug " facility\fR, " \-d " facility enables debugging. Valid facilities are .PP .TS tab(,),box,center; lb|lr. socket,network send/receive auth,authentication and security related information message,iSNS protocol layer state,database state scn,SCN (state change notification) messages esi,ESI (entity status inquiry) messages all,all of the above .TE .PP .TP .B \--dump-db This is a helper function that will read the database from the file system, and display it in human readable form. When using this option, .B isnsd will not open any sockets, and terminate immediately after display the database. .IP This option is intended to be used by the administrator when suspecting that the database contains bad/inconsistent information. .TP .B \--init This option will create the server's authentication key, and the required DSA parameters. The private key is stored in the file specified by the .B AuthKey option (usually .BR /etc/isns/auth_key ). The public portion of the key is written to same directory, with the suffix .B .pub appended to the key file name. .SH SEE ALSO RFC 4171, .BR isnsadm (8), .BR isnsdd (8), .BR isns_config (5). .SH AUTHORS Olaf Kirch open-iscsi-2.0.873/utils/open-isns/doc/isnsdd.8000066400000000000000000000040451175631155400211540ustar00rootroot00000000000000.TH ISNSDD 8 "11 May 2007" .SH NAME isnsdd \- iSNS discovery daemon .SH SYNOPSIS .B isnsdd .RB [ "\-f" ] .RB [ "\-c \fIfilename" ] .RB [ "\-d \fIdebug-facility" ] .SH DESCRIPTION .B Isnsdd is a client side daemon for iSNS. It registers storage nodes and portals with the iSNS service, and refreshes these registrations in a timely manner. .PP The daemon also registers itself to receive SCN notifications, and processes these. It can be configured to invoke an external helper application for each status notification received. The path name of the helper application can be specified via the .B SCNCallout option in the configuration file. .SH OPTIONS By default, .B isnsd will take most of its settings from the configuration file .BR /etc/isns/isnsdd.conf , with the addition of the following command line options: .TP .BI \--config " filename\fR, " \-c " filename This option overrides the default configuration file. .TP .BR \--foreground , \-f By default, .B isnsd will put itself into the background. By specifying this option, you can tell it to run in the foreground. Any error messages or debug output will be printed to the console rather than being sent to syslog. .TP .BI \--role " role This tells the discovery daemon in which capacity is should register itself with the iSNS server. .I Role can be either .BR initiator ", or " control . The default is to register as an initiator. .IP Registering target nodes needs to use a different mechanism, as the iSCSI target server needs to inform the discovery daemon about each exported target separately. This is not implemented yet. .TP .BI \--debug " facility\fR, " \-d " facility enables debugging. Valid facilities are .PP .TS tab(,),box,center; lb|lr. socket,network send/receive auth,authentication and security related information message,iSNS protocol layer state,database state scn,SCN (state change notification) messages esi,ESI (entity status inquiry) messages all,all of the above .TE .PP .SH SEE ALSO RFC 4171, .BR isnsd (8), .BR isnsadm (8), .BR isns_config (5). .SH AUTHORS Olaf Kirch open-iscsi-2.0.873/utils/open-isns/domain.c000066400000000000000000000107731175631155400204520ustar00rootroot00000000000000/* * iSNS object model - discovery domain specific code * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "objects.h" #include "util.h" static int __isns_default_dd_rebuild(isns_object_t *obj, isns_db_t *db) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; unsigned int i; isns_object_prune_attrs(obj); isns_db_get_domainless(db, &isns_iscsi_node_template, &list); for (i = 0; i < list.iol_count; ++i) { isns_object_t *node = list.iol_data[i]; const char *name; uint32_t type; if (!isns_object_get_uint32(node, ISNS_TAG_ISCSI_NODE_TYPE, &type)) continue; if (type & ISNS_ISCSI_CONTROL_MASK) continue; if (!isns_object_get_string(node, ISNS_TAG_ISCSI_NAME, &name)) continue; isns_object_set_string(obj, ISNS_TAG_DD_MEMBER_ISCSI_NAME, name); } return ISNS_SUCCESS; } /* * Create the default domain */ isns_object_t * isns_create_default_domain(void) { isns_object_t *obj; obj = isns_create_object(&isns_dd_template, NULL, NULL); if (!obj) return NULL; isns_object_set_uint32(obj, ISNS_TAG_DD_ID, 0); obj->ie_rebuild = __isns_default_dd_rebuild; return obj; } /* * Check object type */ int isns_object_is_dd(const isns_object_t *obj) { return ISNS_IS_DD(obj); } int isns_object_is_ddset(const isns_object_t *obj) { return ISNS_IS_DDSET(obj); } /* * Keep track of DD membership through a bit vector */ int isns_object_mark_membership(isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) obj->ie_membership = isns_bitvector_alloc(); return isns_bitvector_set_bit(obj->ie_membership, id); } int isns_object_test_membership(const isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) return 0; return isns_bitvector_test_bit(obj->ie_membership, id); } int isns_object_clear_membership(isns_object_t *obj, uint32_t id) { if (!obj->ie_membership) return 0; return isns_bitvector_clear_bit(obj->ie_membership, id); } /* * Check whether the two objects share a discovery domain, * and if so, return the DD_ID. * Returns -1 otherwise. */ int isns_object_test_visibility(const isns_object_t *a, const isns_object_t *b) { /* The admin can tell isnsd to put all nodes which are *not* * in any discovery domain, into the so-called default domain */ if (isns_config.ic_use_default_domain && a->ie_template == b->ie_template && isns_bitvector_is_empty(a->ie_membership) && isns_bitvector_is_empty(b->ie_membership)) return 1; return isns_bitvector_intersect(a->ie_membership, b->ie_membership, NULL) >= 0; } /* * Return all visible nodes and portals */ static int __isns_object_vis_callback(uint32_t dd_id, void *ptr) { isns_object_list_t *list = ptr; /* Get all active members */ isns_dd_get_members(dd_id, list, 1); return 0; } void isns_object_get_visible(const isns_object_t *obj, isns_db_t *db, isns_object_list_t *result) { if (isns_bitvector_is_empty(obj->ie_membership)) { /* Get all other nodes not in any DD */ if (isns_config.ic_use_default_domain) isns_db_get_domainless(db, obj->ie_template, result); return; } isns_bitvector_foreach(obj->ie_membership, __isns_object_vis_callback, result); } /* * Object templates */ static uint32_t discovery_domain_attrs[] = { ISNS_TAG_DD_ID, ISNS_TAG_DD_SYMBOLIC_NAME, ISNS_TAG_DD_MEMBER_ISCSI_INDEX, ISNS_TAG_DD_MEMBER_ISCSI_NAME, ISNS_TAG_DD_MEMBER_FC_PORT_NAME, ISNS_TAG_DD_MEMBER_PORTAL_INDEX, ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR, ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT, ISNS_TAG_DD_FEATURES, }; static uint32_t discovery_domain_key_attrs[] = { ISNS_TAG_DD_ID, }; isns_object_template_t isns_dd_template = { .iot_name = "Discovery Domain", .iot_handle = ISNS_OBJECT_TYPE_DD, .iot_attrs = discovery_domain_attrs, .iot_num_attrs = array_num_elements(discovery_domain_attrs), .iot_keys = discovery_domain_key_attrs, .iot_num_keys = array_num_elements(discovery_domain_key_attrs), .iot_index = ISNS_TAG_DD_ID, .iot_next_index = ISNS_TAG_DD_NEXT_ID, }; static uint32_t dd_set_attrs[] = { ISNS_TAG_DD_SET_ID, ISNS_TAG_DD_SET_SYMBOLIC_NAME, ISNS_TAG_DD_SET_STATUS, }; static uint32_t dd_set_key_attrs[] = { ISNS_TAG_DD_SET_ID, }; isns_object_template_t isns_ddset_template = { .iot_name = "Discovery Domain Set", .iot_handle = ISNS_OBJECT_TYPE_DDSET, .iot_attrs = dd_set_attrs, .iot_num_attrs = array_num_elements(dd_set_attrs), .iot_keys = dd_set_key_attrs, .iot_num_keys = array_num_elements(dd_set_key_attrs), .iot_next_index = ISNS_TAG_DD_SET_NEXT_ID, }; open-iscsi-2.0.873/utils/open-isns/entity.c000066400000000000000000000061221175631155400205100ustar00rootroot00000000000000/* * iSNS object model - network entity specific code * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "objects.h" #include "util.h" /* * Create a network entity */ isns_object_t * isns_create_entity(int protocol, const char *name) { isns_object_t *obj; obj = isns_create_object(&isns_entity_template, NULL, NULL); isns_object_set_string(obj, ISNS_TAG_ENTITY_IDENTIFIER, name); isns_object_set_uint32(obj, ISNS_TAG_ENTITY_PROTOCOL, protocol); return obj; } isns_object_t * isns_create_entity_for_source(const isns_source_t *source, const char *eid) { switch (isns_source_type(source)) { case ISNS_TAG_ISCSI_NAME: return isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, eid); case ISNS_TAG_FC_PORT_NAME_WWPN: return isns_create_entity(ISNS_ENTITY_PROTOCOL_IFCP, eid); } return NULL; } const char * isns_entity_name(const isns_object_t *node) { const isns_attr_t *attr; if (node->ie_attrs.ial_count == 0) return NULL; attr = node->ie_attrs.ial_data[0]; if (attr->ia_value.iv_type != &isns_attr_type_string || attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) return NULL; return attr->ia_value.iv_string; } int isns_object_is_entity(const isns_object_t *obj) { return ISNS_IS_ENTITY(obj); } /* * 6.2.4. Entity Registration Timestamp * * This field indicates the most recent time when the Network Entity * registration occurred or when an associated object attribute was * updated or queried by the iSNS client registering the Network Entity. * The time format is, in seconds, the update period since the standard * base time of 00:00:00 GMT on January 1, 1970. This field cannot be * explicitly registered. This timestamp TLV format is also used in * the SCN and ESI messages. * * Implementer's note: we consider any kind of activity from * the client an indication that it is still alive. * Only exception is the pseudo-entity that holds the access control * information; we never assign it a timestamp so it is never subject * to expiry. */ void isns_entity_touch(isns_object_t *obj) { /* Do not add a timestamp to entity CONTROL */ if (obj == NULL || (obj->ie_flags & ISNS_OBJECT_PRIVATE) || obj->ie_template != &isns_entity_template) return; isns_object_set_uint64(obj, ISNS_TAG_TIMESTAMP, time(NULL)); } /* * Object template */ static uint32_t entity_attrs[] = { ISNS_TAG_ENTITY_IDENTIFIER, ISNS_TAG_ENTITY_PROTOCOL, ISNS_TAG_MGMT_IP_ADDRESS, ISNS_TAG_TIMESTAMP, ISNS_TAG_PROTOCOL_VERSION_RANGE, ISNS_TAG_REGISTRATION_PERIOD, ISNS_TAG_ENTITY_INDEX, ISNS_TAG_ENTITY_ISAKMP_PHASE_1, ISNS_TAG_ENTITY_CERTIFICATE, }; static uint32_t entity_key_attrs[] = { ISNS_TAG_ENTITY_IDENTIFIER, }; isns_object_template_t isns_entity_template = { .iot_name = "Network Entity", .iot_handle = ISNS_OBJECT_TYPE_ENTITY, .iot_attrs = entity_attrs, .iot_num_attrs = array_num_elements(entity_attrs), .iot_keys = entity_key_attrs, .iot_num_keys = array_num_elements(entity_key_attrs), .iot_index = ISNS_TAG_ENTITY_INDEX, .iot_next_index = ISNS_TAG_ENTITY_NEXT_INDEX, }; open-iscsi-2.0.873/utils/open-isns/error.c000066400000000000000000000032271175631155400203300ustar00rootroot00000000000000/* * iSNS error strings etc. * * Copyright (C) 2007 Olaf Kirch */ #include "isns.h" const char * isns_strerror(enum isns_status status) { switch (status) { case ISNS_SUCCESS: return "Success"; case ISNS_UNKNOWN_ERROR: return "Unknown error"; case ISNS_MESSAGE_FORMAT_ERROR: return "Message format error"; case ISNS_INVALID_REGISTRATION: return "Invalid registration"; case ISNS_INVALID_QUERY: return "Invalid query"; case ISNS_SOURCE_UNKNOWN: return "Source unknown"; case ISNS_SOURCE_ABSENT: return "Source absent"; case ISNS_SOURCE_UNAUTHORIZED: return "Source unauthorized"; case ISNS_NO_SUCH_ENTRY: return "No such entry"; case ISNS_VERSION_NOT_SUPPORTED: return "Version not supported"; case ISNS_INTERNAL_ERROR: return "Internal error"; case ISNS_BUSY: return "Busy"; case ISNS_OPTION_NOT_UNDERSTOOD: return "Option not understood"; case ISNS_INVALID_UPDATE: return "Invalid update"; case ISNS_MESSAGE_NOT_SUPPORTED: return "Message not supported"; case ISNS_SCN_EVENT_REJECTED: return "SCN event rejected"; case ISNS_SCN_REGISTRATION_REJECTED: return "SCN registration rejected"; case ISNS_ATTRIBUTE_NOT_IMPLEMENTED: return "Attribute not implemented"; case ISNS_FC_DOMAIN_ID_NOT_AVAILABLE: return "FC domain id not available"; case ISNS_FC_DOMAIN_ID_NOT_ALLOCATED: return "FC domain id not allocated"; case ISNS_ESI_NOT_AVAILABLE: return "ESI not available"; case ISNS_INVALID_DEREGISTRATION: return "Invalid deregistration"; case ISNS_REGISTRATION_FEATURE_NOT_SUPPORTED: return "Registration feature not supported"; default: break; } return "Unknown iSNS status code"; } open-iscsi-2.0.873/utils/open-isns/esi.c000066400000000000000000000334141175631155400177600ustar00rootroot00000000000000/* * Handle ESI events * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" #define ESI_RETRANS_TIMEOUT 60 typedef struct isns_esi isns_esi_t; typedef struct isns_esi_portal isns_esi_portal_t; struct isns_esi { isns_list_t esi_list; isns_object_t * esi_object; isns_list_t esi_portals; unsigned int esi_update : 1; }; struct isns_esi_portal { isns_list_t esp_list; isns_object_t * esp_object; isns_portal_info_t esp_portal; unsigned int esp_interval; isns_portal_info_t esp_dest; isns_socket_t * esp_socket; unsigned int esp_retries; unsigned int esp_timeout; time_t esp_start; time_t esp_next_xmit; uint32_t esp_xid; }; int isns_esi_enabled = 0; static isns_server_t * isns_esi_server = NULL; static ISNS_LIST_DECLARE(isns_esi_list); static void isns_esi_transmit(void *); static void isns_esi_sendto(isns_esi_t *, isns_esi_portal_t *); static void isns_process_esi_response(uint32_t, int, isns_simple_t *); static void isns_esi_disconnect(isns_esi_portal_t *); static void isns_esi_restart(isns_esi_portal_t *); static void isns_esi_drop_portal(isns_esi_portal_t *, isns_db_t *, int); static void isns_esi_drop_entity(isns_esi_t *, isns_db_t *, int); static int isns_esi_update(isns_esi_t *); static void isns_esi_schedule(int); static void isns_esi_callback(const isns_db_event_t *, void *); void isns_esi_init(isns_server_t *srv) { if (isns_config.ic_esi_retries == 0) { isns_debug_esi("ESI disabled by administrator\n"); } else { unsigned int max_interval; isns_register_callback(isns_esi_callback, NULL); isns_esi_schedule(0); max_interval = isns_config.ic_registration_period / 2; if (isns_config.ic_esi_max_interval > max_interval) { isns_warning("Max ESI interval adjusted to %u sec " "to match registration period\n", max_interval); isns_config.ic_esi_max_interval = max_interval; if (isns_config.ic_esi_min_interval > max_interval) isns_config.ic_esi_min_interval = max_interval; } isns_esi_server = srv; isns_esi_enabled = 1; } } /* * Timer callback to send out ESI messages. */ void isns_esi_transmit(void *ptr) { isns_db_t *db = isns_esi_server->is_db; isns_list_t *esi_pos, *esi_next; time_t now; isns_object_t *obj; time_t next_timeout; now = time(NULL); next_timeout = now + 3600; isns_list_foreach(&isns_esi_list, esi_pos, esi_next) { isns_list_t *esp_pos, *esp_next; isns_esi_t *esi = isns_list_item(isns_esi_t, esi_list, esi_pos); if (esi->esi_update) { esi->esi_update = 0; if (!isns_esi_update(esi)) continue; } isns_list_foreach(&esi->esi_portals, esp_pos, esp_next) { isns_esi_portal_t *esp = isns_list_item(isns_esi_portal_t, esp_list, esp_pos); /* Check whether the portal object still exist */ obj = esp->esp_object; if (obj->ie_state != ISNS_OBJECT_STATE_MATURE) { isns_esi_drop_portal(esp, db, 0); continue; } if (esp->esp_next_xmit <= now) { if (esp->esp_retries == 0) { isns_debug_esi("No ESI response from %s - dropping\n", isns_portal_string(&esp->esp_dest)); isns_esi_drop_portal(esp, db, 1); continue; } esp->esp_retries -= 1; esp->esp_next_xmit = now + esp->esp_timeout; isns_esi_sendto(esi, esp); } if (esp->esp_next_xmit < next_timeout) next_timeout = esp->esp_next_xmit; } if (isns_list_empty(&esi->esi_portals)) isns_esi_drop_entity(esi, db, 1); } isns_debug_esi("Next ESI message in %d seconds\n", next_timeout - now); isns_esi_schedule(next_timeout - now); } /* * Send an ESI message */ void isns_esi_sendto(isns_esi_t *esi, isns_esi_portal_t *esp) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_socket_t *sock; isns_simple_t *msg; /* For TCP portals, kill the TCP socket every time. */ if (esp->esp_dest.proto == IPPROTO_TCP) isns_esi_disconnect(esp); if (esp->esp_socket == NULL) { sock = isns_connect_to_portal(&esp->esp_dest); if (sock == NULL) return; isns_socket_set_security_ctx(sock, isns_default_security_context(0)); /* sock->is_disconnect_fatal = 1; */ esp->esp_socket = sock; } isns_attr_list_append_uint64(&attrs, ISNS_TAG_TIMESTAMP, time(NULL)); /* The following will extract the ENTITY IDENTIFIER */ isns_object_extract_keys(esi->esi_object, &attrs); isns_portal_to_attr_list(&esp->esp_portal, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, &attrs); msg = isns_simple_create(ISNS_ENTITY_STATUS_INQUIRY, NULL, &attrs); if (msg == NULL) return; isns_debug_esi("*** Sending ESI message to %s (xid=0x%x); %u retries left\n", isns_portal_string(&esp->esp_dest), msg->is_xid, esp->esp_retries); isns_simple_transmit(esp->esp_socket, msg, NULL, esp->esp_timeout - 1, isns_process_esi_response); esp->esp_xid = msg->is_xid; isns_simple_free(msg); } /* * A new entity was added. See if it uses ESI, and create * portals and such. */ static void isns_esi_add_entity(isns_object_t *obj) { isns_esi_t *esi; isns_debug_esi("Enable ESI monitoring for entity %u\n", obj->ie_index); esi = isns_calloc(1, sizeof(*esi)); esi->esi_object = isns_object_get(obj); esi->esi_update = 1; isns_list_init(&esi->esi_list); isns_list_init(&esi->esi_portals); isns_list_append(&isns_esi_list, &esi->esi_list); } /* * Given an entity, see if we can find ESI state for it. */ static isns_esi_t * isns_esi_find(isns_object_t *obj) { isns_list_t *pos, *next; isns_list_foreach(&isns_esi_list, pos, next) { isns_esi_t *esi = isns_list_item(isns_esi_t, esi_list, pos); if (esi->esi_object == obj) return esi; } return NULL; } /* * Update the ESI state after an entity has changed */ static int isns_esi_update(isns_esi_t *esi) { isns_object_t *entity = esi->esi_object; ISNS_LIST_DECLARE(hold); isns_esi_portal_t *esp; unsigned int i; isns_debug_esi("Updating ESI state for entity %u\n", entity->ie_index); isns_list_move(&hold, &esi->esi_portals); for (i = 0; i < entity->ie_children.iol_count; ++i) { isns_object_t *child = entity->ie_children.iol_data[i]; isns_portal_info_t esi_portal, portal_info; uint32_t esi_interval; isns_list_t *pos, *next; int changed = 0; if (!ISNS_IS_PORTAL(child)) continue; if (!isns_portal_from_object(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, child) || !isns_portal_from_object(&esi_portal, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_ESI_PORT, child) || !isns_object_get_uint32(child, ISNS_TAG_ESI_INTERVAL, &esi_interval)) continue; isns_list_foreach(&hold, pos, next) { esp = isns_list_item(isns_esi_portal_t, esp_list, pos); if (esp->esp_object == child) { isns_debug_esi("Updating ESI state for %s\n", isns_portal_string(&portal_info)); isns_list_del(&esp->esp_list); goto update; } } isns_debug_esi("Creating ESI state for %s\n", isns_portal_string(&portal_info)); esp = isns_calloc(1, sizeof(*esp)); esp->esp_object = isns_object_get(child); isns_list_init(&esp->esp_list); changed = 1; update: if (!isns_portal_equal(&esp->esp_portal, &portal_info)) { esp->esp_portal = portal_info; changed++; } if (!isns_portal_equal(&esp->esp_dest, &esi_portal)) { isns_esi_disconnect(esp); esp->esp_dest = esi_portal; changed++; } if (esp->esp_interval != esi_interval) { esp->esp_interval = esi_interval; changed++; } isns_esi_restart(esp); isns_list_append(&esi->esi_portals, &esp->esp_list); } /* Destroy any old ESI portals */ while (!isns_list_empty(&hold)) { esp = isns_list_item(isns_esi_portal_t, esp_list, hold.next); isns_esi_drop_portal(esp, NULL, 0); } /* If the client explicitly unregistered all ESI portals, * stop monitoring it but *without* destroying the entity. */ if (isns_list_empty(&esi->esi_portals)) { isns_esi_drop_entity(esi, NULL, 0); return 0; } return 1; } void isns_esi_restart(isns_esi_portal_t *esp) { unsigned int timeo; isns_esi_disconnect(esp); esp->esp_start = time(NULL); esp->esp_retries = isns_config.ic_esi_retries; esp->esp_next_xmit = esp->esp_start + esp->esp_interval; esp->esp_xid = 0; timeo = esp->esp_interval / esp->esp_retries; if (timeo == 0) timeo = 1; else if (timeo > ESI_RETRANS_TIMEOUT) timeo = ESI_RETRANS_TIMEOUT; esp->esp_timeout = timeo; } void isns_esi_disconnect(isns_esi_portal_t *esp) { if (esp->esp_socket) isns_socket_free(esp->esp_socket); esp->esp_socket = NULL; } /* * Generic wrapper to dropping an object */ static inline void __isns_esi_drop_object(isns_db_t *db, isns_object_t *obj, unsigned int dead) { if (db && obj && obj->ie_state == ISNS_OBJECT_STATE_MATURE && dead) isns_db_remove(db, obj); isns_object_release(obj); } /* * Portal did not respond in time. Drop it */ void isns_esi_drop_portal(isns_esi_portal_t *esp, isns_db_t *db, int dead) { isns_debug_esi("ESI: dropping portal %s\n", isns_portal_string(&esp->esp_portal)); isns_list_del(&esp->esp_list); isns_esi_disconnect(esp); __isns_esi_drop_object(db, esp->esp_object, dead); isns_free(esp); } /* * We ran out of ESI portals for this entity. */ void isns_esi_drop_entity(isns_esi_t *esi, isns_db_t *db, int dead) { isns_debug_esi("ESI: dropping entity %u\n", esi->esi_object->ie_index); isns_list_del(&esi->esi_list); __isns_esi_drop_object(db, esi->esi_object, dead); while (!isns_list_empty(&esi->esi_portals)) { isns_esi_portal_t *esp; esp = isns_list_item(isns_esi_portal_t, esp_list, esi->esi_portals.next); isns_esi_drop_portal(esp, db, dead); } isns_free(esi); } /* * When receiving an ESI response, find the portal we sent the * original message to. */ static isns_esi_portal_t * isns_esi_get_msg_portal(uint32_t xid, isns_esi_t **esip) { isns_list_t *esi_pos, *esi_next; isns_list_foreach(&isns_esi_list, esi_pos, esi_next) { isns_esi_t *esi = isns_list_item(isns_esi_t, esi_list, esi_pos); isns_list_t *esp_pos, *esp_next; isns_list_foreach(&esi->esi_portals, esp_pos, esp_next) { isns_esi_portal_t *esp = isns_list_item(isns_esi_portal_t, esp_list, esp_pos); if (esp->esp_xid == xid) { *esip = esi; return esp; } } } return NULL; } /* * Handle incoming ESI request */ int isns_process_esi(isns_server_t *srv, isns_simple_t *call, isns_simple_t **reply) { const isns_attr_list_t *attrs = &call->is_message_attrs; isns_object_t *portal = NULL; /* We just echo back the attributes sent to us by the server, * without further checking. */ *reply = isns_simple_create(ISNS_ENTITY_STATUS_INQUIRY, srv->is_source, attrs); /* Look up the portal and update its mtime. * This can help the application find out if a portal has * seen ESIs recently, and react. */ if (srv->is_db && attrs->ial_count == 4) { const isns_attr_t *addr_attr, *port_attr; addr_attr = attrs->ial_data[2]; port_attr = attrs->ial_data[3]; if (addr_attr->ia_tag_id == ISNS_TAG_PORTAL_IP_ADDRESS && port_attr->ia_tag_id == ISNS_TAG_PORTAL_TCP_UDP_PORT) { isns_attr_list_t key; key.ial_count = 2; key.ial_data = attrs->ial_data + 2; portal = isns_db_lookup(srv->is_db, &isns_portal_template, &key); } if (portal) portal->ie_mtime = time(NULL); } return ISNS_SUCCESS; } void isns_process_esi_response(uint32_t xid, int status, isns_simple_t *msg) { isns_portal_info_t portal_info; isns_esi_portal_t *esp; isns_esi_t *esi; if (msg == NULL) { isns_debug_esi("ESI call 0x%x timed out\n", xid); return; } /* FIXME: As a matter of security, we should probably * verify that the ESI response originated from the * portal we sent it to; or at least that it was authenticated * by the client we think we're talking to. */ /* Get the portal */ if (!isns_portal_from_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, &msg->is_message_attrs)) { isns_debug_esi("Ignoring unintelligible ESI response\n"); return; } if (!(esp = isns_esi_get_msg_portal(xid, &esi))) { isns_debug_esi("Ignoring unmatched ESI reply\n"); return; } if (!isns_portal_equal(&esp->esp_portal, &portal_info)) { isns_warning("Faked ESI response for portal %s\n", isns_portal_string(&portal_info)); return; } isns_debug_esi("Good ESI response from %s\n", isns_portal_string(&portal_info)); isns_esi_restart(esp); /* Refresh the entity's registration timestamp */ isns_object_set_uint64(esi->esi_object, ISNS_TAG_TIMESTAMP, time(NULL)); isns_db_sync(isns_esi_server->is_db); } /* * Helper function to schedule the next timeout */ static void isns_esi_schedule(int timeout) { isns_cancel_timer(isns_esi_transmit, NULL); isns_add_oneshot_timer(timeout, isns_esi_transmit, NULL); } /* * Register an entity for ESI monitoring. * This is called when reloading the database. */ void isns_esi_register(isns_object_t *obj) { if (!isns_esi_find(obj)) isns_esi_add_entity(obj); /* We do not call esi_schedule(0) here; that happens in * isns_esi_init already. */ } /* * This callback is invoked whenever an object is added/removed/modified. * We use this to keep track of ESI portals and such. */ void isns_esi_callback(const isns_db_event_t *ev, void *ptr) { isns_object_t *obj, *entity; isns_esi_t *esi; uint32_t event; obj = ev->ie_object; event = ev->ie_bits; if (obj->ie_flags & ISNS_OBJECT_PRIVATE) return; isns_debug_esi("isns_esi_callback(%p, 0x%x)\n", obj, event); if (ISNS_IS_ENTITY(obj) && (event & ISNS_SCN_OBJECT_ADDED_MASK)) { if (!isns_esi_find(obj)) isns_esi_add_entity(obj); /* Schedule an immediate ESI timer run */ isns_esi_schedule(0); return; } if (!(entity = isns_object_get_entity(obj))) return; esi = isns_esi_find(entity); if (esi != NULL) esi->esi_update = 1; /* Schedule an immediate ESI timer run */ isns_esi_schedule(0); } open-iscsi-2.0.873/utils/open-isns/etc/000077500000000000000000000000001175631155400176025ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/etc/isnsadm.conf000066400000000000000000000037201175631155400221110ustar00rootroot00000000000000# # Sample iSNS client configuration file # # The source name. This is an iSCSI qualified name, # and identifies the client uniquely. # # If left empty, the source name is derived from # the client's hostname. # #SourceName = iqn.2006-01.com.example.host1 # Name and port of the iSNS server. # Possible formats: # foo.example.com # foo.example.com:3205 # 192.168.1.7:isns # [2001:4e5f::1]:isns # SLP: # If the special string "SLP:" is given, Open-iSNS will # query the SLP directory service to find the iSNS server. #ServerAddress = isns.example.com # Authentication enable/disable. # When set to 1, the client will sign # all messages, and expect all server messages # to be signed. # # Authentication requires a valid private DSA # key in AuthKeyFile, and the server's DSA public # key in ServerKeyFile. # # The default is to use authentication if the # requires keys are installed, and use unauthenticated # iSNS otherwise. #Security = 1 # Location of the client's private key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/auth_key #AuthKeyFile = /etc/isns/auth_key # Location of the servers's public key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/server_key.pub #ServerKeyFile = /etc/isns/server_key.pub # In order to prevent replay attacks, the # authentication blocks carried by iSNS # include a time stamp. The following two # parameters control how we verify the # time stamp Auth.ReplayWindow = 2m Auth.TimeStampJitter = 1s # Maximum number of incoming connections # accepted. This usually applies to server # side only, but is relevant if you create # a passive TCP socket for ESI or SCN. # Network.MaxSockets = 1024 # Time to wait for a TCP connection to be # established. # Network.ConnectTimeout = 60 # When a connection attempt failed, we wait # before we try connecting again. # Network.ReonnectTimeout = 10 # Total amount of time to wait before timing # out a call to the iSNS server. # Network.CallTimeout = 60 open-iscsi-2.0.873/utils/open-isns/etc/isnsd.conf000066400000000000000000000072741175631155400216030ustar00rootroot00000000000000# # Sample iSNS Server configuration file # # The source name. This is an iSCSI qualified name, # and identifies the client uniquely. # # If left empty, the source name is derived from # the client's hostname. # #SourceName = iqn.2006-01.com.example.host1 # Where to store the database. # If you leave this empty, isnsd will keep its # database in memory. # Setting this to an absolute path name will # make isnsd keep its database in a directory # hierarchy below that directory. Database = /var/lib/isns # The iSNS server can purge registered entities # after a certain period of inactivity. This is # called the registration period. # Clients who register objects are supposed to # refresh their registration within this period. # # The default value is 0, which disables this # feature. RegistrationPeriod = 10m # iSNS scopes visibility of other nodes using so-called # Discovery Domains. A storage node A will only "see" # storage node B, if both are members of the same # discovery domain. # # So if a storage node is registered which is not part of # any discovery domain, it will not see any other nodes. # # By setting DefaultDiscoveryDomain=1, you can tell isnsd to # create a virtual "default discovery domain", which # holds all nodes that are not part of any administratively # configured discovery domain. DefaultDiscoveryDomain = 1 # Make the iSNS server register itself with SLP. # Clients will be able to discover the server by # querying for service type "iscsi:sms", and a query # of "(protocols=isns)" SLPRegister = 1 # Authentication enable/disable. # When set to 1, the client will sign # all messages, and expect all server messages # to be signed. # # Authentication requires a valid private DSA # key in AuthKeyFile, and the server's DSA public # key in ServerKeyFile. # # The default is to use authentication if the # requires keys are installed, and use unauthenticated # iSNS otherwise. #Security = 1 # Location of the client's private key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/auth_key #AuthKeyFile = /etc/isns/auth_key # Location of the servers's public key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/server_key.pub #ServerKeyFile = /etc/isns/server_key.pub # This describes where the iSNS server stores # authentication keys and policy information. # Two options are currently supported: a # simple key store (flat directory with public # keys in PEM encoded files), and the iSNS # database itself #ClientKeyStore = /etc/isns/keystores ClientKeyStore = DB: # When transmitting State Change Notification, # we expect the client to ack them. If the # ACK doesn't arrive in due time, we retransmit # for a limited number of attempts, cycling # through the available portals. SCNTimeout = 60 SCNRetries = 3 # Configuration of ESI. # Defaults are # ESIMaxInterval = 1h # ESIMinInterval = 60s # ESIRetries = 3 # Setting ESIRetries to 0 disables ESI support, and makes # the server reject any portal registrations that specify # an ESI portal. ESIMinInterval = 1m ESIMaxInterval = 2m ESIRetries = 3 # In order to prevent replay attacks, the # authentication blocks carried by iSNS # include a time stamp. The following two # parameters control how we verify the # time stamp Auth.ReplayWindow = 2m Auth.TimeStampJitter = 1s # Maximum number of incoming connections # accepted. # Network.MaxSockets = 1024 # Time to wait for a TCP connection to be # established. # (Client only) # Network.ConnectTimeout = 60 # When a connection attempt failed, we wait # before we try connecting again. # (Client only) # Network.ReonnectTimeout = 10 # Total amount of time to wait before timing # out a call to the iSNS server. # (Client only) # Network.CallTimeout = 60 open-iscsi-2.0.873/utils/open-isns/etc/isnsdd.conf000066400000000000000000000037411175631155400217420ustar00rootroot00000000000000# # Sample iSNS Discovery Daemon configuration file # # The source name. This is an iSCSI qualified name, # and identifies the client uniquely. # # If left empty, the source name is derived from # the client's hostname. # #SourceName = iqn.2006-01.com.example.host1:monitor # Name and port of the iSNS server. # Possible formats: # foo.example.com # foo.example.com:3205 # 192.168.1.7:isns # [2001:4e5f::1]:isns # SLP: # If the special string "SLP:" is given, Open-iSNS will # query the SLP directory service to find the iSNS server. #ServerAddress = isns.example.com # Authentication enable/disable. # When set to 1, the client will sign # all messages, and expect all server messages # to be signed. # # Authentication requires a valid private DSA # key in AuthKeyFile, and the server's DSA public # key in ServerKeyFile. # # The default is to use authentication if the # required keys are installed, and use unauthenticated # iSNS otherwise. #Security = 1 # Location of the client's private key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/auth_key #AuthKeyFile = /etc/isns/auth_key # Location of the servers's public key. # The file must contain a PEM encoded DSA key. # The default is /etc/isns/server_key.pub #ServerKeyFile = /etc/isns/server_key.pub # In order to prevent replay attacks, the # authentication blocks carried by iSNS # include a time stamp. The following two # parameters control how we verify the # time stamp Auth.ReplayWindow = 2m Auth.TimeStampJitter = 1s # Maximum number of incoming connections # accepted. This usually applies to server # side only, but is relevant if you create # a passive TCP socket for ESI or SCN. # Network.MaxSockets = 1024 # Time to wait for a TCP connection to be # established. # Network.ConnectTimeout = 60 # When a connection attempt failed, we wait # before we try connecting again. # Network.ReonnectTimeout = 10 # Total amount of time to wait before timing # out a call to the iSNS server. # Network.CallTimeout = 60 open-iscsi-2.0.873/utils/open-isns/etc/openisns.init000066400000000000000000000021201175631155400223200ustar00rootroot00000000000000#!/bin/sh # # Init script for Open-iSNS. # # Copyright (C) 2007 Albert Pauw # # chkconfig: 345 13 89 # description: Starts and stops the iSCSI isns server # # processname: isnsd # pidfile: /var/run/isnsd.pid # config: /etc/isns/isnsd.conf # Source function library. . /etc/init.d/functions PATH=/sbin:/bin:/usr/sbin:/usr/bin #OPTIONS="-4 -d all" CONFIG="-c /etc/isns/isnsd.conf" RETVAL=0 start() { echo -n "Starting iSCSI isns service: " daemon isnsd $OPTIONS $CONFIG RETVAL=$? success echo [ $RETVAL -eq 0 ] || return touch /var/lock/subsys/open-isns } stop() { echo -n "Stopping iSCSI isns service: " killproc isnsd [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/open-isns success echo } restart() { stop start } case "$1" in start) start ;; stop) stop ;; restart) restart ;; status) status isnsd RETVAL=$? ;; condrestart) [ -f /var/lock/subsys/open-isns ] && restart ;; *) echo $"Usage: $0 {start|stop|restart|status|condrestart}" exit 1 esac exit $RETVAL open-iscsi-2.0.873/utils/open-isns/export.c000066400000000000000000000307011175631155400205150ustar00rootroot00000000000000/* * Helper functions to represent iSNS objects as text, * and/or to parse objects represented in textual form. * These functions can be used by command line utilities * such as isnsadm, as well as applications like iscsid * or stgtd when talking to the iSNS discovery daemon. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include "isns.h" #include "util.h" #include "vendor.h" #include "attrs.h" #include "security.h" #include "objects.h" #include "paths.h" #define MAX_ALIASES 4 struct isns_tag_prefix { const char * name; unsigned int name_len; isns_object_template_t *context; }; struct tag_name { const char * name; uint32_t tag; struct isns_tag_prefix *prefix; const char * alias[MAX_ALIASES]; }; static struct isns_tag_prefix all_prefixes[__ISNS_OBJECT_TYPE_MAX] = { [ISNS_OBJECT_TYPE_ENTITY] = { "entity-", 7, &isns_entity_template }, [ISNS_OBJECT_TYPE_NODE] = { "iscsi-", 6, &isns_iscsi_node_template }, [ISNS_OBJECT_TYPE_PORTAL] = { "portal-", 7, &isns_portal_template }, [ISNS_OBJECT_TYPE_PG] = { "pg-", 3, &isns_iscsi_pg_template }, [ISNS_OBJECT_TYPE_DD] = { "dd-", 3, &isns_dd_template }, [ISNS_OBJECT_TYPE_POLICY] = { "policy-", 7, &isns_policy_template }, }; static struct tag_name all_attrs[] = { { "id", ISNS_TAG_ENTITY_IDENTIFIER, .alias = { "eid", }, }, { "prot", ISNS_TAG_ENTITY_PROTOCOL }, { "idx", ISNS_TAG_ENTITY_INDEX }, { "name", ISNS_TAG_ISCSI_NAME }, { "node-type", ISNS_TAG_ISCSI_NODE_TYPE }, { "alias", ISNS_TAG_ISCSI_ALIAS }, { "authmethod", ISNS_TAG_ISCSI_AUTHMETHOD }, { "idx", ISNS_TAG_ISCSI_NODE_INDEX }, { "addr", ISNS_TAG_PORTAL_IP_ADDRESS }, { "port", ISNS_TAG_PORTAL_TCP_UDP_PORT }, { "name", ISNS_TAG_PORTAL_SYMBOLIC_NAME }, { "esi-port", ISNS_TAG_ESI_PORT }, { "esi-interval", ISNS_TAG_ESI_INTERVAL }, { "scn-port", ISNS_TAG_SCN_PORT }, { "idx", ISNS_TAG_PORTAL_INDEX }, { "name", ISNS_TAG_PG_ISCSI_NAME }, { "addr", ISNS_TAG_PG_PORTAL_IP_ADDR }, { "port", ISNS_TAG_PG_PORTAL_TCP_UDP_PORT }, { "tag", ISNS_TAG_PG_TAG }, { "pgt", ISNS_TAG_PG_TAG }, { "idx", ISNS_TAG_PG_INDEX }, { "id", ISNS_TAG_DD_ID }, { "name", ISNS_TAG_DD_SYMBOLIC_NAME }, { "member-name", ISNS_TAG_DD_MEMBER_ISCSI_NAME }, { "member-iscsi-idx", ISNS_TAG_DD_MEMBER_ISCSI_INDEX }, { "member-fc-name", ISNS_TAG_DD_MEMBER_FC_PORT_NAME }, { "member-portal-idx", ISNS_TAG_DD_MEMBER_PORTAL_INDEX }, { "member-addr", ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR }, { "member-port", ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT }, { "features", ISNS_TAG_DD_FEATURES }, { "name", OPENISNS_TAG_POLICY_SPI, .alias = { "spi" }, }, { "key", OPENISNS_TAG_POLICY_KEY }, { "entity", OPENISNS_TAG_POLICY_ENTITY }, { "object-type", OPENISNS_TAG_POLICY_OBJECT_TYPE }, { "node-type", OPENISNS_TAG_POLICY_NODE_TYPE }, { "node-name", OPENISNS_TAG_POLICY_NODE_NAME }, { "functions", OPENISNS_TAG_POLICY_FUNCTIONS }, { NULL } }; /* * Initialize tag array */ static void init_tags(void) { struct tag_name *t; for (t = all_attrs; t->name; ++t) { isns_object_template_t *tmpl; tmpl = isns_object_template_for_tag(t->tag); if (tmpl == NULL) isns_fatal("Bug: cannot find object type for tag %s\n", t->name); t->prefix = &all_prefixes[tmpl->iot_handle]; } } /* * Match prefix */ static struct isns_tag_prefix * find_prefix(const char *name) { struct isns_tag_prefix *p; unsigned int i; for (i = 0, p = all_prefixes; i < __ISNS_OBJECT_TYPE_MAX; ++i, ++p) { if (p->name && !strncmp(name, p->name, p->name_len)) return p; } return NULL; } /* * Look up the tag for a given attribute name. * By default, attr names come with a disambiguating * prefix that defines the object type the attribute applies * to, such as "entity-" or "portal-". Once a context has * been established (ie we know the object type subsequent * attributes apply to), specifying the prefix is optional. * * For instance, in a portal context, "addr=10.1.1.1 port=616 name=foo" * specifies three portal related attributes. Whereas in a portal * group context, the same string would specify three portal group * related attributes. To disambiguate, the first attribute in * this list should be prefixed by "portal-" or "pg-", respectively. */ static uint32_t tag_by_name(const char *name, struct isns_attr_list_parser *st) { const char *orig_name = name; unsigned int nmatch = 0, i; struct tag_name *t, *match[8]; struct isns_tag_prefix *specific = NULL; if (all_attrs[0].prefix == NULL) init_tags(); specific = find_prefix(name); if (specific != NULL) { if (st->prefix && st->prefix != specific && !st->multi_type_permitted) { isns_error("Cannot mix attributes of different types\n"); return 0; } name += specific->name_len; st->prefix = specific; } for (t = all_attrs; t->name; ++t) { if (specific && t->prefix != specific) continue; if (!st->multi_type_permitted && st->prefix && t->prefix != st->prefix) continue; if (!strcmp(name, t->name)) goto match; for (i = 0; i < MAX_ALIASES && t->alias[i]; ++i) { if (!strcmp(name, t->alias[i])) goto match; } continue; match: if (nmatch < 8) match[nmatch++] = t; } if (nmatch > 1) { char conflict[128]; unsigned int i; conflict[0] = '\0'; for (i = 0; i < nmatch; ++i) { if (i) strcat(conflict, ", "); t = match[i]; strcat(conflict, t->prefix->name); strcat(conflict, t->name); } isns_error("tag name \"%s\" not unique in this context " "(could be one of %s)\n", orig_name, conflict); return 0; } if (nmatch == 0) { isns_error("tag name \"%s\" not known in this context\n", orig_name); return 0; } st->prefix = match[0]->prefix; return match[0]->tag; } static const char * name_by_tag(uint32_t tag, struct isns_attr_list_parser *st) { struct tag_name *t; for (t = all_attrs; t->name; ++t) { if (st->prefix && t->prefix != st->prefix) continue; if (t->tag == tag) return t->name; } return NULL; } static int parse_one_attr(const char *name, const char *value, isns_attr_list_t *attrs, struct isns_attr_list_parser *st) { isns_attr_t *attr; uint32_t tag; /* Special case: "portal=" is translated to * addr=
port= * If no context has been set, assume portal context. */ if (!strcasecmp(name, "portal")) { isns_portal_info_t portal_info; uint32_t addr_tag, port_tag; if (st->prefix == NULL) { addr_tag = tag_by_name("portal-addr", st); port_tag = tag_by_name("portal-port", st); } else { addr_tag = tag_by_name("addr", st); port_tag = tag_by_name("port", st); } if (!addr_tag || !port_tag) { isns_error("portal=... not supported in this context\n"); return 0; } if (value == NULL) { isns_attr_list_append_nil(attrs, addr_tag); isns_attr_list_append_nil(attrs, port_tag); return 1; } if (!isns_portal_parse(&portal_info, value, st->default_port)) return 0; isns_portal_to_attr_list(&portal_info, addr_tag, port_tag, attrs); return 1; } if (!(tag = tag_by_name(name, st))) return 0; /* Special handling for key objects */ if (tag == OPENISNS_TAG_POLICY_KEY) { if (!value || !strcasecmp(value, "gen")) { if (st->generate_key == NULL) { isns_error("Key generation not supported in this context\n"); return 0; } attr = st->generate_key(); } else { if (st->load_key == NULL) { isns_error("Policy-key attribute not supported in this context\n"); return 0; } attr = st->load_key(value); } goto append_attr; } if (value == NULL) { isns_attr_list_append_nil(attrs, tag); return 1; } attr = isns_attr_from_string(tag, value); if (!attr) return 0; append_attr: isns_attr_list_append_attr(attrs, attr); return 1; } void isns_attr_list_parser_init(struct isns_attr_list_parser *st, isns_object_template_t *tmpl) { if (all_attrs[0].prefix == NULL) init_tags(); memset(st, 0, sizeof(*st)); if (tmpl) st->prefix = &all_prefixes[tmpl->iot_handle]; } int isns_attr_list_split(char *line, char **argv, unsigned int argc_max) { char *src = line; unsigned int argc = 0, quoted = 0; if (!line) return 0; while (1) { char *dst; while (isspace(*src)) ++src; if (!*src) break; argv[argc] = dst = src; while (*src) { char cc = *src++; if (cc == '"') { quoted = !quoted; continue; } if (!quoted && isspace(cc)) { *dst = '\0'; break; } *dst++ = cc; } if (quoted) { isns_error("%s: Unterminated quoted string: \"%s\"\n", __FUNCTION__, argv[argc]); return -1; } argc++; } return argc; } int isns_parse_attrs(unsigned int argc, char **argv, isns_attr_list_t *attrs, struct isns_attr_list_parser *st) { unsigned int i; for (i = 0; i < argc; ++i) { char *name, *value; name = argv[i]; if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; if (!value && !st->nil_permitted) { isns_error("Missing value for atribute %s\n", name); return 0; } if (!parse_one_attr(name, value, attrs, st)) { isns_error("Unable to parse %s=%s\n", name, value); return 0; } } return 1; } /* * Query strings may contain a mix of query keys (foo=bar), * and requested attributes (?foo). The former are used by * the server in its object search, whereas the latter instruct * it which attributes to return. */ int isns_parse_query_attrs(unsigned int argc, char **argv, isns_attr_list_t *keys, isns_attr_list_t *requested_attrs, struct isns_attr_list_parser *st) { struct isns_attr_list_parser query_state; unsigned int i; query_state = *st; query_state.multi_type_permitted = 1; for (i = 0; i < argc; ++i) { char *name, *value; name = argv[i]; if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; if (name[0] == '?') { uint32_t tag; if (value) { isns_error("No value allowed for query attribute %s\n", name); return 0; } if ((tag = tag_by_name(name + 1, &query_state)) != 0) { isns_attr_list_append_nil(requested_attrs, tag); continue; } } else { if (!value && !st->nil_permitted) { isns_error("Missing value for atribute %s\n", name); return 0; } if (parse_one_attr(name, value, keys, st)) continue; } isns_error("Unable to parse %s=%s\n", name, value); return 0; } return 1; } void isns_attr_list_parser_help(struct isns_attr_list_parser *st) { isns_object_template_t *tmpl, *current = NULL; struct tag_name *t; if (all_attrs[0].prefix == NULL) init_tags(); for (t = all_attrs; t->name; ++t) { const isns_tag_type_t *tag_type; char namebuf[64]; const char *help; unsigned int i; if (st && !st->multi_type_permitted && st->prefix && t->prefix != st->prefix) continue; tmpl = t->prefix->context; if (tmpl != current) { printf("\nAttributes for object type %s; using prefix %s\n", tmpl->iot_name, t->prefix->name); current = tmpl; } snprintf(namebuf, sizeof(namebuf), "%s%s", t->prefix->name, t->name); printf(" %-20s ", namebuf); tag_type = isns_tag_type_by_id(t->tag); if (tag_type == NULL) { printf("Unknown\n"); continue; } printf("%s (%s", tag_type->it_name, tag_type->it_type->it_name); if (tag_type->it_readonly) printf("; readonly"); if (tag_type->it_multiple) printf("; multiple instances"); printf(")"); help = NULL; if (t->tag == OPENISNS_TAG_POLICY_KEY) { help = "name of key file, or \"gen\" for key generation"; } else if (tag_type->it_help) help = tag_type->it_help(); if (help) { if (strlen(help) < 20) printf(" [%s]", help); else printf("\n%25s[%s]", "", help); } printf("\n"); if (t->alias[0]) { printf("%25sAliases:", ""); for (i = 0; i < MAX_ALIASES && t->alias[i]; ++i) printf(" %s", t->alias[i]); printf("\n"); } } } isns_object_template_t * isns_attr_list_parser_context(const struct isns_attr_list_parser *st) { if (st->prefix) return st->prefix->context; return NULL; } int isns_print_attrs(isns_object_t *obj, char **argv, unsigned int argsmax) { struct isns_attr_list_parser st; unsigned int i, argc = 0; isns_attr_list_parser_init(&st, obj->ie_template); for (i = 0; i < obj->ie_attrs.ial_count; ++i) { isns_attr_t *attr = obj->ie_attrs.ial_data[i]; char argbuf[512], value[512]; const char *name; name = name_by_tag(attr->ia_tag_id, &st); if (name == NULL) continue; if (argc + 1 >= argsmax) break; snprintf(argbuf, sizeof(argbuf), "%s%s=%s", st.prefix->name, name, isns_attr_print_value(attr, value, sizeof(value))); argv[argc++] = isns_strdup(argbuf); } argv[argc] = NULL; return argc; } open-iscsi-2.0.873/utils/open-isns/getnext.c000066400000000000000000000147101175631155400206540ustar00rootroot00000000000000/* * Handle iSNS DevGetNext * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "message.h" #include "security.h" #include "objects.h" #include "db.h" #include "util.h" /* * Create a GetNext query, and set the source name */ static isns_simple_t * __isns_create_getnext(isns_source_t *source, const isns_attr_list_t *key, const isns_attr_list_t *scope) { isns_simple_t *simp; simp = isns_simple_create(ISNS_DEVICE_GET_NEXT, source, key); if (simp && scope) isns_attr_list_copy(&simp->is_operating_attrs, scope); return simp; } isns_simple_t * isns_create_getnext(isns_client_t *clnt, isns_object_template_t *tmpl, const isns_attr_list_t *scope) { isns_simple_t *simp; unsigned int i; simp = __isns_create_getnext(clnt->ic_source, NULL, scope); if (simp == NULL) return NULL; for (i = 0; i < tmpl->iot_num_keys; ++i) { isns_attr_list_append_nil(&simp->is_message_attrs, tmpl->iot_keys[i]); } return simp; } isns_simple_t * isns_create_getnext_followup(isns_client_t *clnt, const isns_simple_t *resp, const isns_attr_list_t *scope) { return __isns_create_getnext(clnt->ic_source, &resp->is_message_attrs, scope); } /* * Get the list of objects matching this query */ static int isns_getnext_get_object(isns_simple_t *qry, isns_db_t *db, isns_object_t **result) { isns_scope_t *scope; isns_attr_list_t *keys = &qry->is_message_attrs, match; isns_object_template_t *tmpl; unsigned int i; /* * 5.6.5.3. * The Message Key Attribute may be an Entity Identifier (EID), * iSCSI Name, iSCSI Index, Portal IP Address and TCP/UDP Port, * Portal Index, PG Index, FC Node Name WWNN, or FC Port Name * WWPN. * * Implementer's comment: In other words, it must be the * key attr(s) of a specific object type, or an index attribute. */ if ((tmpl = isns_object_template_for_key_attrs(keys)) != NULL) { if (keys->ial_count != tmpl->iot_num_keys) return ISNS_INVALID_QUERY; } else if (keys->ial_count == 1) { isns_attr_t *attr = keys->ial_data[0]; tmpl = isns_object_template_for_index_tag(attr->ia_tag_id); } if (tmpl == NULL) return ISNS_INVALID_QUERY; /* Verify whether the client is permitted to retrieve * objects of the given type. */ if (!isns_policy_validate_object_type(qry->is_policy, tmpl, qry->is_function)) return ISNS_SOURCE_UNAUTHORIZED; /* * 5.6.5.3. * The Operating Attributes can be used to specify the scope * of the DevGetNext request, and to specify the attributes of * the next object, which are to be returned in the DevGetNext * response message. All Operating Attributes MUST be attributes * of the object type identified by the Message Key. */ match = qry->is_operating_attrs; for (i = 0; i < match.ial_count; ++i) { isns_attr_t *attr = match.ial_data[i]; if (tmpl != isns_object_template_for_tag(attr->ia_tag_id)) return ISNS_INVALID_QUERY; } /* * 5.6.5.3. * Non-zero-length TLV attributes in the Operating Attributes * are used to scope the DevGetNext message. * [...] * Zero-length TLV attributes MUST be listed after non-zero-length * attributes in the Operating Attributes of the DevGetNext * request message. */ for (i = 0; i < match.ial_count; ++i) { if (ISNS_ATTR_IS_NIL(match.ial_data[i])) { match.ial_count = i; break; } } /* Get the scope for the originating node. */ scope = isns_scope_for_call(db, qry); *result = isns_scope_get_next(scope, tmpl, keys, &match); isns_scope_release(scope); if (*result == NULL) return ISNS_NO_SUCH_ENTRY; return ISNS_SUCCESS; } /* * Create a Query Response */ static isns_simple_t * isns_create_getnext_response(isns_source_t *source, const isns_simple_t *qry, isns_object_t *obj) { const isns_attr_list_t *req_attrs = NULL; isns_attr_list_t requested; isns_simple_t *resp; unsigned int i; resp = __isns_create_getnext(source, NULL, NULL); /* * 5.7.5.3. Device Get Next Response (DevGetNextRsp) * The Message Key Attribute field returns the object keys * for the next object after the Message Key Attribute in the * original DevGetNext message. * * Implementer's note: slightly convoluted English here. * I *think* this means the key attributes of the object * we matched. */ if (!isns_object_get_key_attrs(obj, &resp->is_message_attrs)) return NULL; /* * 5.7.5.3. * The Operating Attribute field returns the Operating Attributes * of the next object as requested in the original DevGetNext * message. The values of the Operating Attributes are those * associated with the object identified by the Message Key * Attribute field of the DevGetNextRsp message. * * Implementer's note: the RFC doesn't say clearly what to * do when the list of operating attributes does not * contain any NIL TLVs. Let's default to the same * behavior as elsewhere, and return all attributes * in this case. */ req_attrs = &qry->is_operating_attrs; for (i = 0; i < req_attrs->ial_count; ++i) { if (ISNS_ATTR_IS_NIL(req_attrs->ial_data[i])) break; } requested.ial_count = req_attrs->ial_count - i; requested.ial_data = req_attrs->ial_data + i; if (requested.ial_count) req_attrs = &requested; else req_attrs = NULL; isns_object_get_attrlist(obj, &resp->is_operating_attrs, req_attrs); return resp; } /* * Process a GetNext request */ int isns_process_getnext(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_simple_t *reply = NULL; isns_object_t *obj = NULL; isns_db_t *db = srv->is_db; int status; /* Get the next object */ status = isns_getnext_get_object(call, db, &obj); if (status != ISNS_SUCCESS) goto done; /* If it's a virtual object, rebuild it */ if (obj->ie_rebuild) obj->ie_rebuild(obj, srv->is_db); /* Success: create a new simple message, and * send it in our reply. */ reply = isns_create_getnext_response(srv->is_source, call, obj); if (reply == NULL) status = ISNS_INTERNAL_ERROR; done: if (obj) isns_object_release(obj); *result = reply; return status; } /* * Parse the object in a getnext response */ int isns_getnext_response_get_object(isns_simple_t *qry, isns_object_t **result) { isns_object_template_t *tmpl; tmpl = isns_object_template_for_key_attrs(&qry->is_operating_attrs); if (tmpl == NULL) { isns_error("Cannot determine object type in GetNext response\n"); return ISNS_ATTRIBUTE_NOT_IMPLEMENTED; } *result = isns_create_object(tmpl, &qry->is_operating_attrs, NULL); return ISNS_SUCCESS; } open-iscsi-2.0.873/utils/open-isns/internal.h000066400000000000000000000005631175631155400210200ustar00rootroot00000000000000/* * iSNS implementation - internal functions and types * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_INTERNAL_H #define ISNS_INTERNAL_H extern char * isns_slp_build_url(uint16_t); extern int isns_slp_register(const char *); extern int isns_slp_unregister(const char *); extern char * isns_slp_find(void); #endif /* ISNS_INTERNAL_H */ open-iscsi-2.0.873/utils/open-isns/isns-proto.h000066400000000000000000000172511175631155400213230ustar00rootroot00000000000000/* * iSNS protocol definitions * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_PROTO_H #define ISNS_PROTO_H #include struct isns_hdr { uint16_t i_version; uint16_t i_function; uint16_t i_length; uint16_t i_flags; uint16_t i_xid; uint16_t i_seq; }; #define ISNS_VERSION 0x0001 #define ISNS_MAX_PDU_SIZE 65535 #define ISNS_DEFAULT_PORT 3205 /* * Values for the i_flags field: */ #define ISNS_F_CLIENT 0x8000 #define ISNS_F_SERVER 0x4000 #define ISNS_F_AUTHBLK_PRESENT 0x2000 #define ISNS_F_REPLACE 0x1000 #define ISNS_F_LAST_PDU 0x0800 #define ISNS_F_FIRST_PDU 0x0400 /* * Function values */ enum isns_function { ISNS_DEVICE_ATTRIBUTE_REGISTER = 1, ISNS_DEVICE_ATTRIBUTE_QUERY = 2, ISNS_DEVICE_GET_NEXT = 3, ISNS_DEVICE_DEREGISTER = 4, ISNS_SCN_REGISTER = 5, ISNS_SCN_DEREGISTER = 6, ISNS_SCN_EVENT = 7, ISNS_STATE_CHANGE_NOTIFICATION = 8, ISNS_DD_REGISTER = 9, ISNS_DD_DEREGISTER = 10, ISNS_DDS_REGISTER = 11, ISNS_DDS_DEREGISTER = 12, ISNS_ENTITY_STATUS_INQUIRY = 13, ISNS_HEARTBEAT = 14, }; /* * iSNS status codes: */ enum isns_status { ISNS_SUCCESS = 0, ISNS_UNKNOWN_ERROR, ISNS_MESSAGE_FORMAT_ERROR, ISNS_INVALID_REGISTRATION, __ISNS_RESERVED_STATUS, ISNS_INVALID_QUERY, ISNS_SOURCE_UNKNOWN, ISNS_SOURCE_ABSENT, ISNS_SOURCE_UNAUTHORIZED, ISNS_NO_SUCH_ENTRY, ISNS_VERSION_NOT_SUPPORTED, ISNS_INTERNAL_ERROR, ISNS_BUSY, ISNS_OPTION_NOT_UNDERSTOOD, ISNS_INVALID_UPDATE, ISNS_MESSAGE_NOT_SUPPORTED, ISNS_SCN_EVENT_REJECTED, ISNS_SCN_REGISTRATION_REJECTED, ISNS_ATTRIBUTE_NOT_IMPLEMENTED, ISNS_FC_DOMAIN_ID_NOT_AVAILABLE, ISNS_FC_DOMAIN_ID_NOT_ALLOCATED, ISNS_ESI_NOT_AVAILABLE, ISNS_INVALID_DEREGISTRATION, ISNS_REGISTRATION_FEATURE_NOT_SUPPORTED, }; enum isns_tag { ISNS_TAG_DELIMITER = 0, ISNS_TAG_ENTITY_IDENTIFIER = 1, ISNS_TAG_ENTITY_PROTOCOL = 2, ISNS_TAG_MGMT_IP_ADDRESS = 3, ISNS_TAG_TIMESTAMP = 4, ISNS_TAG_PROTOCOL_VERSION_RANGE = 5, ISNS_TAG_REGISTRATION_PERIOD = 6, ISNS_TAG_ENTITY_INDEX = 7, ISNS_TAG_ENTITY_NEXT_INDEX = 8, ISNS_TAG_ENTITY_ISAKMP_PHASE_1 = 11, ISNS_TAG_ENTITY_CERTIFICATE = 12, ISNS_TAG_PORTAL_IP_ADDRESS = 16, ISNS_TAG_PORTAL_TCP_UDP_PORT = 17, ISNS_TAG_PORTAL_SYMBOLIC_NAME = 18, ISNS_TAG_ESI_INTERVAL = 19, ISNS_TAG_ESI_PORT = 20, ISNS_TAG_PORTAL_INDEX = 22, ISNS_TAG_SCN_PORT = 23, ISNS_TAG_PORTAL_NEXT_INDEX = 24, ISNS_TAG_PORTAL_SECURITY_BITMAP = 27, ISNS_TAG_PORTAL_ISAKMP_PHASE_1 = 28, ISNS_TAG_PORTAL_ISAKMP_PHASE_2 = 29, ISNS_TAG_PORTAL_CERTIFICATE = 31, ISNS_TAG_ISCSI_NAME = 32, ISNS_TAG_ISCSI_NODE_TYPE = 33, ISNS_TAG_ISCSI_ALIAS = 34, ISNS_TAG_ISCSI_SCN_BITMAP = 35, ISNS_TAG_ISCSI_NODE_INDEX = 36, ISNS_TAG_WWNN_TOKEN = 37, ISNS_TAG_ISCSI_NODE_NEXT_INDEX = 38, ISNS_TAG_ISCSI_AUTHMETHOD = 42, ISNS_TAG_PG_ISCSI_NAME = 48, ISNS_TAG_PG_PORTAL_IP_ADDR = 49, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT = 50, ISNS_TAG_PG_TAG = 51, ISNS_TAG_PG_INDEX = 52, ISNS_TAG_PG_NEXT_INDEX = 53, ISNS_TAG_FC_PORT_NAME_WWPN = 64, ISNS_TAG_PORT_ID = 65, ISNS_TAG_FC_PORT_TYPE = 66, ISNS_TAG_SYMBOLIC_PORT_NAME = 67, ISNS_TAG_FABRIC_PORT_NAME = 68, ISNS_TAG_HARD_ADDRESS = 69, ISNS_TAG_PORT_IP_ADDRESS = 70, ISNS_TAG_CLASS_OF_SERVICE = 71, ISNS_TAG_FC4_TYPES = 72, ISNS_TAG_FC4_DESCRIPTOR = 73, ISNS_TAG_FC4_FEATURES = 74, ISNS_TAG_IFCP_SCN_BITMAP = 75, ISNS_TAG_PORT_ROLE = 76, ISNS_TAG_PERMANENT_PORT_NAME = 77, ISNS_TAG_FC4_TYPE_CODE = 95, ISNS_TAG_FC_NODE_NAME_WWNN = 96, ISNS_TAG_SYMBOLIC_NODE_NAME = 97, ISNS_TAG_NODE_IP_ADDRESS = 98, ISNS_TAG_NODE_IPA = 99, ISNS_TAG_PROXY_ISCSI_NAME = 101, ISNS_TAG_SWITCH_NAME = 128, ISNS_TAG_PREFERRED_ID = 129, ISNS_TAG_ASSIGNED_ID = 130, ISNS_TAG_VIRTUAL_FABRIC_ID = 131, ISNS_TAG_SERVER_VENDOR_OUI = 256, ISNS_TAG_DD_SET_ID = 2049, ISNS_TAG_DD_SET_SYMBOLIC_NAME = 2050, ISNS_TAG_DD_SET_STATUS = 2051, ISNS_TAG_DD_SET_NEXT_ID = 2052, ISNS_TAG_DD_ID = 2065, ISNS_TAG_DD_SYMBOLIC_NAME = 2066, ISNS_TAG_DD_MEMBER_ISCSI_INDEX = 2067, ISNS_TAG_DD_MEMBER_ISCSI_NAME = 2068, ISNS_TAG_DD_MEMBER_FC_PORT_NAME = 2069, ISNS_TAG_DD_MEMBER_PORTAL_INDEX = 2070, ISNS_TAG_DD_MEMBER_PORTAL_IP_ADDR = 2071, ISNS_TAG_DD_MEMBER_PORTAL_TCP_UDP_PORT = 2072, ISNS_TAG_DD_FEATURES = 2078, ISNS_TAG_DD_NEXT_ID = 2079, __ISNS_TAG_MAX, ISNS_VENDOR_SPECIFIC_SERVER_BASE = 257, /* end 384 */ ISNS_VENDOR_SPECIFIC_ENTITY_BASE = 385, /* end 512 */ ISNS_VENDOR_SPECIFIC_PORTAL_BASE = 513, /* end 640 */ ISNS_VENDOR_SPECIFIC_NODE_BASE = 641, /* end 768 */ ISNS_VENDOR_SPECIFIC_DD_BASE = 1024, /* end 1280 */ ISNS_VENDOR_SPECIFIC_DDSET_BASE = 1281, /* end 1536 */ ISNS_VENDOR_SPECIFIC_OTHER_BASE = 1537, /* end 2048 */ }; typedef enum isns_entity_protocol { ISNS_ENTITY_PROTOCOL_NONE = 1, ISNS_ENTITY_PROTOCOL_ISCSI = 2, ISNS_ENTITY_PROTOCOL_IFCP = 3, } isns_entity_protocol_t; enum isns_iscsi_node_type_bits { ISNS_ISCSI_NODE_TYPE_TARGET = 0, ISNS_ISCSI_NODE_TYPE_INITIATOR = 1, ISNS_ISCSI_NODE_TYPE_CONTROL = 2, }; #define ISNS_ISCSI_INITIATOR_MASK (1 << ISNS_ISCSI_NODE_TYPE_INITIATOR) #define ISNS_ISCSI_TARGET_MASK (1 << ISNS_ISCSI_NODE_TYPE_TARGET) #define ISNS_ISCSI_CONTROL_MASK (1 << ISNS_ISCSI_NODE_TYPE_CONTROL) enum isns_portal_port_bits { ISNS_PORTAL_PORT_UDP = 16, }; #define ISNS_PORTAL_PORT_UDP_MASK (1 << ISNS_PORTAL_PORT_UDP) enum isns_portal_security_bits { ISNS_PORTAL_SEC_BITMAP_VALID = 0, ISNS_PORTAL_SEC_IPSEC_ENABLED = 1, ISNS_PORTAL_SEC_MAIN_MODE_ENABLED = 2, ISNS_PORTAL_SEC_AGGR_MODE_ENABLED = 3, ISNS_PORTAL_SEC_PFS_ENABLED = 4, ISNS_PORTAL_SEC_TRANSPORT_MODE_PREFERRED = 5, ISNS_PORTAL_SEC_TUNNEL_MODE_PREFERRED = 6, }; #define ISNS_PORTAL_SEC_BITMAP_VALID_MASK (1 << ISNS_PORTAL_SEC_BITMAP_VALID) #define ISNS_PORTAL_SEC_IPSEC_ENABLED_MASK (1 << ISNS_PORTAL_SEC_IPSEC_ENABLED) #define ISNS_PORTAL_SEC_MAIN_MODE_ENABLED_MASK (1 << ISNS_PORTAL_SEC_MAIN_MODE_ENABLED) #define ISNS_PORTAL_SEC_AGGR_MODE_ENABLED_MASK (1 << ISNS_PORTAL_SEC_AGGR_MODE_ENABLED) #define ISNS_PORTAL_SEC_PFS_ENABLED_MASK (1 << ISNS_PORTAL_SEC_PFS_ENABLED) #define ISNS_PORTAL_SEC_TRANSPORT_MODE_PREFERRED_MASK (1 << ISNS_PORTAL_SEC_TRANSPORT_MODE_PREFERRED) #define ISNS_PORTAL_SEC_TUNNEL_MODE_PREFERRED_MASK (1 << ISNS_PORTAL_SEC_TUNNEL_MODE_PREFERRED) enum isns_scn_bits { ISNS_SCN_DD_MEMBER_ADDED = 0, ISNS_SCN_DD_MEMBER_REMOVED = 1, ISNS_SCN_OBJECT_UPDATED = 2, ISNS_SCN_OBJECT_ADDED = 3, ISNS_SCN_OBJECT_REMOVED = 4, ISNS_SCN_MANAGEMENT_REGISTRATION = 5, ISNS_SCN_TARGET_AND_SELF_ONLY = 6, ISNS_SCN_INITIATOR_AND_SELF_ONLY = 7, }; #define ISNS_SCN_DD_MEMBER_ADDED_MASK (1 << ISNS_SCN_DD_MEMBER_ADDED) #define ISNS_SCN_DD_MEMBER_REMOVED_MASK (1 << ISNS_SCN_DD_MEMBER_REMOVED) #define ISNS_SCN_OBJECT_UPDATED_MASK (1 << ISNS_SCN_OBJECT_UPDATED) #define ISNS_SCN_OBJECT_ADDED_MASK (1 << ISNS_SCN_OBJECT_ADDED) #define ISNS_SCN_OBJECT_REMOVED_MASK (1 << ISNS_SCN_OBJECT_REMOVED) #define ISNS_SCN_MANAGEMENT_REGISTRATION_MASK (1 << ISNS_SCN_MANAGEMENT_REGISTRATION) #define ISNS_SCN_TARGET_AND_SELF_ONLY_MASK (1 << ISNS_SCN_TARGET_AND_SELF_ONLY) #define ISNS_SCN_INITIATOR_AND_SELF_ONLY_MASK (1 << ISNS_SCN_INITIATOR_AND_SELF_ONLY) enum isns_dds_status_bits { ISNS_DDS_ENABLED = 0, }; #define ISNS_DDS_ENABLED_MASK (1 << ISNS_DDS_ENABLED) enum isns_dd_feature_bits { ISNS_DD_BOOT_LIST_ENABLED = 0, }; #define ISNS_DD_BOOT_LIST_ENABLED_MASK (1 << ISN_BOOT_LIST_DDS_ENABLED) #define ISNS_PAD(len) (((len) + 3) & ~3UL) /* * iSNS auth block */ #define ISNS_AUTHBLK_SIZE 20 struct isns_authblk { uint32_t iab_bsd; /* 16bit in SLP */ uint32_t iab_length; /* 16bit in SLP */ uint64_t iab_timestamp; /* 32bit in SLP */ uint32_t iab_spi_len; /* 16bit in SLP */ char * iab_spi; void * iab_sig; uint32_t iab_sig_len; } __attribute__((packed)); #define ISNS_AUTH_TYPE_SHA1_DSA 0x0002 #endif /* ISNS_PROTO_H */ open-iscsi-2.0.873/utils/open-isns/isns.h000066400000000000000000000612611175631155400201620ustar00rootroot00000000000000/* * iSNS implementation - library header file. * * Copyright (C) 2007 Olaf Kirch * * This file contains all declarations and definitions * commonly required by users of libisns. */ #ifndef ISNS_H #define ISNS_H #include #include #include #include #include "types.h" #define ISNS_MAX_BUFFER 8192 #define ISNS_MAX_MESSAGE 8192 /* * Client handle */ typedef struct isns_client isns_client_t; struct isns_client { isns_source_t * ic_source; isns_socket_t * ic_socket; }; /* * Server operations */ typedef int isns_service_fn_t(isns_server_t *, isns_simple_t *, isns_simple_t **); typedef void isns_scn_callback_fn_t(isns_db_t *, uint32_t scn_bits, isns_object_template_t *node_type, const char *node_name, const char *recipient); struct isns_service_ops { isns_service_fn_t * process_registration; isns_service_fn_t * process_query; isns_service_fn_t * process_getnext; isns_service_fn_t * process_deregistration; isns_service_fn_t * process_scn_registration; isns_service_fn_t * process_scn_deregistration; isns_service_fn_t * process_scn_event; isns_service_fn_t * process_scn; isns_service_fn_t * process_dd_registration; isns_service_fn_t * process_dd_deregistration; isns_service_fn_t * process_esi; isns_service_fn_t * process_heartbeat; }; extern struct isns_service_ops isns_default_service_ops; extern struct isns_service_ops isns_callback_service_ops; /* * Output function */ void isns_print_stdout(const char *, ...); /* * Database events */ struct isns_db_event { isns_object_t * ie_recipient; /* Recipient node or NULL */ isns_object_t * ie_object; /* Affected object */ isns_object_t * ie_trigger; /* Triggering object */ unsigned int ie_bits; /* SCN bitmask */ }; typedef void isns_db_callback_t(const isns_db_event_t *, void *user_data); /* * Handling of client objects */ extern isns_client_t * isns_create_default_client(isns_security_t *); extern isns_client_t * isns_create_client(isns_security_t *, const char *source_name); extern isns_client_t * isns_create_local_client(isns_security_t *, const char *source_name); extern int isns_client_call(isns_client_t *, isns_simple_t **inout); extern void isns_client_destroy(isns_client_t *); extern int isns_client_get_local_address(const isns_client_t *, isns_portal_info_t *); /* * Handling of server objects */ extern isns_server_t * isns_create_server(isns_source_t *, isns_db_t *, struct isns_service_ops *); extern void isns_server_set_scn_callback(isns_server_t *, isns_scn_callback_fn_t *); /* * Handling of source names */ extern int isns_init_names(void); extern const char * isns_default_source_name(void); extern isns_source_t * isns_source_create(isns_attr_t *); extern isns_source_t * isns_source_create_iscsi(const char *name); extern isns_source_t * isns_source_create_ifcp(const char *name); extern uint32_t isns_source_type(const isns_source_t *); extern const char * isns_source_name(const isns_source_t *); extern isns_attr_t * isns_source_attr(const isns_source_t *); extern isns_source_t * isns_source_get(isns_source_t *); extern isns_source_t * isns_source_from_object(const isns_object_t *); extern void isns_source_release(isns_source_t *); extern int isns_source_match(const isns_source_t *, const isns_source_t *); extern void isns_server_set_source(isns_source_t *); extern isns_message_t * isns_process_message(isns_server_t *, isns_message_t *); extern void isns_simple_print(isns_simple_t *, isns_print_fn_t *); extern int isns_simple_call(isns_socket_t *, isns_simple_t **); extern int isns_simple_transmit(isns_socket_t *, isns_simple_t *, const isns_portal_info_t *, unsigned int, void (*callback)(uint32_t, int, isns_simple_t *)); extern void isns_simple_free(isns_simple_t *); extern const isns_attr_list_t *isns_simple_get_attrs(isns_simple_t *); extern isns_simple_t * isns_create_query(isns_client_t *clnt, const isns_attr_list_t *query_key); extern isns_simple_t * isns_create_query2(isns_client_t *clnt, const isns_attr_list_t *query_key, isns_source_t *source); extern int isns_query_request_attr_tag(isns_simple_t *, uint32_t); extern int isns_query_request_attr(isns_simple_t *, isns_attr_t *); extern int isns_query_response_get_objects(isns_simple_t *qry, isns_object_list_t *result); extern isns_simple_t * isns_create_registration(isns_client_t *clnt, isns_object_t *key_object); extern isns_simple_t * isns_create_registration2(isns_client_t *clnt, isns_object_t *key_object, isns_source_t *source); extern void isns_registration_set_replace(isns_simple_t *, int); extern void isns_registration_add_object(isns_simple_t *, isns_object_t *object); extern void isns_registration_add_object_list(isns_simple_t *, isns_object_list_t *); extern int isns_registration_response_get_objects(isns_simple_t *, isns_object_list_t *); extern isns_simple_t * isns_create_getnext(isns_client_t *, isns_object_template_t *, const isns_attr_list_t *); extern int isns_getnext_response_get_object(isns_simple_t *, isns_object_t **); extern isns_simple_t * isns_create_getnext_followup(isns_client_t *, const isns_simple_t *, const isns_attr_list_t *); extern isns_simple_t * isns_create_deregistration(isns_client_t *clnt, const isns_attr_list_t *); extern isns_simple_t * isns_create_scn_registration(isns_client_t *clnt, unsigned int); extern isns_simple_t * isns_create_scn_registration2(isns_client_t *clnt, unsigned int, isns_source_t *); extern int isns_dd_load_all(isns_db_t *); extern void isns_dd_get_members(uint32_t, isns_object_list_t *, int); extern isns_simple_t * isns_create_dd_registration(isns_client_t *, const isns_attr_list_t *); extern isns_simple_t * isns_create_dd_deregistration(isns_client_t *, uint32_t, const isns_attr_list_t *); extern isns_object_t * isns_create_object(isns_object_template_t *, const isns_attr_list_t *, isns_object_t *); extern isns_object_t * isns_create_entity(int, const char *); extern isns_object_t * isns_create_entity_for_source(const isns_source_t *, const char *); extern const char * isns_entity_name(const isns_object_t *); extern isns_object_t * isns_create_portal(const isns_portal_info_t *, isns_object_t *parent); extern isns_object_t * isns_create_storage_node(const char *name, uint32_t type_mask, isns_object_t *parent); extern isns_object_t * isns_create_storage_node2(const isns_source_t *, uint32_t type_mask, isns_object_t *parent); extern isns_object_t * isns_create_iscsi_initiator(const char *name, isns_object_t *parent); extern isns_object_t * isns_create_iscsi_target(const char *name, isns_object_t *parent); extern const char * isns_storage_node_name(const isns_object_t *); extern isns_attr_t * isns_storage_node_key_attr(const isns_object_t *); extern isns_object_t * isns_create_portal_group(isns_object_t *portal, isns_object_t *iscsi_node, uint32_t pg_tag); extern isns_object_t * isns_create_default_portal_group(isns_db_t *, isns_object_t *portal, isns_object_t *node); extern void isns_get_portal_groups(isns_object_t *portal, isns_object_t *node, isns_object_list_t *result); extern const char * isns_object_template_name(isns_object_template_t *); extern int isns_object_set_attr(isns_object_t *, isns_attr_t *); extern int isns_object_set_attrlist(isns_object_t *, const isns_attr_list_t *); extern isns_object_t * isns_object_get(isns_object_t *); extern int isns_object_get_attrlist(isns_object_t *obj, isns_attr_list_t *result, const isns_attr_list_t *requested_attrs); extern int isns_object_get_key_attrs(isns_object_t *, isns_attr_list_t *); extern int isns_object_get_attr(const isns_object_t *, uint32_t, isns_attr_t **); extern void isns_object_get_related(isns_db_t *, isns_object_t *, isns_object_list_t *); extern void isns_object_get_descendants(const isns_object_t *, isns_object_template_t *, isns_object_list_t *); extern void isns_object_release(isns_object_t *); extern int isns_object_match(const isns_object_t *, const isns_attr_list_t *); extern isns_object_t * isns_object_get_entity(isns_object_t *); extern int isns_object_attr_valid(isns_object_template_t *, uint32_t); extern int isns_object_contains(const isns_object_t *, const isns_object_t *); extern int isns_object_delete_attr(isns_object_t *, uint32_t); extern int isns_object_is(const isns_object_t *, isns_object_template_t *); extern int isns_object_is_entity(const isns_object_t *); extern int isns_object_is_iscsi_node(const isns_object_t *); extern int isns_object_is_fc_port(const isns_object_t *); extern int isns_object_is_fc_node(const isns_object_t *); extern int isns_object_is_portal(const isns_object_t *); extern int isns_object_is_pg(const isns_object_t *); extern int isns_object_is_policy(const isns_object_t *); extern int isns_object_is_dd(const isns_object_t *); extern int isns_object_is_ddset(const isns_object_t *); extern void isns_object_print(isns_object_t *, isns_print_fn_t *); extern time_t isns_object_last_modified(const isns_object_t *); extern int isns_object_mark_membership(isns_object_t *, uint32_t); extern int isns_object_clear_membership(isns_object_t *, uint32_t); extern int isns_object_test_membership(const isns_object_t *, uint32_t); extern int isns_object_test_visibility(const isns_object_t *, const isns_object_t *); extern void isns_object_get_visible(const isns_object_t *, isns_db_t *, isns_object_list_t *); extern void isns_entity_touch(isns_object_t *); extern int isns_object_extract_keys(const isns_object_t *, isns_attr_list_t *); extern int isns_object_extract_all(const isns_object_t *, isns_attr_list_t *); extern int isns_object_extract_writable(const isns_object_t *, isns_attr_list_t *); extern int isns_object_set_nil(isns_object_t *obj, uint32_t tag); extern int isns_object_set_string(isns_object_t *obj, uint32_t tag, const char *value); extern int isns_object_set_uint32(isns_object_t *obj, uint32_t tag, uint32_t value); extern int isns_object_set_uint64(isns_object_t *obj, uint32_t tag, uint64_t value); extern int isns_object_set_ipaddr(isns_object_t *obj, uint32_t tag, const struct in6_addr *value); extern int isns_object_get_string(const isns_object_t *, uint32_t, const char **); extern int isns_object_get_ipaddr(const isns_object_t *, uint32_t, struct in6_addr *); extern int isns_object_get_uint32(const isns_object_t *, uint32_t, uint32_t *); extern int isns_object_get_uint64(const isns_object_t *, uint32_t, uint64_t *); extern int isns_object_get_opaque(const isns_object_t *, uint32_t, const void **, size_t *); extern int isns_object_find_descendants(isns_object_t *obj, isns_object_template_t *, const isns_attr_list_t *keys, isns_object_list_t *result); extern isns_object_t * isns_object_find_descendant(isns_object_t *obj, const isns_attr_list_t *keys); extern int isns_object_detach(isns_object_t *); extern int isns_object_attach(isns_object_t *, isns_object_t *); extern void isns_object_prune_attrs(isns_object_t *); extern void isns_mark_object(isns_object_t *, unsigned int); extern int isns_get_entity_identifier(isns_object_t *, const char **); extern int isns_get_entity_protocol(isns_object_t *, isns_entity_protocol_t *); extern int isns_get_entity_index(isns_object_t *, uint32_t *); extern int isns_get_portal_ipaddr(isns_object_t *, struct in6_addr *); extern int isns_get_portal_tcpudp_port(isns_object_t *, int *ipprotocol, uint16_t *port); extern int isns_get_portal_index(isns_object_t *, uint32_t *); extern int isns_get_address(struct sockaddr_storage *, const char *, const char *, int, int, int); extern char * isns_get_canon_name(const char *); extern isns_db_t * isns_db_open(const char *location); extern isns_db_t * isns_db_open_shadow(isns_object_list_t *); extern isns_object_t * isns_db_lookup(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *); extern isns_object_t * isns_db_vlookup(isns_db_t *, isns_object_template_t *, ...); extern int isns_db_gang_lookup(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern isns_object_t * isns_db_get_next(isns_db_t *, isns_object_template_t *, const isns_attr_list_t *current, const isns_attr_list_t *scope, const isns_source_t *source); extern isns_object_t * isns_db_lookup_source_node(isns_db_t *, const isns_source_t *); extern void isns_db_get_domainless(isns_db_t *, isns_object_template_t *, isns_object_list_t *); extern uint32_t isns_db_allocate_index(isns_db_t *); extern void isns_db_insert(isns_db_t *, isns_object_t *); extern void isns_db_insert_limbo(isns_db_t *, isns_object_t *); extern int isns_db_remove(isns_db_t *, isns_object_t *); extern time_t isns_db_expire(isns_db_t *); extern void isns_db_purge(isns_db_t *); extern void isns_db_sync(isns_db_t *); extern const char * isns_db_generate_eid(isns_db_t *, char *, size_t); extern isns_object_t * isns_db_get_control(isns_db_t *); extern void isns_db_print(isns_db_t *, isns_print_fn_t *); extern void isns_db_begin_transaction(isns_db_t *); extern void isns_db_commit(isns_db_t *); extern void isns_db_rollback(isns_db_t *); extern void isns_object_event(isns_object_t *obj, unsigned int bits, isns_object_t *trigger); extern void isns_unicast_event(isns_object_t *dst, isns_object_t *obj, unsigned int bits, isns_object_t *trigger); extern void isns_register_callback(isns_db_callback_t *, void *); extern void isns_flush_events(void); extern const char * isns_event_string(unsigned int); extern void isns_add_timer(unsigned int, isns_timer_callback_t *, void *); extern void isns_add_oneshot_timer(unsigned int, isns_timer_callback_t *, void *); extern void isns_cancel_timer(isns_timer_callback_t *, void *); extern time_t isns_run_timers(void); extern void isns_object_list_init(isns_object_list_t *); extern void isns_object_list_destroy(isns_object_list_t *); extern int isns_object_list_contains(const isns_object_list_t *, isns_object_t *); extern void isns_object_list_append(isns_object_list_t *, isns_object_t *); extern void isns_object_list_append_list(isns_object_list_t *, const isns_object_list_t *); extern isns_object_t * isns_object_list_lookup(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *); extern int isns_object_list_gang_lookup(const isns_object_list_t *, isns_object_template_t *, const isns_attr_list_t *, isns_object_list_t *); extern int isns_object_list_remove(isns_object_list_t *, isns_object_t *); extern void isns_object_list_uniq(isns_object_list_t *); extern void isns_object_list_print(const isns_object_list_t *, isns_print_fn_t *); isns_object_template_t *isns_object_template_for_key_attrs(const isns_attr_list_t *); isns_object_template_t *isns_object_template_for_tag(uint32_t); isns_object_template_t *isns_object_template_for_index_tag(uint32_t); isns_object_template_t *isns_object_template_find(uint32_t); extern int isns_attr_set(isns_attr_t *, const void *); extern isns_attr_t * isns_attr_get(isns_attr_t *); extern void isns_attr_release(isns_attr_t *); extern void isns_attr_print(const isns_attr_t *, isns_print_fn_t *); extern char * isns_attr_print_value(const isns_attr_t *, char *, size_t); extern int isns_attr_match(const isns_attr_t *, const isns_attr_t *); extern int isns_attr_compare(const isns_attr_t *, const isns_attr_t *); extern isns_attr_t * isns_attr_from_string(uint32_t, const char *); extern void isns_attr_list_print(const isns_attr_list_t *, isns_print_fn_t *); extern void isns_attr_list_init(isns_attr_list_t *); extern void isns_attr_list_copy(isns_attr_list_t *, const isns_attr_list_t *); extern void isns_attr_list_destroy(isns_attr_list_t *); extern int isns_attr_list_remove_tag(isns_attr_list_t *, uint32_t); extern void isns_attr_list_append_attr(isns_attr_list_t *, isns_attr_t *); extern void isns_attr_list_append_list(isns_attr_list_t *, const isns_attr_list_t *); extern int isns_attr_list_replace_attr(isns_attr_list_t *, isns_attr_t *); /* Warning: this does *NOT* return a reference to the attribute */ extern int isns_attr_list_get_attr(const isns_attr_list_t *, uint32_t tag, isns_attr_t **); extern void isns_attr_list_append_nil(isns_attr_list_t *, uint32_t tag); extern void isns_attr_list_append_string(isns_attr_list_t *, uint32_t tag, const char *value); extern void isns_attr_list_append_uint32(isns_attr_list_t *, uint32_t tag, uint32_t value); extern void isns_attr_list_append_uint64(isns_attr_list_t *, uint32_t, int64_t); extern void isns_attr_list_append_int32(isns_attr_list_t *, uint32_t tag, int32_t value); extern void isns_attr_list_append_opaque(isns_attr_list_t *, uint32_t tag, const void *ptr, size_t len); extern void isns_attr_list_append_ipaddr(isns_attr_list_t *, uint32_t tag, const struct in6_addr *); extern int isns_attr_list_append(isns_attr_list_t *, uint32_t tag, const void *); extern int isns_attr_list_update(isns_attr_list_t *, uint32_t tag, const void *); extern int isns_attr_list_contains(const isns_attr_list_t *, uint32_t tag); extern int isns_attr_list_compare(const isns_attr_list_t *, const isns_attr_list_t *); /* * Helper macros */ #define ISNS_ATTR_TYPE_CHECK(attr, type) \ ((attr)->ia_value.iv_type == &isns_attr_type_##type) #define ISNS_ATTR_IS_NIL(attr) \ ISNS_ATTR_TYPE_CHECK(attr, nil) #define ISNS_ATTR_IS_STRING(attr) \ ISNS_ATTR_TYPE_CHECK(attr, string) #define ISNS_ATTR_IS_IPADDR(attr) \ ISNS_ATTR_TYPE_CHECK(attr, ipaddr) #define ISNS_ATTR_IS_UINT32(attr) \ ISNS_ATTR_TYPE_CHECK(attr, uint32) #define ISNS_ATTR_IS_UINT64(attr) \ ISNS_ATTR_TYPE_CHECK(attr, uint64) #define ISNS_ATTR_IS_OPAQUE(attr) \ ISNS_ATTR_TYPE_CHECK(attr, opaque) extern isns_socket_t * isns_create_server_socket(const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_create_client_socket(const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_create_bound_client_socket(const char *myaddr, const char *hostname, const char *portname, int af_hint, int sock_type); extern isns_socket_t * isns_connect_to_portal(const isns_portal_info_t *); extern void isns_socket_set_report_failure(isns_socket_t *); extern void isns_socket_set_disconnect_fatal(isns_socket_t *); extern int isns_socket_get_local_addr(const isns_socket_t *, struct sockaddr_storage *); extern int isns_socket_get_portal_info(const isns_socket_t *, isns_portal_info_t *); extern void isns_socket_set_security_ctx(isns_socket_t *, isns_security_t *); extern isns_message_t * isns_recv_message(struct timeval *timeout); extern isns_message_t * isns_socket_call(isns_socket_t *, isns_message_t *, long); extern int isns_socket_send(isns_socket_t *, isns_message_t *); extern void isns_socket_free(isns_socket_t *); extern int isns_addr_get_port(const struct sockaddr *); extern void isns_addr_set_port(struct sockaddr *, unsigned int); extern isns_socket_t * isns_socket_find_server(const isns_portal_info_t *); extern isns_message_t * isns_create_message(uint16_t function, uint16_t flags); extern isns_message_t * isns_create_reply(const isns_message_t *); extern int isns_message_init(isns_message_t *, uint16_t, uint16_t, size_t); extern int isns_message_status(isns_message_t *); extern void isns_message_release(isns_message_t *); extern unsigned int isns_message_function(const isns_message_t *); extern isns_socket_t * isns_message_socket(const isns_message_t *); extern void isns_message_set_error(isns_message_t *, uint32_t); extern const char * isns_strerror(enum isns_status); extern const char * isns_function_name(unsigned int); /* * Security related functions */ extern int isns_security_init(void); extern isns_principal_t *isns_security_load_privkey(isns_security_t *, const char *filename); extern isns_principal_t *isns_security_load_pubkey(isns_security_t *, const char *filename); extern isns_security_t *isns_default_security_context(int server_only); extern isns_security_t *isns_control_security_context(int server_only); extern isns_security_t *isns_create_dsa_context(void); extern void isns_security_set_identity(isns_security_t *, isns_principal_t *); extern void isns_principal_free(isns_principal_t *); extern void isns_add_principal(isns_security_t *, isns_principal_t *); extern isns_keystore_t *isns_create_keystore(const char *); extern void isns_security_set_keystore(isns_security_t *, isns_keystore_t *); extern void isns_principal_set_name(isns_principal_t *, const char *); extern const char * isns_principal_name(const isns_principal_t *); extern isns_object_template_t isns_entity_template; extern isns_object_template_t isns_portal_template; extern isns_object_template_t isns_iscsi_node_template; extern isns_object_template_t isns_fc_port_template; extern isns_object_template_t isns_fc_node_template; extern isns_object_template_t isns_iscsi_pg_template; extern isns_object_template_t isns_dd_template; extern isns_object_template_t isns_ddset_template; /* * Config file parser */ struct isns_config { char * ic_host_name; char * ic_auth_name; char * ic_source_name; char * ic_source_suffix; char * ic_entity_name; char * ic_server_name; char * ic_bind_address; char * ic_database; char * ic_auth_key_file; char * ic_server_key_file; char * ic_client_keystore; char * ic_control_socket; char * ic_pidfile; char * ic_local_registry_file; int ic_security; int ic_slp_register; char * ic_control_name; char * ic_control_key_file; unsigned int ic_registration_period; unsigned int ic_scn_timeout; unsigned int ic_scn_retries; char * ic_scn_callout; unsigned int ic_esi_max_interval; unsigned int ic_esi_min_interval; unsigned int ic_esi_retries; unsigned int ic_use_default_domain; struct { unsigned int policy; unsigned int replay_window; unsigned int timestamp_jitter; int allow_unknown_peers; } ic_auth; struct { unsigned int max_sockets; unsigned int connect_timeout; unsigned int reconnect_timeout; unsigned int call_timeout; unsigned int udp_retrans_timeout; unsigned int tcp_retrans_timeout; unsigned int idle_timeout; } ic_network; struct { char * param_file; unsigned int key_bits; } ic_dsa; }; extern struct isns_config isns_config; extern int isns_read_config(const char *); extern int isns_config_set(const char *, char *); /* * Reserved entity name for Policy information */ #define ISNS_ENTITY_CONTROL "CONTROL" /* * Helpers to deal with portal information */ struct isns_portal_info { struct sockaddr_in6 addr; int proto; }; extern void isns_portal_init(isns_portal_info_t *, const struct sockaddr *, int); extern int isns_portal_parse(isns_portal_info_t *portal, const char *addr_spec, const char *default_port); extern int isns_portal_from_attr_list(isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, const isns_attr_list_t *); extern int isns_portal_from_attr_pair(isns_portal_info_t *, const isns_attr_t *, const isns_attr_t *); extern int isns_portal_from_object(isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, const isns_object_t *); extern int isns_portal_from_sockaddr(isns_portal_info_t *, const struct sockaddr_storage *); extern int isns_portal_to_sockaddr(const isns_portal_info_t *, struct sockaddr_storage *); extern int isns_portal_to_attr_list(const isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, isns_attr_list_t *); extern int isns_portal_to_object(const isns_portal_info_t *, uint32_t addr_tag, uint32_t port_tag, isns_object_t *); extern int isns_portal_is_wildcard(const isns_portal_info_t *); extern uint32_t isns_portal_tcpudp_port(const isns_portal_info_t *); extern const char * isns_portal_string(const isns_portal_info_t *); extern int isns_portal_equal(const isns_portal_info_t *, const isns_portal_info_t *); extern int isns_enumerate_portals(isns_portal_info_t *, unsigned int); extern int isns_get_nr_portals(void); /* Local registry stuff */ extern int isns_local_registry_load(const char *, pid_t, isns_object_list_t *); extern int isns_local_registry_store(const char *, pid_t, const isns_object_list_t *); extern int isns_local_registry_purge(const char *, pid_t); /* Should go somwhere else .*/ extern int isns_esi_enabled; extern void isns_esi_init(isns_server_t *); extern void isns_esi_register(isns_object_t *); extern void isns_scn_init(isns_server_t *); extern time_t isns_scn_transmit_all(void); #endif /* ISNS_H */ open-iscsi-2.0.873/utils/open-isns/isnsadm.c000066400000000000000000000714771175631155400206510ustar00rootroot00000000000000/* * isnsadm - helper utility * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include "isns.h" #include "util.h" #include "vendor.h" #include "attrs.h" #include "security.h" #include "objects.h" #include "paths.h" #include "config.h" #define ISNS_DEFAULT_PORT_INITIATOR 860 #define ISNS_DEFAULT_PORT_TARGET 3260 enum { DO_REGISTER = 1024, DO_QUERY, DO_QUERY_EID, DO_LIST, DO_DEREGISTER, DO_DD_REGISTER, DO_DD_DEREGISTER, DO_ENROLL, DO_EDIT_POLICY, DO_DELETE_POLICY, }; static struct option options[] = { { "help", no_argument, NULL, 'h' }, { "config", required_argument, NULL, 'c' }, { "debug", required_argument, NULL, 'd' }, { "keyfile", required_argument, NULL, 'K', }, { "key", required_argument, NULL, 'k', }, { "local", no_argument, NULL, 'l' }, { "control", no_argument, NULL, 'C' }, { "replace", no_argument, NULL, 'r' }, { "query", no_argument, NULL, DO_QUERY }, { "query-eid", no_argument, NULL, DO_QUERY_EID }, { "list", no_argument, NULL, DO_LIST }, { "register", no_argument, NULL, DO_REGISTER }, { "deregister", no_argument, NULL, DO_DEREGISTER }, { "dd-register", no_argument, NULL, DO_DD_REGISTER }, { "dd-deregister", no_argument, NULL, DO_DD_DEREGISTER}, { "enroll", no_argument, NULL, DO_ENROLL }, { "edit-policy", no_argument, NULL, DO_EDIT_POLICY }, { "delete-policy", no_argument, NULL, DO_DELETE_POLICY }, { "version", no_argument, NULL, 'V' }, { NULL } }; static const char * opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; static int opt_af = AF_UNSPEC; static int opt_action = 0; static int opt_local = 0; static int opt_control = 0; static int opt_replace = 0; static const char * opt_keyfile = NULL; static char * opt_key = NULL; static struct sockaddr_storage opt_myaddr; static void usage(int, const char *); static int register_objects(isns_client_t *, int, char **); static int query_objects(isns_client_t *, int, char **); static int query_entity_id(isns_client_t *, int, char **); static int list_objects(isns_client_t *, int, char **); static int deregister_objects(isns_client_t *, int, char **); static int register_domain(isns_client_t *, int, char **); static int deregister_domain(isns_client_t *, int, char **); static int enroll_client(isns_client_t *, int, char **); static int edit_policy(isns_client_t *, int, char **); static isns_attr_t * load_key_callback(const char *); static isns_attr_t * generate_key_callback(void); int main(int argc, char **argv) { isns_client_t *clnt; isns_security_t *security = NULL; int c, status; while ((c = getopt_long(argc, argv, "46Cc:d:hK:k:l", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'C': opt_control = 1; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'h': usage(0, NULL); break; case 'K': opt_keyfile = optarg; break; case 'k': opt_key = optarg; break; case 'l': opt_local = 1; break; case 'r': opt_replace = 1; break; case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch \n", OPENISNS_VERSION_STRING); return 0; case DO_REGISTER: case DO_QUERY: case DO_QUERY_EID: case DO_LIST: case DO_DEREGISTER: case DO_DD_REGISTER: case DO_DD_DEREGISTER: case DO_ENROLL: case DO_EDIT_POLICY: case DO_DELETE_POLICY: if (opt_action) usage(1, "You cannot specify more than one mode\n"); opt_action = c; break; default: usage(1, "Unknown option"); } } isns_read_config(opt_configfile); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); if (!isns_config.ic_server_name) usage(1, "Please specify an iSNS server name"); if (!opt_action) usage(1, "Please specify an operating mode"); if (opt_control) { if (!isns_config.ic_security) isns_fatal("Cannot use control mode, security disabled\n"); security = isns_control_security_context(0); if (!security) isns_fatal("Unable to create control security context\n"); /* Create a networked client, using isns.control as * the source name */ clnt = isns_create_client(security, isns_config.ic_control_name); } else if (opt_local) { /* Create a local client, using isns.control as * the source name */ clnt = isns_create_local_client(security, isns_config.ic_control_name); } else { /* Create a networked client, using the configured * source name */ clnt = isns_create_default_client(security); } if (clnt == NULL) return 1; /* We're an interactive app, and don't want to retry * forever if the server refuses us. */ isns_socket_set_disconnect_fatal(clnt->ic_socket); /* Get the IP address we use to talk to the iSNS server */ if (opt_myaddr.ss_family == AF_UNSPEC && !opt_local) { if (!isns_socket_get_local_addr(clnt->ic_socket, &opt_myaddr)) isns_fatal("Unable to obtain my IP address\n"); isns_addr_set_port((struct sockaddr *) &opt_myaddr, 860); } argv += optind; argc -= optind; switch (opt_action) { case DO_REGISTER: status = register_objects(clnt, argc, argv); break; case DO_QUERY: status = query_objects(clnt, argc, argv); break; case DO_QUERY_EID: status = query_entity_id(clnt, argc, argv); break; case DO_LIST: status = list_objects(clnt, argc, argv); break; case DO_DEREGISTER: status = deregister_objects(clnt, argc, argv); break; case DO_DD_REGISTER: status = register_domain(clnt, argc, argv); break; case DO_DD_DEREGISTER: status = deregister_domain(clnt, argc, argv); break; case DO_ENROLL: status = enroll_client(clnt, argc, argv); break; case DO_EDIT_POLICY: status = edit_policy(clnt, argc, argv); break; // case DO_DELETE_POLICY: default: isns_fatal("Not yet implemented\n"); status = 1; /* compiler food */ } return status != ISNS_SUCCESS; } void usage(int exval, const char *msg) { if (msg) fprintf(stderr, "Error: %s\n", msg); fprintf(stderr, "Usage: isnsadm [options] --action ...\n" " --config Specify alternative config fille\n" " --debug Enable debugging (list of debug flags)\n" " --keyfile Where to store newly generated private key\n" " --local Use local Unix socket to talk to isnsd\n" " --control Assume control node identity for authentication\n" " --replace Use replace mode (--register only)\n" "\nThe following actions are supported:\n" " --register Register one or more objects\n" " --deregister Deregister an object (and children)\n" " --query Query iSNS server for objects\n" " --list List all objects of a given type\n" " --enroll Create a new policy object for a client\n" " --edit-policy Edit a policy object\n" " --delete-policy Edit a policy object\n" " --help Display this message\n" "\nUse \"--query help\" to get help on e.g. the query action\n" ); exit(exval); } int parse_registration(char **argv, int argc, isns_object_list_t *objs, isns_object_t *key_obj) { struct sockaddr_storage def_addr; isns_object_t *entity = NULL, *last_portal = NULL, *last_node = NULL; const char *def_port = NULL; int i; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object registration:\n" " isnsadm [-key attr=value] --register type,attr=value,... type,attr=value,...\n" "Where type can be one of:\n" " entity create/update network entity\n" " initiator create iSCSI initiator storage node\n" " target create iSCSI target storage node\n" " control create control node\n" " portal create portal\n" " pg create portal group\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(NULL); exit(0); } if (argc == 0) usage(1, "Missing object list\n"); if (key_obj) { //isns_object_list_append(objs, key_obj); if (isns_object_is_entity(key_obj)) entity = key_obj; } def_addr = opt_myaddr; for (i = 0; i < argc; ++i) { isns_attr_list_t attrlist = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_object_t *obj; char *type, *name, *value, *next_attr; char *attrs[128]; unsigned int nattrs = 0; name = argv[i]; if ((next_attr = strchr(name, ',')) != NULL) *next_attr++ = '\0'; while (next_attr && *next_attr) { if (nattrs > 128) isns_fatal("Too many attributes\n"); /* Show mercy with fat fingered * people,,,,who,cannot,,,type,properly */ if (next_attr[0] != ',') attrs[nattrs++] = next_attr; if ((next_attr = strchr(next_attr, ',')) != NULL) *next_attr++ = '\0'; } if ((value = strchr(name, '=')) != NULL) *value++ = '\0'; type = name; if (!strcmp(name, "entity")) { if (entity == NULL) { isns_error("Cannot create entity object " "within this key object\n"); return 0; } if (value != NULL) isns_object_set_string(entity, ISNS_TAG_ENTITY_IDENTIFIER, value); obj = isns_object_get(entity); goto handle_attributes; } else if (!strcmp(name, "node") || !strcmp(name, "initiator")) { const char *node_name; node_name = isns_config.ic_source_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_INITIATOR_MASK, entity); last_node = obj; isns_addr_set_port((struct sockaddr *) &def_addr, ISNS_DEFAULT_PORT_INITIATOR); def_port = "iscsi"; } else if (!strcmp(name, "target")) { const char *node_name; node_name = isns_config.ic_source_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_TARGET_MASK, entity); last_node = obj; isns_addr_set_port((struct sockaddr *) &def_addr, ISNS_DEFAULT_PORT_TARGET); def_port = "iscsi-target"; } else if (!strcmp(name, "control")) { const char *node_name; node_name = isns_config.ic_control_name; if (value) node_name = value; obj = isns_create_storage_node(node_name, ISNS_ISCSI_CONTROL_MASK, entity); last_node = obj; def_port = NULL; } else if (!strcmp(name, "portal")) { isns_portal_info_t portal_info; if (value == NULL) { if (def_port == NULL) isns_fatal("portal must follow initiator or target\n"); isns_portal_init(&portal_info, (struct sockaddr *) &def_addr, IPPROTO_TCP); } else if (!isns_portal_parse(&portal_info, value, def_port)) isns_fatal("Unable to parse portal=%s\n", value); obj = isns_create_portal(&portal_info, entity); last_portal = obj; } else if (!strcmp(name, "pg")) { if (value) isns_fatal("Unexpected value for portal group\n"); if (!last_portal || !last_node) isns_fatal("Portal group registration must follow portal and node\n"); obj = isns_create_portal_group(last_portal, last_node, 10); } else { isns_error("Unknown object type \"%s\"\n", name); return 0; } if (obj == NULL) { isns_error("Failure to create %s object\n", name); return 0; } isns_object_list_append(objs, obj); handle_attributes: isns_attr_list_parser_init(&state, obj->ie_template); state.default_port = def_port; if (!isns_parse_attrs(nattrs, attrs, &attrlist, &state) || !isns_object_set_attrlist(obj, &attrlist)) { isns_error("Failure to set all %s attributes\n", name); isns_attr_list_destroy(&attrlist); return 0; } isns_attr_list_destroy(&attrlist); isns_object_release(obj); } return 1; } static int __register_objects(isns_client_t *clnt, isns_object_t *key_obj, const isns_object_list_t *objects) { isns_source_t *source = NULL; isns_simple_t *reg; uint32_t status; unsigned int i; for (i = 0; i < objects->iol_count && !source; ++i) { isns_object_t *obj = objects->iol_data[i]; if (!isns_object_is_iscsi_node(obj)) continue; source = isns_source_from_object(obj); } reg = isns_create_registration2(clnt, key_obj, source); isns_registration_set_replace(reg, opt_replace); /* Add all objects to be registered */ for (i = 0; i < objects->iol_count; ++i) isns_registration_add_object(reg, objects->iol_data[i]); status = isns_client_call(clnt, ®); isns_simple_free(reg); if (status == ISNS_SUCCESS) printf("Successfully registered object(s)\n"); else isns_error("Failed to register object(s): %s\n", isns_strerror(status)); if (source) isns_source_release(source); return status; } int register_objects(isns_client_t *clnt, int argc, char **argv) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_object_t *key_obj = NULL; uint32_t status; if (opt_key != NULL) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); if (!isns_parse_attrs(1, &opt_key, &key_attrs, &state)) { isns_error("Cannot parse registration key \"%s\"\n", opt_key); return 0; } key_obj = isns_create_object(isns_attr_list_parser_context(&state), &key_attrs, NULL); isns_attr_list_destroy(&key_attrs); if (!key_obj) { isns_error("Cannot create registration key object\n"); return 0; } } else { /* If the user does not provide a key object, * create/update an entity. */ key_obj = isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, NULL); } if (!parse_registration(argv, argc, &objects, key_obj)) isns_fatal("Unable to parse registration\n"); status = __register_objects(clnt, key_obj, &objects); isns_object_list_destroy(&objects); isns_object_release(key_obj); return status; } /* * Parse the query string given by the user * * 5.6.5.2 * The Message Key may contain key or non-key attributes or no * attributes at all. If multiple attributes are used as the * Message Key, then they MUST all be from the same object type * (e.g., IP address and TCP/UDP Port are attributes of the * Portal object type). */ int parse_query(char **argv, int argc, isns_attr_list_t *keys, isns_attr_list_t *query) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); state.nil_permitted = 1; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --query attr=value attr=value ... ?query-attr ?query-attr ...\n" "All key attributes must refer to a common object type.\n" "Query attributes specify the attributes the server should return," "and can refer to any object type.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } if (argc == 0) isns_fatal("Missing query attributes\n"); return isns_parse_query_attrs(argc, argv, keys, query, &state); } int query_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_attr_list_t oper_attrs = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; uint32_t status; isns_simple_t *qry; unsigned int i; if (!parse_query(argv, argc, &query_key, &oper_attrs)) isns_fatal("Unable to parse query\n"); qry = isns_create_query(clnt, &query_key); isns_attr_list_destroy(&query_key); /* Add the list of attributes we request */ for (i = 0; i < oper_attrs.ial_count; ++i) isns_query_request_attr(qry, oper_attrs.ial_data[i]); isns_attr_list_destroy(&oper_attrs); status = isns_client_call(clnt, &qry); if (status != ISNS_SUCCESS) { isns_error("Query failed: %s\n", isns_strerror(status)); return status; } status = isns_query_response_get_objects(qry, &objects); if (status) { isns_error("Unable to extract object list from query response: %s\n", isns_strerror(status), status); return status; } isns_object_list_print(&objects, isns_print_stdout); isns_object_list_destroy(&objects); isns_simple_free(qry); return status; } int query_entity_id(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; uint32_t status; isns_simple_t *qry; const char *eid; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Query iSNS for own entity ID.\n" "No arguments allowed\n"); exit(0); } if (argc != 0) isns_fatal("EID query - no arguments accepted\n"); isns_attr_list_append_string(&query_key, ISNS_TAG_ISCSI_NAME, isns_config.ic_source_name); qry = isns_create_query(clnt, &query_key); isns_attr_list_destroy(&query_key); isns_query_request_attr_tag(qry, ISNS_TAG_ENTITY_IDENTIFIER); status = isns_client_call(clnt, &qry); if (status != ISNS_SUCCESS) { isns_error("Query failed: %s\n", isns_strerror(status)); return status; } status = isns_query_response_get_objects(qry, &objects); if (status) { isns_error("Unable to extract object list from query response: %s\n", isns_strerror(status), status); return status; } status = ISNS_NO_SUCH_ENTRY; if (objects.iol_count == 0) { isns_error("Node %s not registered with iSNS\n", isns_config.ic_source_name); } else if (!isns_object_get_string(objects.iol_data[0], ISNS_TAG_ENTITY_IDENTIFIER, &eid)) { isns_error("Query for %s returned an object without EID\n", isns_config.ic_source_name); } else { printf("%s\n", eid); status = ISNS_SUCCESS; } isns_object_list_destroy(&objects); isns_simple_free(qry); return status; } /* * Parse the list query string given by the user */ int parse_list(int argc, char **argv, isns_object_template_t **type_p, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_object_template_t *query_type = NULL; char *type_name; if (argc == 0) usage(1, "Missing object type"); if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --list type attr=value attr=value ...\n" "Possible value for :\n" " entities - list all network entites\n" " nodes - list all storage nodes\n" " portals - list all portals\n" " portal-groups - list all portal groups\n" " dds - list all discovery domains\n" " ddsets - list all discovery domains sets\n" " policies - list all policies (privileged)\n" "Additional attributes can be specified to scope the\n" "search. They must match the specified object type.\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(NULL); exit(0); } type_name = *argv++; --argc; if (!strcasecmp(type_name, "entities")) query_type = &isns_entity_template; else if (!strcasecmp(type_name, "nodes")) query_type = &isns_iscsi_node_template; else if (!strcasecmp(type_name, "portals")) query_type = &isns_portal_template; else if (!strcasecmp(type_name, "portal-groups")) query_type = &isns_iscsi_pg_template; else if (!strcasecmp(type_name, "dds")) query_type = &isns_dd_template; else if (!strcasecmp(type_name, "ddsets")) query_type = &isns_ddset_template; else if (!strcasecmp(type_name, "policies")) query_type = &isns_policy_template; else { isns_error("Unknown object type \"%s\"\n", type_name); return 0; } *type_p = query_type; isns_attr_list_parser_init(&state, query_type); state.nil_permitted = 1; return isns_parse_attrs(argc, argv, keys, &state); } int list_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_keys = ISNS_ATTR_LIST_INIT; isns_object_template_t *query_type = NULL; isns_simple_t *simp; int status, count = 0; if (!parse_list(argc, argv, &query_type, &query_keys)) isns_fatal("Unable to parse parameters\n"); simp = isns_create_getnext(clnt, query_type, &query_keys); while (1) { isns_object_t *obj = NULL; isns_simple_t *followup; status = isns_client_call(clnt, &simp); if (status) break; status = isns_getnext_response_get_object(simp, &obj); if (status) break; printf("Object %u:\n", count++); isns_object_print(obj, isns_print_stdout); isns_object_release(obj); followup = isns_create_getnext_followup(clnt, simp, &query_keys); isns_simple_free(simp); simp = followup; } if (status == ISNS_SOURCE_UNAUTHORIZED && query_type == &isns_policy_template && !opt_local) isns_warning("Please use --local trying to list policies\n"); if (status != ISNS_NO_SUCH_ENTRY) { isns_error("GetNext call failed: %s\n", isns_strerror(status)); return status; } return ISNS_SUCCESS; } /* * Parse the deregistration string given by the user * * 5.6.5.2 * The Message Key may contain key or non-key attributes or no * attributes at all. If multiple attributes are used as the * Message Key, then they MUST all be from the same object type * (e.g., IP address and TCP/UDP Port are attributes of the * Portal object type). */ int parse_deregistration(char **argv, int argc, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, NULL); state.multi_type_permitted = 1; state.nil_permitted = 1; if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object deregistration:\n" " isnsadm --deregister attr=value attr=value ...\n" "All attributes must refer to a common object type.\n" "\nThe following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, keys, &state); } int deregister_objects(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *dereg; uint32_t status; if (!parse_deregistration(argv, argc, &query_key)) isns_fatal("Unable to parse unregistration\n"); dereg = isns_create_deregistration(clnt, &query_key); isns_attr_list_destroy(&query_key); status = isns_client_call(clnt, &dereg); if (status != ISNS_SUCCESS) { isns_error("Deregistration failed: %s\n", isns_strerror(status)); return status; } #if 0 status = isns_dereg_msg_response_get_objects(dereg, &objects); if (status) { isns_error("Unable to extract object list from deregistration response: %s\n", isns_strerror(status), status); goto done; } isns_object_list_print(&objects, isns_print_stdout); #endif isns_object_list_destroy(&objects); isns_simple_free(dereg); return status; } /* * Handle discovery domain registration/deregistration */ int parse_dd_registration(char **argv, int argc, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_dd_template); if (argc == 1 && !strcmp(argv[0], "help")) { printf("Object query:\n" " isnsadm --dd-register attr=value attr=value ...\n" "You cannot specify more than one domain.\n" "If you want to modify an existing domain, you must specify its ID.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, keys, &state); } int register_domain(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_simple_t *msg; uint32_t status; if (!parse_dd_registration(argv, argc, &attrs)) isns_fatal("Unable to parse DD registration\n"); msg = isns_create_dd_registration(clnt, &attrs); isns_attr_list_destroy(&attrs); if (msg == NULL) { isns_error("Cannot create message\n"); return ISNS_INTERNAL_ERROR; } status = isns_client_call(clnt, &msg); if (status != ISNS_SUCCESS) { isns_error("Registration failed: %s\n", isns_strerror(status)); return status; } if (status == ISNS_SUCCESS) { printf("Registered DD:\n"); isns_attr_list_print( isns_simple_get_attrs(msg), isns_print_stdout); } isns_simple_free(msg); return status; } int parse_dd_deregistration(char **argv, int argc, uint32_t *dd_id, isns_attr_list_t *keys) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_dd_template); if (argc == 0 || (argc == 1 && !strcmp(argv[0], "help"))) { printf("DD deregistration:\n" " isnsadm --dd-deregister dd-id attr=value attr=value ...\n" "You cannot specify more than one domain.\n" "The following attributes are recognized:\n"); isns_attr_list_parser_help(&state); exit(0); } *dd_id = parse_count(argv[0]); return isns_parse_attrs(argc - 1, argv + 1, keys, &state); } int deregister_domain(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_simple_t *msg; uint32_t dd_id, status; if (!parse_dd_deregistration(argv, argc, &dd_id, &attrs)) isns_fatal("Unable to parse DD registration\n"); msg = isns_create_dd_deregistration(clnt, dd_id, &attrs); isns_attr_list_destroy(&attrs); if (msg == NULL) { isns_error("Cannot create message\n"); return ISNS_INTERNAL_ERROR; } status = isns_client_call(clnt, &msg); if (status != ISNS_SUCCESS) { isns_error("Deregistration failed: %s\n", isns_strerror(status)); return status; } isns_simple_free(msg); return status; } /* * Parse a policy */ int parse_policy(int argc, char **argv, isns_attr_list_t *attrs, const char *help_title, const char *help_action) { struct isns_attr_list_parser state; isns_attr_list_parser_init(&state, &isns_policy_template); state.nil_permitted = 0; state.load_key = load_key_callback; state.generate_key = generate_key_callback; if (argc == 1 && !strcmp(argv[0], "help")) { printf("%s:\n" " isnsadm %s attr=value attr=value ...\n" "Specifying a Security Policy Index is mandatory.\n" "\nThe following attributes are recognized:\n", help_title, help_action); isns_attr_list_parser_help(&state); exit(0); } return isns_parse_attrs(argc, argv, attrs, &state); } static int __create_policy(isns_client_t *clnt, const isns_attr_list_t *attrs) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_object_t *obj; int status; obj = isns_create_object(&isns_policy_template, attrs, NULL); if (!obj) isns_fatal("Cannot create policy object\n"); isns_object_list_append(&objects, obj); status = __register_objects(clnt, NULL, &objects); isns_object_list_destroy(&objects); return status; } /* * Enroll a new client */ int enroll_client(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; const char *client_name; int status; if (argc == 0) usage(1, "Missing client name"); client_name = *argv++; --argc; isns_attr_list_append_string(&attrs, OPENISNS_TAG_POLICY_SPI, client_name); #if 0 isns_attr_list_append_string(&attrs, OPENISNS_TAG_POLICY_SOURCE_NAME, client_name); #endif if (!opt_keyfile) { static char namebuf[PATH_MAX]; snprintf(namebuf, sizeof(namebuf), "%s.key", client_name); opt_keyfile = namebuf; } if (argc && !parse_policy(argc, argv, &attrs, "Enroll an iSNS client", "--enroll hostname")) isns_fatal("Cannot parse policy\n"); /* If no key is given, generate one */ if (!isns_attr_list_contains(&attrs, OPENISNS_TAG_POLICY_KEY)) { printf("No key given, generating one\n"); isns_attr_list_append_attr(&attrs, generate_key_callback()); } status = __create_policy(clnt, &attrs); isns_attr_list_destroy(&attrs); return status; } /* * Create a new policy */ int edit_policy(isns_client_t *clnt, int argc, char **argv) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; int status; if (!parse_policy(argc, argv, &attrs, "Edit an existing policy", "--edit-policy")) isns_fatal("Cannot parse policy\n"); status = __create_policy(clnt, &attrs); isns_attr_list_destroy(&attrs); return status; } #ifdef WITH_SECURITY static isns_attr_t * __key_to_attr(EVP_PKEY *pkey) { struct __isns_opaque key; isns_value_t value; isns_attr_t *attr = NULL; if (!isns_dsa_encode_public(pkey, &key.ptr, &key.len)) goto out; /* Must pad key. This means we may end up encoding a few * bytes of trash. Oh well. */ key.len = ISNS_PAD(key.len); value = ISNS_VALUE_INIT(opaque, key); attr = isns_attr_alloc(OPENISNS_TAG_POLICY_KEY, NULL, &value); isns_free(key.ptr); out: EVP_PKEY_free(pkey); return attr; } isns_attr_t * generate_key_callback(void) { EVP_PKEY *pkey; if (opt_keyfile == NULL) isns_fatal("Key generation requires --keyfile option\n"); if (!(pkey = isns_dsa_generate_key())) isns_fatal("Key generation failed\n"); if (!isns_dsa_store_private(opt_keyfile, pkey)) isns_fatal("Unable to write private key to %s\n", opt_keyfile); printf("Stored DSA private key in %s\n", opt_keyfile); return __key_to_attr(pkey); } isns_attr_t * load_key_callback(const char *pathname) { EVP_PKEY *pkey; if (!(pkey = isns_dsa_load_public(pathname))) isns_fatal("Unable to load public key from file %s\n", pathname); return __key_to_attr(pkey); } #else /* WITH_SECURITY */ isns_attr_t * generate_key_callback(void) { isns_fatal("Authentication disabled in this build\n"); return NULL; } isns_attr_t * load_key_callback(const char *pathname) { isns_fatal("Authentication disabled in this build\n"); return NULL; } #endif open-iscsi-2.0.873/utils/open-isns/isnsd.c000066400000000000000000000143061175631155400203170ustar00rootroot00000000000000/* * isnsd - the iSNS Daemon * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #ifdef MTRACE # include #endif #include #include "security.h" #include "util.h" #include "paths.h" #include "internal.h" enum { MODE_NORMAL, MODE_DUMP_DB, MODE_INIT, }; static const char * opt_configfile = ISNS_DEFAULT_ISNSD_CONFIG; static int opt_af = AF_UNSPEC; static int opt_mode = MODE_NORMAL; static int opt_foreground = 0; static char * slp_url; static int init_server(void); static void run_server(isns_server_t *, isns_db_t *); static void usage(int, const char *); static void cleanup(int); static struct option options[] = { { "config", required_argument, NULL, 'c' }, { "debug", required_argument, NULL, 'd' }, { "foreground", no_argument, NULL, 'f' }, { "init", no_argument, NULL, MODE_INIT }, { "dump-db", no_argument, NULL, MODE_DUMP_DB }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL } }; int main(int argc, char **argv) { isns_server_t *server; isns_source_t *source; isns_db_t *db; int c; #ifdef MTRACE mtrace(); #endif while ((c = getopt_long(argc, argv, "46c:d:fh", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'f': opt_foreground = 1; break; case MODE_DUMP_DB: case MODE_INIT: opt_mode = c; break; case 'h': usage(0, NULL); case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch \n", OPENISNS_VERSION_STRING); return 0; default: usage(1, "Unknown option"); } } if (optind != argc) usage(1, NULL); isns_read_config(opt_configfile); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); source = isns_source_create_iscsi(isns_config.ic_source_name); if (opt_mode == MODE_INIT) return !init_server(); if (opt_mode == MODE_NORMAL) isns_write_pidfile(isns_config.ic_pidfile); db = isns_db_open(isns_config.ic_database); if (db == NULL) isns_fatal("Unable to open database\n"); if (opt_mode == MODE_DUMP_DB) { isns_db_print(db, isns_print_stdout); exit(0); } if (!opt_foreground) { if (daemon(0, 0) < 0) isns_fatal("Unable to background server process\n"); isns_log_background(); isns_update_pidfile(isns_config.ic_pidfile); } signal(SIGTERM, cleanup); signal(SIGINT, cleanup); server = isns_create_server(source, db, &isns_default_service_ops); run_server(server, db); return 0; } void usage(int exval, const char *msg) { if (msg) fprintf(stderr, "Error: %s\n", msg); fprintf(stderr, "Usage: isnsd [options]\n\n" " --config Specify alternative config fille\n" " --foreground Do not put daemon in the background\n" " --debug Enable debugging (list of debug flags)\n" " --init Initialize the server (key generation etc)\n" " --dump-db Display the database contents and exit\n" " --help Print this message\n" ); exit(exval); } void cleanup(int sig) { isns_remove_pidfile(isns_config.ic_pidfile); exit(1); } static void slp_cleanup(void) { char *url = slp_url; slp_url = NULL; if (url) { isns_slp_unregister(url); isns_free(url); } } /* * Initialize server */ int init_server(void) { if (!isns_security_init()) return 0; /* Anything else? */ return 1; } /* * Server main loop */ void run_server(isns_server_t *server, isns_db_t *db) { isns_socket_t *sock; isns_security_t *ctx = NULL; isns_message_t *msg, *resp; int status; if (isns_config.ic_security) { const char *ksname; isns_keystore_t *ks; ctx = isns_default_security_context(1); if (!(ksname = isns_config.ic_client_keystore)) isns_fatal("config problem: no key store specified\n"); if (!strcasecmp(ksname, "db:")) ks = isns_create_db_keystore(db); else ks = isns_create_keystore(ksname); if (ks == NULL) isns_fatal("Unable to create keystore %s\n", ksname); isns_security_set_keystore(ctx, ks); } status = isns_dd_load_all(db); if (status != ISNS_SUCCESS) isns_fatal("Problem loading Discovery Domains from database\n"); if (isns_config.ic_control_socket) { sock = isns_create_server_socket(isns_config.ic_control_socket, NULL, AF_UNSPEC, SOCK_STREAM); if (sock == NULL) isns_fatal("Unable to create control socket\n"); /* isns_socket_set_security_ctx(sock, ctx); */ } sock = isns_create_server_socket(isns_config.ic_bind_address, "isns", opt_af, SOCK_STREAM); if (sock == NULL) isns_fatal("Unable to create server socket\n"); isns_socket_set_security_ctx(sock, ctx); if (isns_config.ic_slp_register) { slp_url = isns_slp_build_url(0); isns_slp_register(slp_url); atexit(slp_cleanup); } isns_esi_init(server); isns_scn_init(server); while (1) { struct timeval timeout = { 0, 0 }; time_t now, then, next_timeout = time(NULL) + 3600; /* Expire entities that haven't seen any activity * for a while. */ if (isns_config.ic_registration_period) { then = isns_db_expire(db); if (then && then < next_timeout) next_timeout = then; } /* Run any timers (eg for ESI) */ then = isns_run_timers(); if (then && then < next_timeout) next_timeout = then; /* There may be pending SCNs, push them out now */ then = isns_scn_transmit_all(); if (then && then < next_timeout) next_timeout = then; /* Purge any objects that have been marked for removal * from the DB (deleting them, or moving them to limbo * state). */ isns_db_purge(db); /* Determine how long we can sleep before working * the ESI queues and DB expiry again. */ now = time(NULL); if (next_timeout <= now) continue; timeout.tv_sec = next_timeout - now; if ((msg = isns_recv_message(&timeout)) == NULL) continue; if ((resp = isns_process_message(server, msg)) != NULL) { isns_socket_t *sock = isns_message_socket(msg); isns_socket_send(sock, resp); isns_message_release(resp); } isns_message_release(msg); } } open-iscsi-2.0.873/utils/open-isns/isnsdd.c000066400000000000000000000676661175631155400205040ustar00rootroot00000000000000/* * isnsdd - the iSNS Discovery Daemon * * Copyright (C) 2007 Olaf Kirch * * The way isnsdd communicates with local services (initiator, * target) is via a set of files and signals. That sounds rather * awkward, but it's a lot simpler to add to these services * than another socket based communication mechanism I guess. */ #include #include #include #include #include #include #include #ifdef MTRACE # include #endif #include #include "security.h" #include "util.h" #include "isns-proto.h" #include "paths.h" #include "attrs.h" enum { ROLE_INITIATOR = 1, ROLE_MONITOR = 2, }; #define ISNSDD_REG_NAME "isns" #define ISNSDD_PGT_OFFSET 10000 #define MAX_RETRY_TIMEOUT 300 typedef struct isns_proxy isns_proxy_t; struct isns_proxy { isns_list_t ip_list; char * ip_eid; isns_object_t * ip_entity; isns_client_t * ip_client; isns_object_list_t ip_objects; time_t ip_last_registration; }; static const char * opt_configfile = ISNS_DEFAULT_ISNSDD_CONFIG; static int opt_af = AF_INET6; static int opt_foreground = 0; static int opt_role = ROLE_INITIATOR; static int opt_scn_bits = ISNS_SCN_OBJECT_UPDATED_MASK | ISNS_SCN_OBJECT_ADDED_MASK | ISNS_SCN_OBJECT_REMOVED_MASK | ISNS_SCN_TARGET_AND_SELF_ONLY_MASK; static unsigned int opt_retry_timeout = 10; static int opt_esi = 1; static isns_socket_t * server_socket; static ISNS_LIST_DECLARE(proxies); static isns_object_list_t local_registry = ISNS_OBJECT_LIST_INIT; static isns_object_list_t local_portals = ISNS_OBJECT_LIST_INIT; static isns_object_list_t visible_nodes = ISNS_OBJECT_LIST_INIT; static unsigned int esi_interval; static int should_reexport; static void run_discovery(isns_server_t *srv); static void scn_callback(isns_db_t *, uint32_t, isns_object_template_t *, const char *, const char *); static void refresh_registration(void *); static void retry_registration(void *); static void load_exported_objects(void); static void store_imported_objects(void); static void usage(int, const char *); static void install_sighandler(int, void (*func)(int)); static void sig_cleanup(int); static void sig_reread(int); static struct option options[] = { { "config", required_argument, NULL, 'c' }, { "debug", required_argument, NULL, 'd' }, { "foreground", no_argument, NULL, 'f' }, { "role", required_argument, NULL, 'r' }, { "no-esi", no_argument, NULL, 'E' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL } }; int main(int argc, char **argv) { isns_server_t *server; isns_source_t *source; isns_db_t *db; int c; #ifdef MTRACE mtrace(); #endif while ((c = getopt_long(argc, argv, "46c:d:Efhr:", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'E': opt_esi = 0; break; case 'f': opt_foreground = 1; break; case 'h': usage(0, NULL); case 'r': if (!strcasecmp(optarg, "initiator")) opt_role = ROLE_INITIATOR; else if (!strcasecmp(optarg, "control") || !strcasecmp(optarg, "monitor")) opt_role = ROLE_MONITOR; else { isns_error("Unknown role \"%s\"\n", optarg); usage(1, NULL); } break; case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch \n", OPENISNS_VERSION_STRING); return 0; default: usage(1, "Unknown option"); } } if (optind != argc) usage(1, NULL); /* If the config code derives the source name * automatically, we want it to be distinct from * any other source name (chosen by eg the iSCSI * initiator). Adding a suffix of ":isns" is a * somewhat lame attempt. */ isns_config.ic_source_suffix = "isns"; isns_read_config(opt_configfile); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); source = isns_source_create_iscsi(isns_config.ic_source_name); isns_write_pidfile(isns_config.ic_pidfile); if (!opt_foreground) { if (daemon(0, 0) < 0) isns_fatal("Unable to background server process\n"); isns_log_background(); isns_update_pidfile(isns_config.ic_pidfile); } install_sighandler(SIGTERM, sig_cleanup); install_sighandler(SIGINT, sig_cleanup); install_sighandler(SIGUSR2, sig_reread); /* Create a DB object that shadows our portal list. This is for ESI - * when an ESI comes in, the library will look up the portal in this * database, and update its mtime. By checking the mtime at regular * intervals, we can verify whether the server's ESIs actually * reach us. */ db = isns_db_open_shadow(&local_portals); server = isns_create_server(source, db, &isns_callback_service_ops); isns_server_set_scn_callback(server, scn_callback); run_discovery(server); return 0; } void usage(int exval, const char *msg) { if (msg) fprintf(stderr, "Error: %s\n", msg); fprintf(stderr, "Usage: isnsdd [options]\n\n" " --role Specify role (one of initiator, control)\n" " --config Specify alternative config fille\n" " --foreground Do not put daemon in the background\n" " --no-esi Do not try to register an portals for ESI status inquiries\n" " --debug Enable debugging (list of debug flags)\n" " --help Print this message\n" ); exit(exval); } void install_sighandler(int signo, void (*func)(int)) { struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = func; sigaction(signo, &act, NULL); } void sig_reread(int sig) { should_reexport = 1; } void sig_cleanup(int sig) { isns_remove_pidfile(isns_config.ic_pidfile); exit(1); } /* * Proxy handling functions */ static isns_proxy_t * isns_create_proxy(const char *eid) { isns_proxy_t *proxy; proxy = calloc(1, sizeof(*proxy)); isns_list_init(&proxy->ip_list); proxy->ip_eid = strdup(eid); return proxy; } static isns_proxy_t * __isns_proxy_find(isns_list_t *head, const char *eid) { isns_list_t *pos, *next; isns_list_foreach(head, pos, next) { isns_proxy_t *proxy = isns_list_item(isns_proxy_t, ip_list, pos); if (!strcmp(proxy->ip_eid, eid)) return proxy; } return NULL; } static isns_proxy_t * isns_proxy_by_entity(const isns_object_t *entity) { isns_list_t *pos, *next; isns_list_foreach(&proxies, pos, next) { isns_proxy_t *proxy = isns_list_item(isns_proxy_t, ip_list, pos); if (proxy->ip_entity == entity) return proxy; } return NULL; } static void isns_proxy_erase(isns_proxy_t *proxy) { isns_object_list_destroy(&proxy->ip_objects); if (proxy->ip_client) { isns_client_destroy(proxy->ip_client); proxy->ip_client = NULL; } if (proxy->ip_entity) { isns_object_release(proxy->ip_entity); proxy->ip_entity = NULL; } isns_cancel_timer(refresh_registration, proxy); } static void isns_proxy_free(isns_proxy_t *proxy) { isns_proxy_erase(proxy); isns_list_del(&proxy->ip_list); free(&proxy->ip_eid); free(proxy); } /* * Force a re-registration of the whole object set. */ static void force_reregistration(isns_proxy_t *proxy) { isns_cancel_timer(refresh_registration, proxy); isns_add_oneshot_timer(0, retry_registration, proxy); } /* * Refresh the registration by calling DevAttrQry */ static void refresh_registration(void *ptr) { isns_proxy_t *proxy = ptr; isns_client_t *clnt = proxy->ip_client; isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT; isns_simple_t *qry = NULL; uint32_t status; isns_debug_state("Refreshing registration for %s\n", proxy->ip_eid); isns_attr_list_append_string(&query_key, ISNS_TAG_ENTITY_IDENTIFIER, proxy->ip_eid); qry = isns_create_query(clnt, &query_key); isns_attr_list_destroy(&query_key); /* We should have an async call mechanism. If the server * is wedged, we'll block here, unable to service any other * functions. */ status = isns_simple_call(clnt->ic_socket, &qry); if (status != ISNS_SUCCESS) { isns_error("Query failed: %s\n", isns_strerror(status)); goto re_register; } status = isns_query_response_get_objects(qry, &objects); isns_simple_free(qry); if (status == ISNS_SUCCESS) { if (objects.iol_count != 0) return; } else { isns_error("Unable to parse query response\n"); } re_register: isns_warning("Lost registration, trying to re-register\n"); force_reregistration(proxy); } /* * Check if all portals have seen ESI messages from the server */ static void check_portal_registration(void *ptr) { isns_object_list_t bad_portals = ISNS_OBJECT_LIST_INIT; unsigned int i, need_reregister = 0, good_portals = 0; time_t now; isns_debug_state("%s()\n", __FUNCTION__); now = time(NULL); for (i = 0; i < local_portals.iol_count; ++i) { isns_object_t *obj = local_portals.iol_data[i]; isns_portal_info_t portal_info; isns_proxy_t *proxy; time_t last_modified; uint32_t interval; if (!isns_object_get_uint32(obj, ISNS_TAG_ESI_INTERVAL, &interval)) continue; last_modified = isns_object_last_modified(obj); if (last_modified + 2 * interval > now) { good_portals++; continue; } isns_portal_from_object(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, obj); isns_notice("Portal %s did not receive ESIs within %u seconds - " "server may have lost us.\n", isns_portal_string(&portal_info), now - last_modified); proxy = isns_proxy_by_entity(isns_object_get_entity(obj)); if (!proxy) continue; /* If we haven't received ANY ESIs, ever, the portal * may be using a non-routable IP */ if (last_modified <= proxy->ip_last_registration) isns_object_list_append(&bad_portals, obj); force_reregistration(proxy); need_reregister++; } for (i = 0; i < bad_portals.iol_count; ++i) isns_object_list_remove(&local_portals, bad_portals.iol_data[i]); isns_object_list_destroy(&bad_portals); if (need_reregister && local_portals.iol_count == 0) { /* Force a re-registration from scratch. * This time without ESI. */ isns_notice("Suspiciously little ESI traffic - server may be broken\n"); isns_notice("Disabling ESI\n"); opt_esi = 0; } } static void setup_esi_watchdog(void) { unsigned int i; isns_cancel_timer(check_portal_registration, NULL); esi_interval = 0; for (i = 0; i < local_portals.iol_count; ++i) { isns_object_t *obj = local_portals.iol_data[i]; uint32_t interval; /* should always succeed */ if (isns_object_get_uint32(obj, ISNS_TAG_ESI_INTERVAL, &interval)) continue; if (!esi_interval || interval < esi_interval) esi_interval = interval; } if (esi_interval) { isns_debug_state("Setting up timer to check for ESI reachability\n"); isns_add_timer(esi_interval * 4 / 5, check_portal_registration, NULL); } } static void load_exported_objects(void) { isns_debug_state("Reading list of exported objects\n"); isns_object_list_destroy(&local_registry); if (!isns_local_registry_load("!" ISNSDD_REG_NAME, 0, &local_registry)) { isns_warning("Unable to obtain locally registered objects\n"); return; } } static void store_imported_objects(void) { if (!isns_local_registry_store(ISNSDD_REG_NAME, 0, &visible_nodes)) isns_warning("Unable to store discovered objects\n"); } /* * Given the DevAttrReg response, extract the entity ID we * have been assigned. */ static int extract_entity_id(isns_proxy_t *proxy, isns_simple_t *resp) { isns_object_list_t resp_objects = ISNS_OBJECT_LIST_INIT; isns_object_t *entity = NULL; int status; unsigned int i; status = isns_query_response_get_objects(resp, &resp_objects); if (status) { isns_error("Unable to extract object list from " "registration response: %s\n", isns_strerror(status), status); goto out; } for (i = 0; i < resp_objects.iol_count; ++i) { isns_object_t *obj = resp_objects.iol_data[i]; uint32_t interval; if (!isns_object_is_entity(obj)) continue; if (entity) { isns_error("Server returns more than one entity " "in registration response. What a weirdo.\n"); continue; } entity = obj; if (!isns_object_get_uint32(obj, ISNS_TAG_REGISTRATION_PERIOD, &interval)) continue; if (interval == 0) { isns_error("Server returns a registration period of 0\n"); continue; } isns_debug_state("Setting up timer for registration refresh\n"); isns_add_timer(interval / 2, refresh_registration, proxy); } for (i = 0; i < resp_objects.iol_count; ++i) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_t *obj = resp_objects.iol_data[i]; uint32_t interval; if (!isns_object_is_portal(obj) || !isns_object_get_uint32(obj, ISNS_TAG_ESI_INTERVAL, &interval)) continue; if (interval == 0) { isns_error("Server returns an ESI interval of 0\n"); continue; } isns_object_get_key_attrs(obj, &key_attrs); if (!(obj = isns_object_list_lookup(&proxy->ip_objects, NULL, &key_attrs))) { isns_error("Server response includes a portal we never registered\n"); continue; } isns_object_set_uint32(obj, ISNS_TAG_ESI_INTERVAL, interval); /* Server enabled ESI for this portal, so add it to * the list of local portals we regularly check for * incoming ESI messages. */ isns_object_list_append(&local_portals, obj); } proxy->ip_last_registration = time(NULL); out: isns_object_list_destroy(&resp_objects); return status; } static inline void __add_release_object(isns_object_list_t *objects, isns_object_t *cur) { if (cur == NULL) return; isns_object_list_append(objects, cur); isns_object_release(cur); } /* * Rebuild the list of proxies given the set of entities */ void rebuild_proxy_list(isns_object_list_t *entities, isns_list_t *old_list) { isns_proxy_t *proxy; unsigned int i; isns_list_move(old_list, &proxies); for (i = 0; i < entities->iol_count; ++i) { isns_object_t *entity = entities->iol_data[i]; isns_object_t *node; const char *eid; eid = isns_entity_name(entity); if (eid == NULL) { isns_error("Whoopee, entity without name\n"); continue; } proxy = __isns_proxy_find(old_list, eid); if (proxy == NULL) { proxy = isns_create_proxy(eid); } else { isns_proxy_erase(proxy); } isns_object_list_append(&proxy->ip_objects, entity); isns_object_get_descendants(entity, NULL, &proxy->ip_objects); node = isns_object_list_lookup(&proxy->ip_objects, &isns_iscsi_node_template, NULL); if (node == NULL) { isns_warning("Service %s did not register any " "storage nodes - skipped\n", eid); continue; } proxy->ip_client = isns_create_client(NULL, isns_storage_node_name(node)); proxy->ip_entity = isns_object_get(entity); isns_list_del(&proxy->ip_list); isns_list_append(&proxies, &proxy->ip_list); } } /* * Unregister old proxies */ static void unregister_entities(isns_list_t *list) { while (!isns_list_empty(list)) { isns_proxy_t *proxy = isns_list_item(isns_proxy_t, ip_list, list->next); /* XXX send a DevDereg */ isns_proxy_free(proxy); } } /* * The local registry creates fake entities to group objects * registered by the same service. We use this to perform * several registration calls, each with a different EID */ static int register_entity(isns_proxy_t *proxy) { isns_client_t *clnt = proxy->ip_client; isns_simple_t *call = NULL; int status; call = isns_create_registration(clnt, proxy->ip_entity); isns_registration_set_replace(call, 1); isns_registration_add_object_list(call, &proxy->ip_objects); status = isns_simple_call(clnt->ic_socket, &call); if (status == ISNS_SUCCESS) { /* Extract the EID and registration period */ extract_entity_id(proxy, call); } isns_simple_free(call); return status; } static int register_exported_entities(void) { int status = ISNS_SUCCESS; isns_list_t *pos, *next; isns_list_foreach(&proxies, pos, next) { isns_proxy_t *proxy = isns_list_item(isns_proxy_t, ip_list, pos); status = register_entity(proxy); if (status != ISNS_SUCCESS) break; } setup_esi_watchdog(); return status; } static void all_objects_set(isns_object_list_t *list, uint32_t tag, uint32_t value) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_set_uint32(obj, tag, value); } } static void all_objects_unset(isns_object_list_t *list, uint32_t tag) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_delete_attr(obj, tag); } } static int register_exported_objects(isns_client_t *clnt) { isns_portal_info_t portal_info; isns_object_list_t entities = ISNS_OBJECT_LIST_INIT; isns_object_list_t portals = ISNS_OBJECT_LIST_INIT; isns_simple_t *call = NULL; int status, with_esi; unsigned int i, my_port; isns_list_t old_proxies; if (!isns_socket_get_portal_info(server_socket, &portal_info)) isns_fatal("Unable to get portal info\n"); my_port = isns_portal_tcpudp_port(&portal_info); /* Look up all entites and portals */ isns_object_list_gang_lookup(&local_registry, &isns_entity_template, NULL, &entities); isns_object_list_gang_lookup(&local_registry, &isns_portal_template, NULL, &portals); isns_list_init(&old_proxies); rebuild_proxy_list(&entities, &old_proxies); unregister_entities(&old_proxies); /* Enable SCN on all portals we're about to register */ all_objects_set(&portals, ISNS_TAG_SCN_PORT, my_port); /* Try ESI first. If the server doesn't support it, or doesn't * have the resources to serve us, fall back to normal * registration refresh. */ if (opt_esi) { all_objects_set(&portals, ISNS_TAG_ESI_INTERVAL, isns_config.ic_esi_min_interval); all_objects_set(&portals, ISNS_TAG_ESI_PORT, my_port); } for (with_esi = opt_esi; 1; with_esi--) { status = register_exported_entities(); /* At some point, we need to add these portals * to the local_portals list so that ESI works * properly. * Right now, we extract the portals from the response * and add those. The down side of this is that we no * longer use the same object (pointer) to refer to the * same thing. The up side is that the information returned * by the server reflects the correct ESI interval. */ if (status == ISNS_SUCCESS) break; if (status != ISNS_ESI_NOT_AVAILABLE || with_esi == 0) { isns_error("Failed to register object(s): %s\n", isns_strerror(status)); goto out; } /* Continue and retry without ESI */ all_objects_unset(&portals, ISNS_TAG_ESI_INTERVAL); all_objects_unset(&portals, ISNS_TAG_ESI_PORT); } for (i = 0; i < local_registry.iol_count; ++i) { isns_object_t *obj = local_registry.iol_data[i]; isns_source_t *source; int status; if (!isns_object_is_iscsi_node(obj) && !isns_object_is_fc_port(obj)) continue; if (!(source = isns_source_from_object(obj))) continue; call = isns_create_scn_registration2(clnt, opt_scn_bits, source); status = isns_simple_call(clnt->ic_socket, &call); if (status != ISNS_SUCCESS) { isns_error("SCN registration for %s failed: %s\n", isns_storage_node_name(obj), isns_strerror(status)); } isns_source_release(source); } out: if (call) isns_simple_free(call); isns_object_list_destroy(&entities); isns_object_list_destroy(&portals); return status; } static void retry_registration(void *ptr) { isns_proxy_t *proxy = ptr; static unsigned int timeout = 0; int status; status = register_exported_objects(proxy->ip_client); if (status) { if (timeout == 0) timeout = opt_retry_timeout; else if (timeout >= MAX_RETRY_TIMEOUT) timeout = MAX_RETRY_TIMEOUT; isns_debug_state("Retrying to register in %u seconds\n", timeout); isns_add_oneshot_timer(timeout, retry_registration, proxy); /* Exponential backoff */ timeout <<= 1; } } /* * Get a list of all visible storage nodes */ static int get_objects_from_query(isns_simple_t *resp) { isns_object_list_t resp_objects = ISNS_OBJECT_LIST_INIT; unsigned int i; int status; status = isns_query_response_get_objects(resp, &resp_objects); if (status) { isns_error("Unable to extract object list from " "query response: %s\n", isns_strerror(status)); return status; } isns_debug_state("Initial query returned %u object(s)\n", resp_objects.iol_count); for (i = 0; i < resp_objects.iol_count; ++i) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_t *obj = resp_objects.iol_data[i]; isns_object_t *found; if (!isns_object_extract_keys(obj, &key_attrs)) continue; /* Don't add an object twice, and don't add objects * that *we* registered. * This still leaves any default PGs created by the server, * but we cannot help that (for now). */ found = isns_object_list_lookup(&visible_nodes, NULL, &key_attrs); if (!found) found = isns_object_list_lookup(&local_registry, NULL, &key_attrs); if (found) { isns_object_release(found); } else { isns_object_list_append(&visible_nodes, obj); } isns_attr_list_destroy(&key_attrs); } isns_object_list_destroy(&resp_objects); return status; } static int query_storage_node(isns_source_t *source, const char *name) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_simple_t *call; uint32_t tag; int status; isns_client_t *clnt; if (isns_source_type(source) != ISNS_TAG_ISCSI_NAME) { isns_error("FC source node - doesn't work yet\n"); return ISNS_SUCCESS; } clnt = isns_create_client(NULL, isns_source_name(source)); tag = isns_source_type(source); if (name) { isns_attr_list_append_string(&key_attrs, tag, name); } else { /* Query for visible nodes */ isns_attr_list_append_nil(&key_attrs, tag); } call = isns_create_query2(clnt, &key_attrs, source); isns_attr_list_destroy(&key_attrs); isns_query_request_attr_tag(call, tag); switch (tag) { case ISNS_TAG_ISCSI_NAME: isns_query_request_attr_tag(call, ISNS_TAG_ISCSI_NODE_TYPE); isns_query_request_attr_tag(call, ISNS_TAG_ISCSI_ALIAS); isns_query_request_attr_tag(call, ISNS_TAG_ISCSI_NODE_INDEX); isns_query_request_attr_tag(call, ISNS_TAG_PORTAL_IP_ADDRESS); isns_query_request_attr_tag(call, ISNS_TAG_PORTAL_TCP_UDP_PORT); isns_query_request_attr_tag(call, ISNS_TAG_PORTAL_INDEX); isns_query_request_attr_tag(call, ISNS_TAG_PG_ISCSI_NAME); isns_query_request_attr_tag(call, ISNS_TAG_PG_PORTAL_IP_ADDR); isns_query_request_attr_tag(call, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT); isns_query_request_attr_tag(call, ISNS_TAG_PG_TAG); isns_query_request_attr_tag(call, ISNS_TAG_PG_INDEX); break; default: ; } status = isns_simple_call(clnt->ic_socket, &call); if (status == ISNS_SUCCESS) status = get_objects_from_query(call); isns_simple_free(call); isns_client_destroy(clnt); return status; } /* * Query for visible iscsi nodes */ static int query_visible(void) { unsigned int i; for (i = 0; i < local_registry.iol_count; ++i) { isns_object_t *obj = local_registry.iol_data[i]; isns_source_t *source; int status; if (!isns_object_is_iscsi_node(obj) && !isns_object_is_fc_port(obj)) continue; if (isns_object_is_fc_port(obj)) { isns_error("FC source node - sorry, won't work yet\n"); continue; } if (!(source = isns_source_from_object(obj))) continue; status = query_storage_node(source, NULL); if (status != ISNS_SUCCESS) { isns_warning("Unable to run query on behalf of %s: %s\n", isns_storage_node_name(obj), isns_strerror(status)); } isns_source_release(source); } return ISNS_SUCCESS; } /* * Invoke the registered callout program */ static void callout(const char *how, isns_object_t *obj, unsigned int bitmap) { char *argv[128]; int fargc, argc = 0; pid_t pid; if (!isns_config.ic_scn_callout) return; argv[argc++] = isns_config.ic_scn_callout; argv[argc++] = (char *) how; fargc = argc; argc += isns_print_attrs(obj, argv + argc, 128 - argc); pid = fork(); if (pid == 0) { execv(argv[0], argv); isns_fatal("Cannot execute %s: %m\n", argv[0]); } while (fargc < argc) isns_free(argv[fargc++]); if (pid < 0) { isns_error("fork: %m\n"); return; } while (waitpid(pid, NULL, 0) < 0) ; } /* * This is called when we receive a State Change Notification */ static void scn_callback(isns_db_t *db, uint32_t bitmap, isns_object_template_t *node_type, const char *node_name, const char *dst_name) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; uint32_t key_tag; isns_object_t *node = NULL, *recipient = NULL; isns_notice("%s \"%s\" %s\n", isns_object_template_name(node_type), node_name, isns_event_string(bitmap)); /* This is either an iSCSI node or a FC node - in both cases the storage node name is the key attr */ if (node_type == &isns_iscsi_node_template) { key_tag = ISNS_TAG_ISCSI_NAME; } else if (node_type == &isns_fc_node_template) { key_tag = ISNS_TAG_FC_PORT_NAME_WWPN; } else return; isns_attr_list_append_string(&key_attrs, key_tag, dst_name); recipient = isns_object_list_lookup(&local_registry, node_type, &key_attrs); if (recipient == NULL) { isns_error("Received SCN for unknown recipient \"%s\"\n", dst_name); goto out; } isns_attr_list_destroy(&key_attrs); isns_attr_list_append_string(&key_attrs, key_tag, node_name); node = isns_object_list_lookup(&visible_nodes, node_type, &key_attrs); if (bitmap & (ISNS_SCN_OBJECT_REMOVED_MASK|ISNS_SCN_DD_MEMBER_REMOVED_MASK)) { if (node) { isns_object_list_remove(&visible_nodes, node); /* FIXME: We also want to remove any PGs associated with * this node. */ } store_imported_objects(); callout("remove", node, bitmap); } else if (bitmap & (ISNS_SCN_OBJECT_ADDED_MASK|ISNS_SCN_OBJECT_UPDATED_MASK|ISNS_SCN_DD_MEMBER_ADDED_MASK)) { const char *how = "add"; isns_source_t *source; if (bitmap & ISNS_SCN_OBJECT_UPDATED_MASK) how = "update"; if (!node) { node = isns_create_object(node_type, &key_attrs, NULL); if (!node) goto out; isns_object_list_append(&visible_nodes, node); } /* Query the server for information on this node */ source = isns_source_from_object(recipient); query_storage_node(source, node_name); isns_source_release(source); store_imported_objects(); callout(how, node, bitmap); } out: if (node) isns_object_release(node); if (recipient) isns_object_release(recipient); isns_attr_list_destroy(&key_attrs); } /* * Server main loop */ void run_discovery(isns_server_t *server) { isns_client_t *clnt; isns_security_t *ctx = NULL; isns_message_t *msg, *resp; /* Create the server socket */ ctx = isns_default_security_context(0); server_socket = isns_create_server_socket(isns_config.ic_bind_address, NULL, opt_af, SOCK_DGRAM); if (server_socket == NULL) isns_fatal("Unable to create server socket\n"); isns_socket_set_security_ctx(server_socket, ctx); /* Create the client socket */ clnt = isns_create_default_client(NULL); if (clnt == NULL) isns_fatal("Cannot connect to server\n"); /* Load all objects registered by local services */ should_reexport = 1; while (1) { struct timeval timeout = { 0, 0 }; time_t now, then, next_timeout; unsigned int function; next_timeout = time(NULL) + 3600; /* Run timers */ then = isns_run_timers(); if (then && then < next_timeout) next_timeout = then; /* Determine how long we can sleep */ now = time(NULL); if (next_timeout <= now) continue; timeout.tv_sec = next_timeout - now; if (should_reexport) { load_exported_objects(); if (register_exported_objects(clnt)) isns_error("Failed to register exported objects.\n"); /* Prime the list of visible storage nodes */ if (query_visible()) isns_error("Unable to query list of visible nodes.\n"); store_imported_objects(); should_reexport = 0; } if ((msg = isns_recv_message(&timeout)) == NULL) continue; function = isns_message_function(msg); if (function != ISNS_STATE_CHANGE_NOTIFICATION && function != ISNS_ENTITY_STATUS_INQUIRY) { isns_warning("Discarding unexpected %s message\n", isns_function_name(function)); isns_message_release(msg); continue; } if ((resp = isns_process_message(server, msg)) != NULL) { isns_socket_t *sock = isns_message_socket(msg); isns_socket_send(sock, resp); isns_message_release(resp); } isns_message_release(msg); } } open-iscsi-2.0.873/utils/open-isns/isnssetup000066400000000000000000000023441175631155400210120ustar00rootroot00000000000000#!/bin/sh # # isnssetup - bootstrap open-isns server # # Copyright (C) 2007 Olaf Kirch # # This is a very simple script to bootstrap an iSNS server. # It creates the necessary keys, enrolls a control node, # and enrolls the local host as target and initiator. hostname=`hostname -f` if [ -f isnsd -a -d isnsadm ]; then PATH=.:$PATH fi # Massage the configuration file for f in isnsadm.conf isnsdd.conf; do etcfile=/etc/isns/$f sed -e 's/^#*\(ServerAddress[[:space:]]*=\).*/\1 localhost/' \ -e 's/^#*\(Security[[:space:]]*=\).*/\1 1/' \ $etcfile > $etcfile.tmp mv $etcfile.tmp $etcfile done echo "*** Initializing server security ***" isnsd --init cp /etc/isns/auth_key.pub /etc/isns/server_key.pub if ps ax|grep isnsd | grep -qv grep; then killall -TERM isnsd sleep 1 fi isnsd sleep 1 echo "*** Registering control node policy ***" rm -f /etc/isns/control.key isnsadm --local \ --keyfile=/etc/isns/control.key \ --enroll isns.control \ node-type=ALL functions=ALL object-type=ALL echo "*** Registering control node ***" isnsadm --local \ --register control echo "*** Registering policy for server ***" isnsadm --control \ --enroll $hostname \ key=/etc/isns/auth_key.pub \ node-type=target+initiator open-iscsi-2.0.873/utils/open-isns/local.c000066400000000000000000000205361175631155400202730ustar00rootroot00000000000000/* * Local iSNS registration * * Copyright (C) 2007 Olaf Kirch * * The way isnsdd communicates with local services (initiator, * target) is via a file and signals. That sounds rather * awkward, but it's a lot simpler to add to these services * than another socket based communication mechanism I guess. * * The file format is simple: * owner= * owner= * ... * * identifies the service owning these entries. * This is a service name, such as iscsid, tgtd, isnsdd, * optionally followed by a colon and a PID. This allows * removal of all entries created by one service in one go. * * is the description of one iSNS object, using the * syntax used by all other open-isns apps. */ #include #include #include #include #include #include #include #include #include #include #include "security.h" #include "util.h" #include "isns-proto.h" #include "paths.h" #include "attrs.h" #include "util.h" typedef int __isns_local_registry_cb_fn_t(const char *line, int argc, char **argv, void *user_data); /* * Build the owner=: tag */ static const char * __isns_local_registry_make_owner(const char *svcname, pid_t pid) { static char owner[128]; if (pid == 0) { return svcname; } snprintf(owner, sizeof(owner), "%s:%u", svcname, pid); return owner; } /* * Read the registry file, match each entry against the given owner= tag, * and invoke the callback function. * This is used for both reading the registry, and rewriting it. */ static int __isns_local_registry_read(const char *match_owner, __isns_local_registry_cb_fn_t handle_matching, __isns_local_registry_cb_fn_t handle_nonmatching, void *user_data) { const char *filename = isns_config.ic_local_registry_file; char *line, *copy = NULL; FILE *fp; int rv = 0, owner_len; if (!(fp = fopen(filename, "r"))) { if (errno == ENOENT) { isns_debug_state("Unable to open %s: %m\n", filename); return 1; } isns_error("Unable to open %s: %m\n", filename); return 0; } owner_len = match_owner? strlen(match_owner) : 0; while ((line = parser_get_next_line(fp)) != NULL) { __isns_local_registry_cb_fn_t *cb; char *argv[256], *owner; int argc = 0; isns_assign_string(©, line); argc = isns_attr_list_split(line, argv, 255); if (argc <= 0) continue; /* Last attr should be owner */ if (strncasecmp(argv[argc-1], "owner=", 6)) { isns_error("%s: syntax error (missing owner field)\n", filename); goto out; } owner = argv[argc-1] + 6; if (!strncasecmp(owner, match_owner, owner_len) && (owner[owner_len] == '\0' || owner[owner_len] == ':')) cb = handle_matching; else cb = handle_nonmatching; if (cb && !cb(copy, argc, argv, user_data)) goto out; } rv = 1; out: free(copy); fclose(fp); return rv; } /* * Open and lock the registry file for writing. Returns an * open stream and the name of the lock file. * Follow up with _finish_write when done. */ static FILE * __isns_local_registry_open_write(char **lock_name) { char lock_path[PATH_MAX]; FILE *fp; int fd, retry; snprintf(lock_path, sizeof(lock_path), "%s.lock", isns_config.ic_local_registry_file); for (retry = 0; retry < 5; ++retry) { fd = open(lock_path, O_RDWR|O_CREAT|O_EXCL, 0644); if (fd >= 0) break; if (errno != EEXIST) { isns_error("Unable to create %s: %m\n", lock_path); return NULL; } isns_error("Cannot lock %s - retry in 1 sec\n", isns_config.ic_local_registry_file); sleep(1); } if (!(fp = fdopen(fd, "w"))) { isns_error("fdopen failed: %m\n"); close(fd); return NULL; } isns_assign_string(lock_name, lock_path); return fp; } /* * We're done with (re)writing the registry. Commit the changes, * or discard them. * Also frees the lock_name returned by registry_open_write. */ static int __isns_local_registry_finish_write(FILE *fp, char *lock_name, int commit) { int rv = 1; fclose(fp); if (!commit) { if (unlink(lock_name)) isns_error("Failed to unlink %s: %m\n", lock_name); } else if (rename(lock_name, isns_config.ic_local_registry_file)) { isns_error("Failed to rename %s to %s: %m\n", lock_name, isns_config.ic_local_registry_file); rv = 0; } free(lock_name); return rv; } /* * Get the entity name for this service */ static char * __isns_local_registry_entity_name(const char *owner) { static char namebuf[1024]; snprintf(namebuf, sizeof(namebuf), "%s:%s", isns_config.ic_entity_name, owner); return namebuf; } /* * Callback function which builds an iSNS object from the * list of attr=tag values. */ static int __isns_local_registry_load_object(const char *line, int argc, char **argv, void *user_data) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; struct isns_attr_list_parser state; isns_object_list_t *list = user_data; isns_object_t *obj, *entity = NULL; for (; argc > 0; --argc) { char *attr = argv[argc-1]; if (!strncasecmp(attr, "owner=", 6)) { char *eid = __isns_local_registry_entity_name(attr + 6); ISNS_QUICK_ATTR_LIST_DECLARE(key_attrs, ISNS_TAG_ENTITY_IDENTIFIER, string, eid); if (entity) { isns_error("Duplicate owner entry in registry\n"); continue; } isns_attr_print(&key_attrs.iqa_attr, isns_print_stdout); entity = isns_object_list_lookup(list, &isns_entity_template, &key_attrs.iqa_list); if (entity != NULL) continue; isns_debug_state("Creating fake entity %s\n", eid); entity = isns_create_entity(ISNS_ENTITY_PROTOCOL_ISCSI, eid); isns_object_list_append(list, entity); } else { break; } } isns_attr_list_parser_init(&state, NULL); if (!isns_parse_attrs(argc, argv, &attrs, &state)) { isns_error("Unable to parse attrs\n"); isns_attr_list_destroy(&attrs); return 0; } obj = isns_create_object(isns_attr_list_parser_context(&state), &attrs, entity); isns_attr_list_destroy(&attrs); if (obj == NULL) { isns_error("Unable to create object\n"); return 0; } isns_object_list_append(list, obj); return 1; } /* * Callback function that simply writes out the line as-is */ static int __isns_local_registry_rewrite_object(const char *line, int argc, char **argv, void *user_data) { FILE *ofp = user_data; fprintf(ofp, "%s\n", line); return 1; } /* * Load all objects owner by a specific service from the local registry. * If the svcname starts with "!", all entries except those matching this * particular service are returned. */ int isns_local_registry_load(const char *svcname, pid_t pid, isns_object_list_t *objs) { __isns_local_registry_cb_fn_t *if_matching = NULL, *if_nonmatching = NULL; if (svcname == NULL) { isns_error("%s: no svcname given\n", __FUNCTION__); return 0; } if (*svcname == '!') { if_nonmatching = __isns_local_registry_load_object; svcname++; } else { if_matching = __isns_local_registry_load_object; } return __isns_local_registry_read( __isns_local_registry_make_owner(svcname, pid), if_matching, if_nonmatching, objs); } /* * Store the given list of objects in the registry. * This replaces all objects previously registered by this service. */ int isns_local_registry_store(const char *svcname, pid_t pid, const isns_object_list_t *objs) { const char *owner = __isns_local_registry_make_owner(svcname, pid); char *lock_name = NULL; FILE *ofp; if (!(ofp = __isns_local_registry_open_write(&lock_name))) { isns_error("%s: could not open registry for writing\n", __FUNCTION__); return 0; } /* First, purge all entries previously belonging to this owner */ if (!__isns_local_registry_read(owner, NULL, __isns_local_registry_rewrite_object, ofp)) goto failed; if (objs) { unsigned int i; for (i = 0; i < objs->iol_count; ++i) { isns_object_t *obj = objs->iol_data[i]; char *argv[256]; int i, argc; argc = isns_print_attrs(obj, argv, 256); for (i = 0; i < argc; ++i) fprintf(ofp, "%s ", argv[i]); fprintf(ofp, "owner=%s\n", owner); } } return __isns_local_registry_finish_write(ofp, lock_name, 1); failed: isns_error("%s: error rewriting registry file\n", __FUNCTION__); __isns_local_registry_finish_write(ofp, lock_name, 0); return 0; } /* * Purge the local registry of all objects owned by the * given service. */ int isns_local_registry_purge(const char *svcname, pid_t pid) { return isns_local_registry_store(svcname, pid, NULL); } open-iscsi-2.0.873/utils/open-isns/logging.c000066400000000000000000000076021175631155400206260ustar00rootroot00000000000000/* * Logging related utility functions. * * Copyright (C) 2004-2007 Olaf Kirch */ #include #include #include #include #include #include "util.h" static unsigned int log_stdout = 1; static unsigned int debugging = 0; /* * When backgrounding, any logging output should * go to syslog instead of stdout */ void isns_log_background(void) { log_stdout = 0; } /* * For output to syslog, sanitize the format string * by removing newlines. */ static const char * sanitize_format(const char *fmt) { static char __fmt[1024]; unsigned int len; /* Don't bother unless there's a newline */ if (!strchr(fmt, '\n')) return fmt; len = strlen(fmt); /* Decline if the buffer would overflow */ if (len >= sizeof(__fmt)) return fmt; strcpy(__fmt, fmt); while (len-- && __fmt[len] == '\n') __fmt[len] = '\0'; while (len) { if (__fmt[len] == '\n') __fmt[len] = ' '; --len; } return __fmt; } /* * Output to stderr or syslog */ static void voutput(int severity, const char *fmt, va_list ap) { if (log_stdout) { switch (severity) { case LOG_ERR: fprintf(stderr, "Error: "); break; case LOG_WARNING: fprintf(stderr, "Warning: "); break; case LOG_DEBUG: fprintf(stderr, " "); break; } vfprintf(stderr, fmt, ap); } else { fmt = sanitize_format(fmt); if (!fmt || !*fmt) return; vsyslog(severity, fmt, ap); } } void isns_assert_failed(const char *condition, const char *file, unsigned int line) { isns_error("Assertion failed (%s:%d): %s\n", file, line, condition); abort(); } void isns_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (log_stdout) fprintf(stderr, "** FATAL ERROR **\n"); voutput(LOG_ERR, fmt, ap); va_end(ap); exit(1); } void isns_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); voutput(LOG_WARNING, fmt, ap); va_end(ap); } void isns_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); voutput(LOG_NOTICE, fmt, ap); va_end(ap); } void isns_notice(const char *fmt, ...) { va_list ap; va_start(ap, fmt); voutput(LOG_INFO, fmt, ap); va_end(ap); } void isns_enable_debugging(const char *what) { char *copy, *s, *next; if (!strcmp(what, "all")) { debugging = ~0U; return; } copy = isns_strdup(what); for (s = copy; s; s = next) { if ((next = strchr(s, ',')) != NULL) *next++ = '\0'; if (!strcmp(s, "general")) debugging |= (1 << DBG_GENERAL); else if (!strcmp(s, "socket")) debugging |= (1 << DBG_SOCKET); else if (!strcmp(s, "protocol")) debugging |= (1 << DBG_PROTOCOL); else if (!strcmp(s, "state")) debugging |= (1 << DBG_STATE); else if (!strcmp(s, "message")) debugging |= (1 << DBG_MESSAGE); else if (!strcmp(s, "auth")) debugging |= (1 << DBG_AUTH); else if (!strcmp(s, "scn")) debugging |= (1 << DBG_SCN); else if (!strcmp(s, "esi")) debugging |= (1 << DBG_ESI); else { isns_error("Ignoring unknown isns_debug facility <<%s>>\n", s); } } isns_free(copy); } #define DEFINE_DEBUG_FUNC(name, NAME) \ void \ isns_debug_##name(const char *fmt, ...) \ { \ va_list ap; \ \ if (!(debugging & (1 << DBG_##NAME))) \ return; \ \ va_start(ap, fmt); \ voutput(LOG_DEBUG, fmt, ap); \ va_end(ap); \ } DEFINE_DEBUG_FUNC(general, GENERAL) DEFINE_DEBUG_FUNC(socket, SOCKET) DEFINE_DEBUG_FUNC(protocol, PROTOCOL) DEFINE_DEBUG_FUNC(message, MESSAGE) DEFINE_DEBUG_FUNC(auth, AUTH) DEFINE_DEBUG_FUNC(state, STATE) DEFINE_DEBUG_FUNC(scn, SCN) DEFINE_DEBUG_FUNC(esi, ESI) int isns_debug_enabled(int fac) { return (debugging & (1 << fac)) != 0; } /* * Misc isns_print_fn_t implementations */ void isns_print_stdout(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stdout, fmt, ap); va_end(ap); } void isns_print_stderr(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } open-iscsi-2.0.873/utils/open-isns/mdebug.c000066400000000000000000000141501175631155400204370ustar00rootroot00000000000000/* * Stupid malloc debugger. I think I wrote something like * this a couple of times already. Where does all the old * source code go? */ #ifdef MDEBUG #include #include #include "util.h" static void * isns_malloc_default(size_t, const char *, unsigned int); static void * isns_calloc_default(unsigned int, size_t, const char *, unsigned int); static void * isns_realloc_default(void *, size_t, const char *, unsigned int); static char * isns_strdup_default(const char *, const char *, unsigned int); static void isns_free_default(void *, const char *, unsigned int); /* * These are the function pointers used to redirect malloc and such. */ void * (*isns_malloc_fn)(size_t, const char *, unsigned int) = isns_malloc_default; void * (*isns_calloc_fn)(unsigned int, size_t, const char *, unsigned int) = isns_calloc_default; void * (*isns_realloc_fn)(void *, size_t, const char *, unsigned int) = isns_realloc_default; char * (*isns_strdup_fn)(const char *, const char *, unsigned int) = isns_strdup_default; void (*isns_free_fn)(void *, const char *, unsigned int) = isns_free_default; #define H_MAGIC 0xfeedbeef #define T_MAGIC 0xbadf00d #define CHUNK_OVERHEAD (sizeof(struct m_header) + sizeof(struct m_trailer)) struct m_header { struct isns_list h_list; uint32_t h_magic; size_t h_size; const char * h_file; unsigned int h_line; }; struct m_trailer { uint32_t t_magic[8]; size_t t_size; }; static ISNS_LIST_DECLARE(m_list); static void * m_low_addr; static void * m_high_addr; static int m_init = 0; static void __isns_check_chunk(const struct m_header *head) { const struct m_trailer *tail; int i; if ((void *) head < m_low_addr || (void *) head > m_high_addr) { isns_error("%s: m_list corrupted!\n", __FUNCTION__); abort(); } if (head->h_magic != H_MAGIC) { isns_error("%s: m_list item %p with bad header magic %08x\n", __FUNCTION__, head, head->h_magic); isns_error(" Allocated from %s:%u\n", head->h_file, head->h_line); abort(); } tail = ((void *) head) + sizeof(*head) + head->h_size; for (i = 0; i < 8; ++i) { if (tail->t_magic[i] == T_MAGIC) continue; isns_error("%s: m_list item %p with bad trailer magic[%d] %08x\n", __FUNCTION__, head, i, tail->t_magic[i]); isns_error(" Allocated from %s:%u\n", head->h_file, head->h_line); abort(); } if (tail->t_size != head->h_size) { isns_error("%s: m_list item %p size mismatch; head=%u tail=%u\n", __FUNCTION__, head, head->h_size, tail->t_size); isns_error(" Allocated from %s:%u\n", head->h_file, head->h_line); abort(); } } static void __isns_verify_all(void) { struct isns_list *pos, *next; isns_list_foreach(&m_list, pos, next) { __isns_check_chunk(isns_list_item(struct m_header, h_list, pos)); } } void * __isns_malloc(size_t size, const char *file, unsigned int line) { struct m_header *head; struct m_trailer *tail; size_t true_size; void *ptr; int i; __isns_verify_all(); true_size = size + sizeof(*head) + sizeof(*tail); isns_assert(size < true_size); ptr = malloc(true_size); if (!ptr) return NULL; if (!m_low_addr) { m_low_addr = m_high_addr = ptr; } else if (ptr < m_low_addr) { m_low_addr = ptr; } else if (ptr > m_high_addr) { m_high_addr = ptr; } head = ptr; head->h_magic = H_MAGIC; head->h_size = size; head->h_file = file; head->h_line = line; isns_list_append(&m_list, &head->h_list); ptr += sizeof(*head); tail = ptr + size; for (i = 0; i < 8; ++i) tail->t_magic[i] = T_MAGIC; tail->t_size = size; return ptr; } void * __isns_calloc(unsigned int nele, size_t size, const char *file, unsigned int line) { void *ptr; ptr = __isns_malloc(nele * size, file, line); if (ptr) memset(ptr, 0, nele * size); return ptr; } void * __isns_realloc(void *old, size_t new_size, const char *file, unsigned int line) { struct m_header *old_head = NULL; void *new; if (old) { old_head = (old - sizeof(struct m_header)); __isns_check_chunk(old_head); } new = __isns_malloc(new_size, file, line); if (new && old) { memcpy(new, old, old_head->h_size); isns_free_fn(old, file, line); } return new; } char * __isns_strdup(const char *s, const char *file, unsigned int line) { size_t len; char *ptr; len = s? strlen(s) : 0; ptr = __isns_malloc(len + 1, file, line); if (ptr) { memcpy(ptr, s, len); ptr[len] = '\0'; } return ptr; } void __isns_free(void *ptr, const char *file, unsigned int line) { struct m_header *head; size_t true_size; if (ptr == NULL) return; head = ptr - sizeof(struct m_header); __isns_check_chunk(head); /* printf("__isns_free(%u from %s:%u): freed by %s:%u\n", head->h_size, head->h_file, head->h_line, file, line); */ true_size = head->h_size + CHUNK_OVERHEAD; isns_list_del(&head->h_list); memset(head, 0xa5, true_size); free(head); __isns_verify_all(); } /* * Enable memory debugging */ static void __isns_mdebug_init(void) { const char *tracefile; tracefile = getenv("ISNS_MTRACE"); if (tracefile) isns_error("MTRACE not yet supported\n"); if (getenv("ISNS_MDEBUG")) { isns_malloc_fn = __isns_malloc; isns_calloc_fn = __isns_calloc; isns_realloc_fn = __isns_realloc; isns_strdup_fn = __isns_strdup; isns_free_fn = __isns_free; isns_notice("Enabled memory debugging\n"); } m_init = 1; } static inline void isns_mdebug_init(void) { if (!m_init) __isns_mdebug_init(); } /* * Default implementations of malloc and friends */ static void * isns_malloc_default(size_t size, const char *file, unsigned int line) { isns_mdebug_init(); return malloc(size); } static void * isns_calloc_default(unsigned int nele, size_t size, const char *file, unsigned int line) { isns_mdebug_init(); return calloc(nele, size); } static void * isns_realloc_default(void *old, size_t size, const char *file, unsigned int line) { isns_mdebug_init(); return realloc(old, size); } static char * isns_strdup_default(const char *s, const char *file, unsigned int line) { isns_mdebug_init(); return strdup(s); } static void isns_free_default(void *ptr, const char *file, unsigned int line) { isns_mdebug_init(); return free(ptr); } #endif open-iscsi-2.0.873/utils/open-isns/message.c000066400000000000000000000332111175631155400206170ustar00rootroot00000000000000/* * iSNS message handling functions * * Copyright (C) 2007 Olaf Kirch * * */ #include #include #include /* for timercmp */ #include /* gethostname */ #include #include "isns.h" #include "attrs.h" #include "message.h" #include "socket.h" #include "util.h" /* iSCSI qualified names include the year and * month in which the domain was assigned. * See RFC 3720, section 3.2.6.3.1. * That's one of these wonderful committee * type of ideas that makes it hard for everyone, * from coder to sysadmin. * Since we have no way of finding out here, * we fake it by assigning a date before the * dawn of time. */ #define DUMMY_IQN_PREFIX "iqn.1967-12." static uint32_t isns_xid = 1; /* * Initialize a message object */ isns_message_t * __isns_alloc_message(uint32_t xid, size_t size, void (*destroy)(isns_message_t *)) { isns_message_t *msg; isns_assert(size >= sizeof(*msg)); msg = isns_calloc(1, size); isns_list_init(&msg->im_list); msg->im_users = 1; msg->im_xid = xid; msg->im_destroy = destroy; return msg; } static int __isns_message_init(isns_message_t *msg, uint16_t function, uint16_t flags, size_t payload_len) { struct isns_hdr *hdr = &msg->im_header; /* Pad to multiple of 4 octets */ payload_len = (payload_len + 3) & ~3UL; /* For now, we don't do segmentation */ if (payload_len > ISNS_MAX_PDU_SIZE) return 0; /* msg->im_header is in host byte order */ hdr->i_version = ISNS_VERSION; hdr->i_function = function; hdr->i_flags = flags; hdr->i_length = payload_len; hdr->i_xid = msg->im_xid; hdr->i_seq = 0; /* Allocate buffer and reserve room for header */ msg->im_payload = buf_alloc(sizeof(*hdr) + payload_len); buf_push(msg->im_payload, sizeof(*hdr)); return 1; } /* * Allocate a message object. */ static isns_message_t * __isns_create_message(uint32_t xid, uint16_t function, uint16_t flags) { isns_message_t *msg; msg = __isns_alloc_message(xid, sizeof(*msg), NULL); __isns_message_init(msg, function, flags, ISNS_MAX_MESSAGE); return msg; } /* * Allocate a request message */ isns_message_t * isns_create_message(uint16_t function, uint16_t flags) { return __isns_create_message(isns_xid++, function, flags); } /* * Allocate a response message */ isns_message_t * isns_create_reply(const isns_message_t *msg) { uint16_t function = msg->im_header.i_function;; isns_message_t *resp; resp = __isns_create_message(msg->im_xid, function | 0x8000, ISNS_F_SERVER); resp->im_addr = msg->im_addr; resp->im_addrlen = msg->im_addrlen; /* Default to ISNS_SUCCESS */ buf_put32(resp->im_payload, ISNS_SUCCESS); return resp; } /* * Delete a message */ void isns_message_release(isns_message_t *msg) { if (msg == NULL) return; isns_assert(msg->im_users); if (--(msg->im_users)) return; if (msg->im_destroy) msg->im_destroy(msg); if (msg->im_payload) buf_free(msg->im_payload); isns_principal_free(msg->im_security); isns_list_del(&msg->im_list); isns_free(msg); } /* * Extract the status from a reply message */ int isns_message_status(isns_message_t *msg) { uint32_t status; if (!(msg->im_header.i_function & 0x8000) || !buf_get32(msg->im_payload, &status)) return ISNS_MESSAGE_FORMAT_ERROR; return status; } /* * Obtain the socket on which the message was received. */ isns_socket_t * isns_message_socket(const isns_message_t *msg) { return msg->im_socket; } /* * Obtain the message's security context */ isns_security_t * isns_message_security(const isns_message_t *msg) { if (!msg->im_socket) return NULL; return msg->im_socket->is_security; } unsigned int isns_message_function(const isns_message_t *msg) { return msg->im_header.i_function; } /* * Reset the response message, and encode isns_error * status */ void isns_message_set_error(isns_message_t *msg, uint32_t status) { /* Clear the buffer. This just resets head + tail */ buf_clear(msg->im_payload); /* Now move past the header, and overwrite the * status word. */ buf_push(msg->im_payload, sizeof(struct isns_hdr)); buf_put32(msg->im_payload, status); } /* * Message queue handling. Most related functions are * in message.h */ void isns_message_queue_move(isns_message_queue_t *dstq, isns_message_t *msg) { unsigned int src_ref = 0; /* If the message was on a different queue, * the source queue will hold a reference * to it. Account for that and fix up the * refcount after we've appended it to the * destination queue. */ if (isns_message_unlink(msg)) src_ref = 1; isns_message_queue_append(dstq, msg); msg->im_users -= src_ref; } /* * Insert a messsage into a queue sorted by resend timeout */ void isns_message_queue_insert_sorted(isns_message_queue_t *q, int sort, isns_message_t *msg) { isns_list_t *pos; isns_message_t *__m; isns_assert(msg->im_queue == NULL); if (sort == ISNS_MQ_SORT_RESEND_TIMEOUT) { isns_message_queue_foreach(q, pos, __m) { if (timercmp(&msg->im_resend_timeout, &__m->im_resend_timeout, <)) break; } } else { isns_message_queue_append(q, msg); return; } /* Insert before pos */ __isns_list_insert(pos->prev, &msg->im_list, pos); q->imq_count++; msg->im_queue = q; msg->im_users++; } /* * Message queue handling */ void isns_message_queue_destroy(isns_message_queue_t *q) { isns_message_t *msg; while ((msg = isns_message_dequeue(q)) != NULL) isns_message_release(msg); } /* * Find a message with matching xid and address. * (address, alen) may be NULL. */ isns_message_t * isns_message_queue_find(isns_message_queue_t *q, uint32_t xid, const struct sockaddr_storage *addr, socklen_t alen) { isns_message_t *msg; isns_list_t *pos; isns_message_queue_foreach(q, pos, msg) { if (msg->im_xid != xid) continue; if (alen == 0) return msg; if (msg->im_addrlen == alen && !memcmp(&msg->im_addr, addr, alen)) return msg; } return NULL; } /* * Convert a hostname into an iSCSI qualified name * We omit the dismbiguating YYYY-MM infix because * we have no way of finding out, short of bothering * whois. */ static char * __revert_fqdn(const char *prefix, const char *__fqdn, const char *suffix) { static char namebuf[1024] = { '\0' }; char *fqdn, *result = NULL; int pos, count = 0; if (prefix) strcpy(namebuf, prefix); pos = strlen(namebuf); fqdn = isns_strdup(__fqdn); while (1) { char *dot, *comp; int comp_len; if ((dot = strrchr(fqdn, '.')) != NULL) { *dot++ = '\0'; comp = dot; } else { comp = fqdn; } if (*comp == '\0') continue; comp_len = strlen(comp); if (pos + comp_len + 2 > sizeof(namebuf)) { isns_error("%s: FQDN too long\n", __FUNCTION__); goto out; } if (count++) namebuf[pos++] = '.'; strcpy(namebuf + pos, comp); pos += comp_len; if (dot == NULL) break; } if (suffix) { int sfx_len = strlen(suffix); if (pos + sfx_len + 2 > sizeof(namebuf)) { isns_error("%s: name too long\n", __FUNCTION__); goto out; } namebuf[pos++] = ':'; strcpy(namebuf + pos, suffix); pos += sfx_len; } result = isns_strdup(namebuf); out: isns_free(fqdn); return result; } /* * Initialize all names */ int isns_init_names(void) { if (isns_config.ic_host_name == NULL) { char namebuf[1024], *fqdn; if (gethostname(namebuf, sizeof(namebuf)) < 0) { isns_error("gehostname: %m\n"); return 0; } fqdn = isns_get_canon_name(namebuf); if (fqdn == NULL) { /* FIXME: we could get some unique value here * such as the IP address, and concat that * with iqn.2005-01.org.open-iscsi.ip for the * source name. */ isns_error("Unable to get fully qualified hostname\n"); return 0; } isns_config.ic_host_name = fqdn; } if (isns_config.ic_auth_name == NULL) { isns_config.ic_auth_name = isns_config.ic_host_name; } if (isns_config.ic_entity_name == NULL) { isns_config.ic_entity_name = isns_config.ic_auth_name; } if (isns_config.ic_source_name == NULL) { isns_config.ic_source_name = __revert_fqdn(DUMMY_IQN_PREFIX, isns_config.ic_host_name, isns_config.ic_source_suffix); if (isns_config.ic_source_name == NULL) { isns_error("Unable to build source name\n"); return 0; } } return 1; } /* * Match a source name to a pattern (which is really just * the entity identifier, usually). * * If the pattern is of the form "match:rev-fqdn", the * source name must match * iqn.[YYYY-MM.] * optionally followed by dot, colon or hyphen and arbitrary * text. * * If the pattern does not start with "match:", the source name * must match the pattern literally (case insensitively). */ int isns_source_pattern_match(const char *pattern, const char *source) { unsigned int rev_len; isns_debug_message("%s(%s, %s)\n", __FUNCTION__, pattern, source); if (!strcmp(pattern, "*")) return 1; if (strncmp(pattern, "match:", 6)) return !strcasecmp(pattern, source); pattern += 6; if (strncasecmp(source, "iqn.", 4)) return 0; source += 4; rev_len = strlen(pattern); if (strncasecmp(source, pattern, rev_len)) { /* See if the next component is YYYY-MM */ if (!(isdigit(source[0]) && isdigit(source[1]) && isdigit(source[2]) && isdigit(source[3]) && source[4] == '-' && isdigit(source[5]) && isdigit(source[6]) && source[7] == '.')) return 0; source += 8; if (strncasecmp(source, pattern, rev_len)) return 0; } source += rev_len; if (source[0] != '.' && source[0] != ':' && source[0] != '-' && source[0] != '\0') return 0; return 1; } /* * This really just reverts the FQDN so it can * be used in isns_source_entity_match */ char * isns_build_source_pattern(const char *fqdn) { return __revert_fqdn("match:", fqdn, NULL); } /* * Manage source objects */ static isns_source_t * __isns_source_create(isns_attr_t *name_attr) { isns_source_t *source = isns_calloc(1, sizeof(*source)); source->is_users = 1; source->is_attr = name_attr; return source; } isns_source_t * isns_source_create(isns_attr_t *name_attr) { if (name_attr->ia_tag_id != ISNS_TAG_ISCSI_NAME && name_attr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) return NULL; name_attr->ia_users++; return __isns_source_create(name_attr); } isns_source_t * isns_source_from_object(const isns_object_t *node) { isns_attr_t *attr; if (!(attr = isns_storage_node_key_attr(node))) return NULL; return isns_source_create(attr); } isns_source_t * isns_source_create_iscsi(const char *name) { isns_value_t var = ISNS_VALUE_INIT(string, (char *) name); isns_attr_t *attr; attr = isns_attr_alloc(ISNS_TAG_ISCSI_NAME, NULL, &var); return __isns_source_create(attr); } /* * This is used to attach a dummy source to iSNS responses * until I fixed up all the code that relies on msg->is_source * to be valid all the time. */ isns_source_t * isns_source_dummy(void) { static isns_source_t *dummy = NULL; if (!dummy) dummy = isns_source_create_iscsi(".dummy."); return isns_source_get(dummy); } uint32_t isns_source_type(const isns_source_t *source) { return source->is_attr->ia_tag_id; } const char * isns_source_name(const isns_source_t *source) { return source->is_attr->ia_value.iv_string; } isns_attr_t * isns_source_attr(const isns_source_t *source) { return source->is_attr; } /* * Obtain an additional reference on the source object */ isns_source_t * isns_source_get(isns_source_t *source) { if (source) source->is_users++; return source; } /* * Look up the node corresponding to this source name * When we get here, we have already verified that the * client is permitted (by policy) to use this source node. */ int isns_source_set_node(isns_source_t *source, isns_db_t *db) { isns_object_t *node, *entity; uint32_t node_type; if (source->is_node) return 1; if (db == NULL) return 0; node = isns_db_lookup_source_node(db, source); if (node == NULL) return 0; if (!isns_object_get_uint32(node, ISNS_TAG_ISCSI_NODE_TYPE, &node_type)) node_type = 0; source->is_node = node; source->is_node_type = node_type; if ((entity = isns_object_get_entity(node)) != NULL) source->is_entity = isns_object_get(entity); return 1; } void isns_source_set_entity(isns_source_t *source, isns_object_t *obj) { if (obj) isns_object_get(obj); isns_object_release(source->is_entity); source->is_entity = obj; } /* * Release a reference on the source object */ void isns_source_release(isns_source_t *source) { if (source && --source->is_users == 0) { isns_attr_release(source->is_attr); isns_object_release(source->is_node); isns_object_release(source->is_entity); memset(source, 0xa5, sizeof(*source)); isns_free(source); } } /* * Compare two source objects */ int isns_source_match(const isns_source_t *a, const isns_source_t *b) { if (a && b) return isns_attr_match(a->is_attr, b->is_attr); return 0; } /* * Encode/decode source object */ int isns_source_encode(buf_t *bp, const isns_source_t *source) { if (source == NULL) { isns_attr_t nil = ISNS_ATTR_INIT(ISNS_TAG_DELIMITER, nil, 0); return isns_attr_encode(bp, &nil); } return isns_attr_encode(bp, source->is_attr); } int isns_source_decode(buf_t *bp, isns_source_t **result) { isns_attr_t *attr; int status; status = isns_attr_decode(bp, &attr); if (status == ISNS_SUCCESS) { /* * 5.6.1 * The Source Attribute uniquely identifies the source of the * message. Valid Source Attribute types are shown below. * * Valid Source Attributes * ----------------------- * iSCSI Name * FC Port Name WWPN */ switch (attr->ia_tag_id) { #if 0 case ISNS_TAG_DELIMITER: *result = NULL; break; #endif case ISNS_TAG_ISCSI_NAME: *result = __isns_source_create(attr); break; case ISNS_TAG_FC_PORT_NAME_WWPN: *result = __isns_source_create(attr); break; default: isns_attr_release(attr); return ISNS_SOURCE_UNKNOWN; } } return status; } open-iscsi-2.0.873/utils/open-isns/message.h000066400000000000000000000122551175631155400206310ustar00rootroot00000000000000/* * iSNS message definitions and functions * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_MESSAGE_H #define ISNS_MESSAGE_H #include "attrs.h" #include "source.h" #include "util.h" typedef struct isns_message_queue isns_message_queue_t; struct isns_simple { uint32_t is_function; isns_source_t * is_source; isns_policy_t * is_policy; uint16_t is_xid; unsigned int is_replace : 1; isns_attr_list_t is_message_attrs; isns_attr_list_t is_operating_attrs; }; struct isns_message { unsigned int im_users; isns_list_t im_list; struct sockaddr_storage im_addr; socklen_t im_addrlen; uint32_t im_xid; struct isns_hdr im_header; struct isns_buf * im_payload; isns_socket_t * im_socket; isns_principal_t * im_security; struct ucred * im_creds; isns_message_queue_t * im_queue; /* When to retransmit */ struct timeval im_resend_timeout; struct timeval im_timeout; void (*im_destroy)(isns_message_t *); void (*im_callback)(isns_message_t *, isns_message_t *); void * im_calldata; }; enum { ISNS_MQ_SORT_NONE, ISNS_MQ_SORT_RESEND_TIMEOUT, }; struct isns_message_queue { isns_list_t imq_list; size_t imq_count; }; struct isns_server { isns_source_t * is_source; isns_db_t * is_db; isns_scn_callback_fn_t *is_scn_callback; struct isns_service_ops *is_ops; }; extern isns_message_t * __isns_alloc_message(uint32_t, size_t, void (*)(isns_message_t *)); extern isns_security_t *isns_message_security(const isns_message_t *); extern isns_message_t * isns_message_queue_find(isns_message_queue_t *, uint32_t, const struct sockaddr_storage *, socklen_t); extern void isns_message_queue_insert_sorted(isns_message_queue_t *, int, isns_message_t *); extern void isns_message_queue_move(isns_message_queue_t *, isns_message_t *); extern void isns_message_queue_destroy(isns_message_queue_t *); extern isns_simple_t * isns_simple_create(uint32_t, isns_source_t *, const isns_attr_list_t *); extern void isns_simple_free(isns_simple_t *); extern int isns_simple_encode(isns_simple_t *, isns_message_t **result); extern int isns_simple_decode(isns_message_t *, isns_simple_t **); extern int isns_simple_encode_response(isns_simple_t *, const isns_message_t *, isns_message_t **); extern int isns_simple_response_get_objects(isns_simple_t *, isns_object_list_t *); extern const char * isns_function_name(uint32_t); extern isns_source_t * isns_simple_get_source(isns_simple_t *); extern int isns_process_registration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_query(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_getnext(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn_register(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_dd_registration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_dd_deregistration(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_esi(isns_server_t *, isns_simple_t *, isns_simple_t **); extern int isns_process_scn(isns_server_t *, isns_simple_t *, isns_simple_t **); /* * Inline functions for message queues. */ static inline void isns_message_queue_init(isns_message_queue_t *q) { isns_list_init(&q->imq_list); q->imq_count = 0; } static inline isns_message_t * isns_message_queue_head(const isns_message_queue_t *q) { isns_list_t *pos = q->imq_list.next; if (pos == &q->imq_list) return NULL; return isns_list_item(isns_message_t, im_list, pos); } static inline void isns_message_queue_append(isns_message_queue_t *q, isns_message_t *msg) { isns_assert(msg->im_queue == NULL); isns_list_append(&q->imq_list, &msg->im_list); q->imq_count++; msg->im_queue = q; msg->im_users++; } static inline isns_message_t * isns_message_queue_remove(isns_message_queue_t *q, isns_message_t *msg) { isns_assert(msg->im_queue == q); isns_list_del(&msg->im_list); msg->im_queue = NULL; q->imq_count--; return msg; } static inline isns_message_t * isns_message_unlink(isns_message_t *msg) { if (msg->im_queue) return isns_message_queue_remove(msg->im_queue, msg); return NULL; } static inline isns_message_t * isns_message_dequeue(isns_message_queue_t *q) { isns_message_t *msg; if ((msg = isns_message_queue_head(q)) != NULL) { isns_list_del(&msg->im_list); msg->im_queue = NULL; q->imq_count--; } return msg; } /* * Iterator for looping over all messages in a queue */ static inline void isns_message_queue_begin(isns_message_queue_t *q, isns_list_t **pos) { *pos = q->imq_list.next; } static inline isns_message_t * isns_message_queue_next(isns_message_queue_t *q, isns_list_t **pos) { isns_list_t *next = *pos; if (next == &q->imq_list) return NULL; *pos = next->next; return isns_list_item(isns_message_t, im_list, next); } #define isns_message_queue_foreach(q, pos, item) \ for (isns_message_queue_begin(q, &pos); \ (item = isns_message_queue_next(q, &pos)) != NULL; \ ) #endif /* ISNS_MESSAGE_H */ open-iscsi-2.0.873/utils/open-isns/objects.c000066400000000000000000000654201175631155400206330ustar00rootroot00000000000000/* * iSNS object model * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "objects.h" #include "source.h" #include "vendor.h" #include "attrs.h" #include "util.h" /* For relationship stuff - should go */ #include "db.h" static isns_object_template_t * isns_object_templates[] = { &isns_entity_template, &isns_portal_template, &isns_iscsi_node_template, &isns_fc_port_template, &isns_fc_node_template, &isns_iscsi_pg_template, &isns_dd_template, &isns_ddset_template, /* vendor-specific templates */ &isns_policy_template, NULL }; /* * Quick lookup of (key) tag to template */ #define MAX_QUICK_TAG 2100 static isns_object_template_t * isns_object_template_key_map[MAX_QUICK_TAG]; static isns_object_template_t * isns_object_template_any_map[MAX_QUICK_TAG]; static isns_object_template_t * isns_object_template_idx_map[MAX_QUICK_TAG]; static int isns_object_maps_inizialized = 0; static void __isns_object_maps_init(void) { isns_object_template_t *tmpl; uint32_t i, j, tag; isns_object_maps_inizialized = 1; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { if (tmpl->iot_vendor_specific) continue; tag = tmpl->iot_keys[0]; isns_assert(tag < MAX_QUICK_TAG); isns_object_template_key_map[tag] = tmpl; for (j = 0; j < tmpl->iot_num_attrs; ++j) { tag = tmpl->iot_attrs[j]; isns_assert(tag < MAX_QUICK_TAG); isns_object_template_any_map[tag] = tmpl; } if ((tag = tmpl->iot_index) != 0) isns_object_template_idx_map[tag] = tmpl; } } static void isns_object_maps_init(void) { if (!isns_object_maps_inizialized) __isns_object_maps_init(); } /* * Based on a given key attribute, find the corresponding * object type. */ isns_object_template_t * isns_object_template_find(uint32_t key_tag) { isns_object_template_t *tmpl; unsigned int i; isns_object_maps_init(); if (key_tag < MAX_QUICK_TAG) return isns_object_template_key_map[key_tag]; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { if (tmpl->iot_keys[0] == key_tag) return tmpl; } return NULL; } /* * Given a set of attributes, find the corresponding * object type. * Any attributes in the list in *addition to* the keys * attributes are ignored. */ isns_object_template_t * isns_object_template_for_key_attrs(const isns_attr_list_t *attrs) { isns_object_template_t *tmpl; const isns_attr_t *attr; unsigned int i; if (attrs->ial_count == 0) return NULL; attr = attrs->ial_data[0]; tmpl = isns_object_template_find(attr->ia_tag_id); if (tmpl == NULL) return NULL; /* * 5.6.4. * * Some objects are keyed by more than one object key attribute * value. For example, the Portal object is keyed by attribute * tags 16 and 17. When describing an object keyed by more than one * key attribute, every object key attribute of that object MUST be * listed sequentially by tag value in the message before non-key * attributes of that object and key attributes of the next object. * A group of key attributes of this kind is treated as a single * logical key attribute when identifying an object. */ for (i = 1; i < tmpl->iot_num_keys; ++i) { attr = attrs->ial_data[i]; if (attr->ia_tag_id != tmpl->iot_keys[i]) return NULL; } return tmpl; } isns_object_template_t * isns_object_template_for_tag(uint32_t tag) { isns_object_template_t *tmpl; unsigned int i, j; isns_object_maps_init(); if (tag < MAX_QUICK_TAG) return isns_object_template_any_map[tag]; for (i = 0; (tmpl = isns_object_templates[i]) != NULL; ++i) { for (j = 0; j < tmpl->iot_num_attrs; ++j) { if (tmpl->iot_attrs[j] == tag) return tmpl; } } return NULL; } isns_object_template_t * isns_object_template_for_index_tag(uint32_t tag) { isns_object_maps_init(); if (tag >= MAX_QUICK_TAG) return NULL; return isns_object_template_idx_map[tag]; } isns_object_template_t * isns_object_template_by_name(const char *name) { isns_object_template_t **pp, *tmpl; pp = isns_object_templates; while ((tmpl = *pp++) != NULL) { if (!strcasecmp(tmpl->iot_name, name)) return tmpl; } return NULL; } const char * isns_object_template_name(isns_object_template_t *tmpl) { if (!tmpl) return NULL; return tmpl->iot_name; } /* * Notify any listeners that the object has changed, * and mark it dirty. * dd_or_dds is used for DD_MEMBER_ADDED and * DD_MEMBER_REMOVED events, and refers to the * domain or domain set the object was added to or * removed from. */ void isns_mark_object(isns_object_t *obj, unsigned int how) { obj->ie_flags |= ISNS_OBJECT_DIRTY; obj->ie_mtime = time(NULL); obj->ie_scn_bits |= (1 << how); isns_object_event(obj, 0, NULL); } static void __isns_mark_object(isns_object_t *obj) { obj->ie_flags |= ISNS_OBJECT_DIRTY; obj->ie_mtime = time(NULL); } /* * Create an object given its object template */ isns_object_t * isns_create_object(isns_object_template_t *tmpl, const isns_attr_list_t *attrs, isns_object_t *parent) { isns_object_t *obj; unsigned int i; /* Enforce containment rules. */ if (parent) isns_assert(tmpl->iot_container == parent->ie_template); #ifdef notdef /* This check is somewhat costly: */ if (attrs && tmpl != isns_object_template_for_key_attrs(attrs)) return NULL; #endif obj = isns_calloc(1, sizeof(*obj)); obj->ie_users = 1; obj->ie_template = tmpl; isns_attr_list_init(&obj->ie_attrs); if (parent) isns_object_attach(obj, parent); if (attrs == NULL) { /* Make sure that all key attrs are instantiated * and in sequence. */ for (i = 0; i < tmpl->iot_num_keys; ++i) isns_attr_list_append_nil(&obj->ie_attrs, tmpl->iot_keys[i]); } else { /* We rely on the caller to ensure that * attributes are in proper sequence. */ isns_attr_list_copy(&obj->ie_attrs, attrs); } /* Just mark it dirty, but do not schedule a * SCN event. */ __isns_mark_object(obj); return obj; } /* * Obtain an additional reference on the object */ isns_object_t * isns_object_get(isns_object_t *obj) { if (obj) { isns_assert(obj->ie_users); obj->ie_users++; } return obj; } /* * Release a reference on the object */ void isns_object_release(isns_object_t *obj) { unsigned int i; isns_object_t *child; if (!obj) return; isns_assert(obj->ie_users); if (--(obj)->ie_users != 0) return; /* Must not have any live references to it */ isns_assert(obj->ie_references == 0); /* Must be detached from parent */ isns_assert(obj->ie_container == NULL); /* Release all children. We explicitly clear * ie_container because the destructor * checks for this (in order to catch * refcounting bugs) */ for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; child->ie_container = NULL; } isns_object_list_destroy(&obj->ie_children); isns_attr_list_destroy(&obj->ie_attrs); isns_bitvector_free(obj->ie_membership); isns_free(obj); } /* * Get the topmost container (ie Network Entity) * for the given object */ isns_object_t * isns_object_get_entity(isns_object_t *obj) { if (obj == NULL) return NULL; while (obj->ie_container) obj = obj->ie_container; if (!ISNS_IS_ENTITY(obj)) return NULL; return obj; } int isns_object_contains(const isns_object_t *ancestor, const isns_object_t *descendant) { while (descendant) { if (descendant == ancestor) return 1; descendant = descendant->ie_container; } return 0; } /* * Get all children of the specified type */ void isns_object_get_descendants(const isns_object_t *obj, isns_object_template_t *tmpl, isns_object_list_t *result) { isns_object_t *child; unsigned int i; for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; if (!tmpl || child->ie_template == tmpl) isns_object_list_append(result, child); } } /* * Attach an object to a new container */ int isns_object_attach(isns_object_t *obj, isns_object_t *parent) { isns_assert(obj->ie_container == NULL); if (parent) { /* Copy the owner (ie source) from the parent * object. * Make sure the parent object type is a valid * container for this object. */ if (parent->ie_template != obj->ie_template->iot_container) { isns_error("You are not allowed to add a %s object " "to a %s!\n", obj->ie_template->iot_name, parent->ie_template->iot_name); return 0; } obj->ie_flags = parent->ie_flags & ISNS_OBJECT_PRIVATE; isns_object_list_append(&parent->ie_children, obj); } obj->ie_container = parent; return 1; } int isns_object_is_valid_container(const isns_object_t *container, isns_object_template_t *child_type) { return child_type->iot_container == container->ie_template; } /* * Detach an object from its container */ int isns_object_detach(isns_object_t *obj) { isns_object_t *parent; /* Detach from parent */ if ((parent = obj->ie_container) != NULL) { int removed; obj->ie_container = NULL; removed = isns_object_list_remove( &parent->ie_children, obj); isns_assert(removed != 0); } return 0; } /* * Check the type of an object */ int isns_object_is(const isns_object_t *obj, isns_object_template_t *tmpl) { return obj->ie_template == tmpl; } int isns_object_is_iscsi_node(const isns_object_t *obj) { return ISNS_IS_ISCSI_NODE(obj); } int isns_object_is_fc_port(const isns_object_t *obj) { return ISNS_IS_FC_PORT(obj); } int isns_object_is_fc_node(const isns_object_t *obj) { return ISNS_IS_FC_NODE(obj); } int isns_object_is_portal(const isns_object_t *obj) { return ISNS_IS_PORTAL(obj); } int isns_object_is_pg(const isns_object_t *obj) { return ISNS_IS_PG(obj); } int isns_object_is_policy(const isns_object_t *obj) { return ISNS_IS_POLICY(obj); } /* * Match an object against a list of attributes. */ int isns_object_match(const isns_object_t *obj, const isns_attr_list_t *attrs) { isns_object_template_t *tmpl = obj->ie_template; isns_attr_t *self, *match; unsigned int i, j, from = 0; uint32_t tag; /* Fast path: try to compare in-order */ while (from < attrs->ial_count) { match = attrs->ial_data[from]; self = obj->ie_attrs.ial_data[from]; if (match->ia_tag_id != self->ia_tag_id) goto slow_path; if (!isns_attr_match(self, match)) return 0; from++; } return 1; slow_path: for (i = from; i < attrs->ial_count; ++i) { isns_attr_t *found = NULL; match = attrs->ial_data[i]; /* * 5.6.5.2 * A Message Key with zero-length TLV(s) is scoped to * every object of the type indicated by the zero-length * TLV(s) */ if (match->ia_value.iv_type == &isns_attr_type_nil) { tag = match->ia_tag_id; if (isns_object_attr_valid(tmpl, tag)) continue; return 0; } for (j = from; j < obj->ie_attrs.ial_count; ++j) { self = obj->ie_attrs.ial_data[j]; if (match->ia_tag_id == self->ia_tag_id) { found = self; break; } } if (found == NULL) return 0; if (!isns_attr_match(self, match)) return 0; } return 1; } /* * Find descendant object matching the given key */ isns_object_t * isns_object_find_descendant(isns_object_t *obj, const isns_attr_list_t *keys) { isns_object_list_t list = ISNS_OBJECT_LIST_INIT; isns_object_t *found; if (!isns_object_find_descendants(obj, NULL, keys, &list)) return NULL; found = isns_object_get(list.iol_data[0]); isns_object_list_destroy(&list); return found; } int isns_object_find_descendants(isns_object_t *obj, isns_object_template_t *tmpl, const isns_attr_list_t *keys, isns_object_list_t *result) { isns_object_t *child; unsigned int i; if ((tmpl == NULL || tmpl == obj->ie_template) && (keys == NULL || isns_object_match(obj, keys))) isns_object_list_append(result, obj); for (i = 0; i < obj->ie_children.iol_count; ++i) { child = obj->ie_children.iol_data[i]; isns_object_find_descendants(child, tmpl, keys, result); } return result->iol_count; } /* * Return the object's modification time stamp */ time_t isns_object_last_modified(const isns_object_t *obj) { return obj->ie_mtime; } /* * Set the SCN bitmap */ void isns_object_set_scn_mask(isns_object_t *obj, uint32_t bitmap) { obj->ie_scn_mask = bitmap; __isns_mark_object(obj); } /* * Debugging utility: print the object */ void isns_object_print(isns_object_t *obj, isns_print_fn_t *fn) { isns_attr_list_print(&obj->ie_attrs, fn); } /* * Return a string representing the object state */ const char * isns_object_state_string(unsigned int state) { switch (state) { case ISNS_OBJECT_STATE_LARVAL: return "larval"; case ISNS_OBJECT_STATE_MATURE: return "mature"; case ISNS_OBJECT_STATE_LIMBO: return "limbo"; case ISNS_OBJECT_STATE_DEAD: return "dead"; } return "UNKNOWN"; } /* * This is needed when deregistering an object. * Remove all attributes except the key and index attrs. */ void isns_object_prune_attrs(isns_object_t *obj) { isns_object_template_t *tmpl = obj->ie_template; uint32_t tags[16]; unsigned int i; isns_assert(tmpl->iot_num_keys + 1 <= 16); for (i = 0; i < tmpl->iot_num_keys; ++i) tags[i] = tmpl->iot_keys[i]; if (tmpl->iot_index) tags[i++] = tmpl->iot_index; isns_attr_list_prune(&obj->ie_attrs, tags, i); } /* * Convenience functions */ /* * Create a portal object. * For now, always assume TCP. */ isns_object_t * isns_create_portal(const isns_portal_info_t *info, isns_object_t *parent) { isns_object_t *obj; obj = isns_create_object(&isns_portal_template, NULL, parent); isns_portal_to_object(info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, obj); return obj; } /* * Extract all key attrs and place them * in the attribute list. */ int isns_object_extract_keys(const isns_object_t *obj, isns_attr_list_t *list) { isns_object_template_t *tmpl = obj->ie_template; const isns_attr_list_t *src = &obj->ie_attrs; unsigned int i; for (i = 0; i < tmpl->iot_num_keys; ++i) { isns_attr_t *attr; if (!isns_attr_list_get_attr(src, tmpl->iot_keys[i], &attr)) return 0; isns_attr_list_append_attr(list, attr); } return 1; } /* * Extract all attributes we are permitted to overwrite and place them * in the attribute list. */ int isns_object_extract_writable(const isns_object_t *obj, isns_attr_list_t *list) { const isns_attr_list_t *src = &obj->ie_attrs; unsigned int i; for (i = 0; i < src->ial_count; ++i) { isns_attr_t *attr = src->ial_data[i]; if (attr->ia_tag->it_readonly) continue; isns_attr_list_append_attr(list, attr); } return 1; } /* * Extract all attrs and place them * in the attribute list. We copy the attributes * as they appear inside the object; which allows * duplicate attributes (eg inside a discovery domain). */ int isns_object_extract_all(const isns_object_t *obj, isns_attr_list_t *list) { isns_attr_list_append_list(list, &obj->ie_attrs); return 1; } /* * Check if the given object is valid */ int isns_object_attr_valid(isns_object_template_t *tmpl, uint32_t tag) { const uint32_t *attr_tags = tmpl->iot_attrs; unsigned int i; for (i = 0; i < tmpl->iot_num_attrs; ++i) { if (*attr_tags == tag) return 1; ++attr_tags; } return 0; } /* * Set an object attribute */ static int __isns_object_set_attr(isns_object_t *obj, uint32_t tag, const isns_attr_type_t *type, const isns_value_t *value) { const isns_tag_type_t *tag_type; if (!isns_object_attr_valid(obj->ie_template, tag)) return 0; tag_type = isns_tag_type_by_id(tag); if (type != &isns_attr_type_nil && type != tag_type->it_type) { isns_warning("application bug: cannot set attr %s(id=%u, " "type=%s) to a value of type %s\n", tag_type->it_name, tag, tag_type->it_type->it_name, type->it_name); return 0; } isns_attr_list_update_value(&obj->ie_attrs, tag, tag_type, value); /* Timestamp updates should just be written out, but we * do not want to trigger SCN messages and such. */ if (tag != ISNS_TAG_TIMESTAMP) isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); else __isns_mark_object(obj); return 1; } /* * Copy an attribute to the object */ int isns_object_set_attr(isns_object_t *obj, isns_attr_t *attr) { isns_attr_list_t *list = &obj->ie_attrs; uint32_t tag = attr->ia_tag_id; /* If this attribute exists within the object, * and it cannot occur multiple times, replace it. */ if (!attr->ia_tag->it_multiple && isns_attr_list_replace_attr(list, attr)) goto done; /* It doesn't exist; make sure it's a valid * attribute. */ if (!isns_object_attr_valid(obj->ie_template, tag)) return 0; isns_attr_list_append_attr(list, attr); done: isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); return 1; } int isns_object_set_attrlist(isns_object_t *obj, const isns_attr_list_t *attrs) { unsigned int i; for (i = 0; i < attrs->ial_count; ++i) { isns_attr_t *attr = attrs->ial_data[i]; if (!isns_object_set_attr(obj, attr)) return 0; } isns_mark_object(obj, ISNS_SCN_OBJECT_UPDATED); return 1; } /* * Untyped version of isns_object_set. * Any type checking must be done by the caller; * failure to do so will result in the end of the world. */ int isns_object_set_value(isns_object_t *obj, uint32_t tag, const void *data) { return isns_attr_list_update(&obj->ie_attrs, tag, data); } /* * Typed versions of isns_object_set */ int isns_object_set_nil(isns_object_t *obj, uint32_t tag) { return __isns_object_set_attr(obj, tag, &isns_attr_type_nil, NULL); } int isns_object_set_string(isns_object_t *obj, uint32_t tag, const char *value) { isns_value_t var = ISNS_VALUE_INIT(string, (char *) value); int rc; rc = __isns_object_set_attr(obj, tag, &isns_attr_type_string, &var); return rc; } int isns_object_set_uint32(isns_object_t *obj, uint32_t tag, uint32_t value) { isns_value_t var = ISNS_VALUE_INIT(uint32, value); return __isns_object_set_attr(obj, tag, &isns_attr_type_uint32, &var); } int isns_object_set_uint64(isns_object_t *obj, uint32_t tag, uint64_t value) { isns_value_t var = ISNS_VALUE_INIT(uint64, value); return __isns_object_set_attr(obj, tag, &isns_attr_type_uint64, &var); } int isns_object_set_ipaddr(isns_object_t *obj, uint32_t tag, const struct in6_addr *value) { isns_value_t var = ISNS_VALUE_INIT(ipaddr, *value); return __isns_object_set_attr(obj, tag, &isns_attr_type_ipaddr, &var); } /* * Query object attributes */ int isns_object_get_attr(const isns_object_t *obj, uint32_t tag, isns_attr_t **result) { return isns_attr_list_get_attr(&obj->ie_attrs, tag, result); } int isns_object_get_attrlist(isns_object_t *obj, isns_attr_list_t *result, const isns_attr_list_t *req_attrs) { isns_attr_list_t *attrs = &obj->ie_attrs; isns_attr_t *attr; unsigned int i; if (req_attrs == NULL) { /* Retrieve all attributes */ isns_attr_list_append_list(result, attrs); } else { for (i = 0; i < req_attrs->ial_count; ++i) { uint32_t tag = req_attrs->ial_data[i]->ia_tag_id; if (tag == obj->ie_template->iot_next_index) { /* FIXME: for now, we fake this value. * We need the DB object at this point * to find out what the next unused * index is. */ isns_attr_list_append_uint32(result, tag, 0); } else if (isns_attr_list_get_attr(attrs, tag, &attr)) isns_attr_list_append_attr(result, attr); } } return 1; } int isns_object_get_key_attrs(isns_object_t *obj, isns_attr_list_t *result) { isns_object_template_t *tmpl = obj->ie_template; isns_attr_list_t *attrs = &obj->ie_attrs; isns_attr_t *attr; unsigned int i; for (i = 0; i < tmpl->iot_num_keys; ++i) { uint32_t tag = tmpl->iot_keys[i]; if (!isns_attr_list_get_attr(attrs, tag, &attr)) { isns_error("%s: %s object is missing key attr %u\n", __FUNCTION__, tmpl->iot_name, tag); return 0; } isns_attr_list_append_attr(result, attr); } return 1; } int isns_object_get_string(const isns_object_t *obj, uint32_t tag, const char **result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_STRING(attr)) return 0; *result = attr->ia_value.iv_string; return 1; } int isns_object_get_ipaddr(const isns_object_t *obj, uint32_t tag, struct in6_addr *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_IPADDR(attr)) return 0; *result = attr->ia_value.iv_ipaddr; return 1; } int isns_object_get_uint32(const isns_object_t *obj, uint32_t tag, uint32_t *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_UINT32(attr)) return 0; *result = attr->ia_value.iv_uint32; return 1; } int isns_object_get_uint64(const isns_object_t *obj, uint32_t tag, uint64_t *result) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_UINT64(attr)) return 0; *result = attr->ia_value.iv_uint64; return 1; } int isns_object_get_opaque(const isns_object_t *obj, uint32_t tag, const void **ptr, size_t *len) { isns_attr_t *attr; if (!isns_object_get_attr(obj, tag, &attr) || !ISNS_ATTR_IS_OPAQUE(attr)) return 0; *ptr = attr->ia_value.iv_opaque.ptr; *len = attr->ia_value.iv_opaque.len; return 1; } int isns_object_delete_attr(isns_object_t *obj, uint32_t tag) { return isns_attr_list_remove_tag(&obj->ie_attrs, tag); } int isns_object_remove_member(isns_object_t *obj, const isns_attr_t *attr, const uint32_t *subordinate_tags) { return isns_attr_list_remove_member(&obj->ie_attrs, attr, subordinate_tags); } /* * Object list functions */ void isns_object_list_init(isns_object_list_t *list) { memset(list, 0, sizeof(*list)); } static inline void __isns_object_list_resize(isns_object_list_t *list, unsigned int count) { unsigned int max; max = (list->iol_count + 15) & ~15; if (count < max) return; count = (count + 15) & ~15; list->iol_data = isns_realloc(list->iol_data, count * sizeof(isns_object_t *)); if (!list->iol_data) isns_fatal("Out of memory!\n"); } void isns_object_list_append(isns_object_list_t *list, isns_object_t *obj) { __isns_object_list_resize(list, list->iol_count + 1); list->iol_data[list->iol_count++] = obj; obj->ie_users++; } void isns_object_list_append_list(isns_object_list_t *dst, const isns_object_list_t *src) { unsigned int i, j; __isns_object_list_resize(dst, dst->iol_count + src->iol_count); j = dst->iol_count; for (i = 0; i < src->iol_count; ++i, ++j) { isns_object_t *obj = src->iol_data[i]; dst->iol_data[j] = obj; obj->ie_users++; } dst->iol_count = j; } int isns_object_list_contains(const isns_object_list_t *list, isns_object_t *obj) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { if (obj == list->iol_data[i]) return 1; } return 0; } isns_object_t * isns_object_list_lookup(const isns_object_list_t *list, isns_object_template_t *tmpl, const isns_attr_list_t *keys) { unsigned int i; if (!tmpl && !keys) return NULL; if (!tmpl && !(tmpl = isns_object_template_for_key_attrs(keys))) return NULL; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template != tmpl) continue; if (keys && !isns_object_match(obj, keys)) continue; obj->ie_users++; return obj; } return NULL; } int isns_object_list_gang_lookup(const isns_object_list_t *list, isns_object_template_t *tmpl, const isns_attr_list_t *keys, isns_object_list_t *result) { unsigned int i; if (!tmpl && !keys) return ISNS_INVALID_QUERY; if (!tmpl && !(tmpl = isns_object_template_for_key_attrs(keys))) return ISNS_INVALID_QUERY; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj->ie_template != tmpl) continue; if (keys && !isns_object_match(obj, keys)) continue; isns_object_list_append(result, obj); } return ISNS_SUCCESS; } void isns_object_list_destroy(isns_object_list_t *list) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_release(obj); } isns_free(list->iol_data); memset(list, 0, sizeof(*list)); } int isns_object_list_remove(isns_object_list_t *list, isns_object_t *tbr) { unsigned int i, last; last = list->iol_count - 1; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (obj == tbr) { list->iol_data[i] = list->iol_data[last]; list->iol_count--; isns_object_release(tbr); return 1; } } return 0; } static int isns_object_compare_id(const void *pa, const void *pb) { const isns_object_t *a = *(const isns_object_t **) pa; const isns_object_t *b = *(const isns_object_t **) pb; return (int) a->ie_index - (int) b->ie_index; } void isns_object_list_sort(isns_object_list_t *list) { if (list->iol_count == 0) return; qsort(list->iol_data, list->iol_count, sizeof(void *), isns_object_compare_id); } void isns_object_list_uniq(isns_object_list_t *list) { isns_object_t *prev = NULL, *this; unsigned int i, j; isns_object_list_sort(list); for (i = j = 0; i < list->iol_count; i++) { this = list->iol_data[i]; if (this != prev) list->iol_data[j++] = this; prev = this; } list->iol_count = j; } void isns_object_list_print(const isns_object_list_t *list, isns_print_fn_t *fn) { unsigned int i; if (list->iol_count == 0) { fn("(Object list empty)\n"); return; } for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj; obj = list->iol_data[i]; fn("object[%u] = <%s>\n", i, obj->ie_template->iot_name); isns_object_print(obj, fn); } } /* * Handle object references */ void isns_object_reference_set(isns_object_ref_t *ref, isns_object_t *obj) { isns_object_t *old; if (obj) { isns_assert(obj->ie_users); obj->ie_references++; obj->ie_users++; } if ((old = ref->obj) != NULL) { isns_assert(old->ie_references); old->ie_references--; isns_object_release(old); } ref->obj = obj; } void isns_object_reference_drop(isns_object_ref_t *ref) { isns_object_reference_set(ref, NULL); } /* * Helper function for portal/object conversion */ int isns_portal_from_object(isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, const isns_object_t *obj) { return isns_portal_from_attr_list(portal, addr_tag, port_tag, &obj->ie_attrs); } int isns_portal_to_object(const isns_portal_info_t *portal, uint32_t addr_tag, uint32_t port_tag, isns_object_t *obj) { return isns_portal_to_attr_list(portal, addr_tag, port_tag, &obj->ie_attrs); } /* * Portal */ static uint32_t portal_attrs[] = { ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, ISNS_TAG_PORTAL_SYMBOLIC_NAME, ISNS_TAG_ESI_INTERVAL, ISNS_TAG_ESI_PORT, ISNS_TAG_PORTAL_INDEX, ISNS_TAG_SCN_PORT, ISNS_TAG_PORTAL_NEXT_INDEX, ISNS_TAG_PORTAL_SECURITY_BITMAP, ISNS_TAG_PORTAL_ISAKMP_PHASE_1, ISNS_TAG_PORTAL_ISAKMP_PHASE_2, ISNS_TAG_PORTAL_CERTIFICATE, }; static uint32_t portal_key_attrs[] = { ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, }; isns_object_template_t isns_portal_template = { .iot_name = "Portal", .iot_handle = ISNS_OBJECT_TYPE_PORTAL, .iot_attrs = portal_attrs, .iot_num_attrs = array_num_elements(portal_attrs), .iot_keys = portal_key_attrs, .iot_num_keys = array_num_elements(portal_key_attrs), .iot_index = ISNS_TAG_PORTAL_INDEX, .iot_next_index = ISNS_TAG_PORTAL_NEXT_INDEX, .iot_container = &isns_entity_template, }; open-iscsi-2.0.873/utils/open-isns/objects.h000066400000000000000000000106161175631155400206350ustar00rootroot00000000000000/* * iSNS object model * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_OBJECTS_H #define ISNS_OBJECTS_H #include "isns.h" #include "attrs.h" enum isns_object_id { ISNS_OBJECT_TYPE_ENTITY = 1, ISNS_OBJECT_TYPE_NODE, ISNS_OBJECT_TYPE_PORTAL, ISNS_OBJECT_TYPE_PG, ISNS_OBJECT_TYPE_DD, ISNS_OBJECT_TYPE_DDSET, ISNS_OBJECT_TYPE_POLICY, ISNS_OBJECT_TYPE_FC_PORT, ISNS_OBJECT_TYPE_FC_NODE, __ISNS_OBJECT_TYPE_MAX }; struct isns_object_template { const char * iot_name; unsigned int iot_handle; /* internal handle */ unsigned int iot_num_attrs; unsigned int iot_num_keys; uint32_t * iot_attrs; uint32_t * iot_keys; uint32_t iot_index; uint32_t iot_next_index; isns_object_template_t *iot_container; unsigned int iot_relation_type; isns_relation_t * (*iot_build_relation)(isns_db_t *, isns_object_t *, const isns_object_list_t *); unsigned int iot_vendor_specific : 1; }; struct isns_object { /* There are two kinds of users of an object * - Temporary references that result from the * object being examined; being on a list, * etc. The main purpose of these references * is to make sure the object doesn't go away * while being used. * * These are accounted for by ie_users. * * - Permanent references that result from the * object being references by other objects * (usually relations) such as a Portal Group, * or a Discovery Domain. * * These are accounted for by ie_references. * * The main purpose of these references is to * model some of the weirder life cycle states * described in RFC 4711. * * Every reference via ie_references implies a * reference via ie_users. */ unsigned int ie_users; unsigned int ie_references; uint32_t ie_index; unsigned int ie_state; unsigned int ie_flags; time_t ie_mtime; uint32_t ie_scn_mask; /* Events this node listens for */ uint32_t ie_scn_bits; /* Current event bits */ isns_attr_list_t ie_attrs; isns_object_t * ie_container; uint32_t ie_container_idx; isns_object_template_t *ie_template; isns_relation_t * ie_relation; isns_object_list_t ie_children; /* Bit vector describing DD membership */ isns_bitvector_t * ie_membership; /* Support for virtual objects */ int (*ie_rebuild)(isns_object_t *, isns_db_t *); }; typedef struct isns_object_ref { isns_object_t * obj; } isns_object_ref_t; enum { ISNS_RELATION_NONE = 0, ISNS_RELATION_PORTAL_GROUP, }; struct isns_relation { unsigned int ir_type; unsigned int ir_users; isns_object_t * ir_object; isns_object_ref_t ir_subordinate[2]; }; typedef struct isns_relation_soup isns_relation_soup_t; typedef struct isns_relation_list isns_relation_list_t; struct isns_relation_list { unsigned int irl_count; isns_relation_t ** irl_data; }; #define ISNS_RELATION_LIST_INIT { .irl_count = 0, .irl_data = NULL } #define ISNS_OBJECT_DIRTY 0x0001 #define ISNS_OBJECT_PRIVATE 0x0002 #define ISNS_OBJECT_DEAD 0x0004 enum { ISNS_OBJECT_STATE_LARVAL, ISNS_OBJECT_STATE_MATURE, ISNS_OBJECT_STATE_LIMBO, ISNS_OBJECT_STATE_DEAD, }; extern int isns_object_remove_member(isns_object_t *obj, const isns_attr_t *attr, const uint32_t *subordinate_tags); extern void isns_object_reference_set(isns_object_ref_t *ref, isns_object_t *obj); extern void isns_object_reference_drop(isns_object_ref_t *ref); extern const char *isns_object_state_string(unsigned int); extern isns_object_template_t *isns_object_template_by_name(const char *); extern int isns_object_is_valid_container(const isns_object_t *, isns_object_template_t *); extern void isns_object_set_scn_mask(isns_object_t *, uint32_t); extern isns_object_t *isns_create_default_domain(void); /* * Helper macros for object type check */ #define __ISNS_OBJECT_TYPE_CHECK(obj, type) \ ((obj)->ie_template == &isns_##type##_template) #define ISNS_IS_ENTITY(obj) __ISNS_OBJECT_TYPE_CHECK(obj, entity) #define ISNS_IS_ISCSI_NODE(obj) __ISNS_OBJECT_TYPE_CHECK(obj, iscsi_node) #define ISNS_IS_FC_PORT(obj) __ISNS_OBJECT_TYPE_CHECK(obj, fc_port) #define ISNS_IS_FC_NODE(obj) __ISNS_OBJECT_TYPE_CHECK(obj, fc_node) #define ISNS_IS_PORTAL(obj) __ISNS_OBJECT_TYPE_CHECK(obj, portal) #define ISNS_IS_PG(obj) __ISNS_OBJECT_TYPE_CHECK(obj, iscsi_pg) #define ISNS_IS_POLICY(obj) __ISNS_OBJECT_TYPE_CHECK(obj, policy) #define ISNS_IS_DD(obj) __ISNS_OBJECT_TYPE_CHECK(obj, dd) #define ISNS_IS_DDSET(obj) __ISNS_OBJECT_TYPE_CHECK(obj, ddset) #endif /* ISNS_OBJECTS_H */ open-iscsi-2.0.873/utils/open-isns/parser.c000066400000000000000000000042271175631155400204740ustar00rootroot00000000000000/* * parser.c - simple line based parser * * Copyright (C) 2006, 2007 Olaf Kirch */ #include #include #include #include #include #include #include "util.h" /* * By default, the parser will recognize any white space * as "word" separators. * If you need additional separators, you can put them * here. */ const char * parser_separators = NULL; const char * parser_punctuation = "="; char * parser_get_next_line(FILE *fp) { static char buffer[8192]; unsigned int n = 0, count = 0; int c, continuation = 0; while (n < sizeof(buffer) - 1) { c = fgetc(fp); if (c == EOF) break; count++; if (c == '\r') continue; /* Discard all blanks * following a backslash-newline */ if (continuation) { if (c == ' ' || c == '\t') continue; continuation = 0; } if (c == '\n') { if (n && buffer[n-1] == '\\') { buffer[--n] = '\0'; continuation = 1; } while (n && isspace(buffer[n-1])) buffer[--n] = '\0'; if (!continuation) break; buffer[n++] = ' '; continue; } buffer[n++] = c; } if (count == 0) return NULL; buffer[n] = '\0'; return buffer; } static inline int is_separator(char c) { if (isspace(c)) return 1; return parser_separators && c && strchr(parser_separators, c); } static inline int is_punctuation(char c) { return parser_punctuation && c && strchr(parser_punctuation, c); } char * parser_get_next_word(char **sp) { static char buffer[512]; char *s = *sp, *p = buffer; while (is_separator(*s)) ++s; if (*s == '\0') goto done; if (is_punctuation(*s)) { *p++ = *s++; goto done; } while (*s && !is_separator(*s) && !is_punctuation(*s)) *p++ = *s++; done: *p++ = '\0'; *sp = s; return buffer[0]? buffer : NULL; } int parser_split_line(char *line, unsigned int argsmax, char **argv) { unsigned int argc = 0; char *s; while (argc < argsmax && (s = parser_get_next_word(&line))) argv[argc++] = strdup(s); return argc; } char * parser_get_rest_of_line(char **sp) { char *s = *sp, *res = NULL; while (is_separator(*s)) ++s; *sp = ""; if (*s != '\0') res = s; return res; } open-iscsi-2.0.873/utils/open-isns/paths.h000066400000000000000000000013061175631155400203170ustar00rootroot00000000000000/* * Compile time configuration. * For now, let's keep it simple and ignore autoconf... * * Copyright (C) 2006, 2007 Olaf Kirch */ #ifndef ISNS_CONFIG_H #define ISNS_CONFIG_H #define __OPENISNS_MKVERSION(maj, min) (((maj) << 8) + (min)) #define OPENISNS_VERSION __OPENISNS_MKVERSION(0, 90); #define OPENISNS_VERSION_STRING "0.90" #define ISNS_ETCDIR "/etc/isns" #define ISNS_RUNDIR "/var/run" #define ISNS_DEFAULT_ISNSD_CONFIG ISNS_ETCDIR "/isnsd.conf" #define ISNS_DEFAULT_ISNSDD_CONFIG ISNS_ETCDIR "/isnsdd.conf" #define ISNS_DEFAULT_ISNSADM_CONFIG ISNS_ETCDIR "/isnsadm.conf" #define ISNS_DEFAULT_LOCAL_REGISTRY ISNS_RUNDIR "/isns.registry" #endif /* ISNS_CONFIG_H */ open-iscsi-2.0.873/utils/open-isns/pidfile.c000066400000000000000000000032721175631155400206130ustar00rootroot00000000000000/* * write pidfile * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include "util.h" static void __update_pidfile(int fd) { char pidbuf[32]; snprintf(pidbuf, sizeof(pidbuf), "%u\n", getpid()); if (write(fd, pidbuf, strlen(pidbuf)) < 0) isns_fatal("Error writing pid file: %m\n"); close(fd); } static pid_t __read_pidfile(const char *filename) { char pidbuf[32]; FILE *fp; pid_t pid = -1; fp = fopen(filename, "r"); if (fp != NULL) { if (fgets(pidbuf, sizeof(pidbuf), fp)) pid = strtoul(pidbuf, NULL, 0); fclose(fp); } return pid; } void isns_write_pidfile(const char *filename) { int fd; pid_t pid; fd = open(filename, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd >= 0) { __update_pidfile(fd); return; } if (errno != EEXIST) isns_fatal("Error creating pid file %s: %m\n", filename); /* If the pid file is stale, remove it. * Not really needed in real life, but * highly convenient for debugging :) */ if ((pid = __read_pidfile(filename)) > 0 && kill(pid, 0) < 0 && errno == ESRCH) { isns_debug_general( "Removing stale PID file %s\n", filename); unlink(filename); } /* Try again */ fd = open(filename, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd < 0) isns_fatal("PID file exists; another daemon " "seems to be running\n"); __update_pidfile(fd); } void isns_update_pidfile(const char *filename) { int fd; fd = open(filename, O_WRONLY); if (fd < 0) { isns_fatal("Error opening pid file %s: %m\n", filename); } __update_pidfile(fd); } void isns_remove_pidfile(const char *filename) { unlink(filename); } open-iscsi-2.0.873/utils/open-isns/pki.c000066400000000000000000000257631175631155400177730ustar00rootroot00000000000000/* * PKI related functions * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include #include "isns.h" #include "security.h" #include "util.h" #include "config.h" #ifdef WITH_SECURITY /* versions prior to 9.6.8 didn't seem to have these */ #if OPADDRCONFIGENSSL_VERSION_NUMBER < 0x00906080L # define EVP_MD_CTX_init(c) do { } while (0) # define EVP_MD_CTX_cleanup(c) do { } while (0) #endif #if OPADDRCONFIGENSSL_VERSION_NUMBER < 0x00906070L # define i2d_DSA_PUBKEY i2d_DSA_PUBKEY_backwards static int i2d_DSA_PUBKEY_backwards(DSA *, unsigned char **); #endif static int isns_openssl_init = 0; static int isns_dsasig_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *); static int isns_dsasig_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *); static EVP_PKEY *isns_dsasig_load_private_pem(isns_security_t *ctx, const char *filename); static EVP_PKEY *isns_dsasig_load_public_pem(isns_security_t *ctx, const char *filename); static DSA * isns_dsa_load_params(const char *); /* * Create a DSA security context */ isns_security_t * isns_create_dsa_context(void) { isns_security_t *ctx; if (!isns_openssl_init) { ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); isns_openssl_init = 1; } ctx = isns_calloc(1, sizeof(*ctx)); ctx->is_name = "DSA"; ctx->is_type = ISNS_AUTH_TYPE_SHA1_DSA; ctx->is_replay_window = isns_config.ic_auth.replay_window; ctx->is_timestamp_jitter = isns_config.ic_auth.timestamp_jitter; ctx->is_verify = isns_dsasig_verify; ctx->is_sign = isns_dsasig_sign; ctx->is_load_private = isns_dsasig_load_private_pem; ctx->is_load_public = isns_dsasig_load_public_pem; isns_debug_auth("Created DSA authentication context\n"); return ctx; } /* * DSA signature generation and verification */ static void isns_message_digest(EVP_MD_CTX *md, const buf_t *pdu, const struct isns_authblk *blk) { uint64_t stamp; EVP_DigestUpdate(md, buf_head(pdu), buf_avail(pdu)); /* The RFC doesn't say which pieces of the * message should be hashed. * We make an educated guess. */ stamp = htonll(blk->iab_timestamp); EVP_DigestUpdate(md, &stamp, sizeof(stamp)); } static void isns_dsasig_report_errors(const char *msg, isns_print_fn_t *fn) { unsigned long code; fn("%s - OpenSSL errors follow:\n", msg); while ((code = ERR_get_error()) != 0) fn("> %s: %s\n", ERR_func_error_string(code), ERR_reason_error_string(code)); } int isns_dsasig_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *blk) { static unsigned char signature[1024]; unsigned int sig_len = sizeof(signature); EVP_MD_CTX md_ctx; EVP_PKEY *pkey; int err; if ((pkey = peer->is_key) == NULL) return 0; if (pkey->type != EVP_PKEY_DSA) { isns_debug_message( "Incompatible public key (spi=%s)\n", peer->is_name); return 0; } if (EVP_PKEY_size(pkey) > sizeof(signature)) { isns_error("isns_dsasig_sign: signature buffer too small\n"); return 0; } if (pkey->pkey.dsa->priv_key == NULL) { isns_error("isns_dsasig_sign: oops, seems to be a public key\n"); return 0; } isns_debug_auth("Signing messages with spi=%s, DSA/%u\n", peer->is_name, EVP_PKEY_bits(pkey)); EVP_MD_CTX_init(&md_ctx); EVP_SignInit(&md_ctx, EVP_dss1()); isns_message_digest(&md_ctx, pdu, blk); err = EVP_SignFinal(&md_ctx, signature, &sig_len, pkey); EVP_MD_CTX_cleanup(&md_ctx); if (err == 0) { isns_dsasig_report_errors("EVP_SignFinal failed", isns_error); return 0; } blk->iab_sig = signature; blk->iab_sig_len = sig_len; return 1; } int isns_dsasig_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *blk) { EVP_MD_CTX md_ctx; EVP_PKEY *pkey; int err; if ((pkey = peer->is_key) == NULL) return 0; if (pkey->type != EVP_PKEY_DSA) { isns_debug_message( "Incompatible public key (spi=%s)\n", peer->is_name); return 0; } EVP_MD_CTX_init(&md_ctx); EVP_VerifyInit(&md_ctx, EVP_dss1()); isns_message_digest(&md_ctx, pdu, blk); err = EVP_VerifyFinal(&md_ctx, blk->iab_sig, blk->iab_sig_len, pkey); EVP_MD_CTX_cleanup(&md_ctx); if (err == 0) { isns_debug_auth("*** Incorrect signature ***\n"); return 0; } if (err < 0) { isns_dsasig_report_errors("EVP_VerifyFinal failed", isns_error); return 0; } isns_debug_message("Good signature from %s\n", peer->is_name?: ""); return 1; } EVP_PKEY * isns_dsasig_load_private_pem(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; FILE *fp; if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open DSA keyfile %s: %m\n", filename); return 0; } pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL); fclose(fp); return pkey; } EVP_PKEY * isns_dsasig_load_public_pem(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; FILE *fp; if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open DSA keyfile %s: %m\n", filename); return 0; } pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (pkey == NULL) { isns_dsasig_report_errors("Error loading DSA public key", isns_error); } fclose(fp); return pkey; } EVP_PKEY * isns_dsa_decode_public(const void *ptr, size_t len) { const unsigned char *der = ptr; EVP_PKEY *evp; DSA *dsa; /* Assigning ptr to a temporary variable avoids a silly * compiled warning about type-punning. */ dsa = d2i_DSA_PUBKEY(NULL, &der, len); if (dsa == NULL) return NULL; evp = EVP_PKEY_new(); EVP_PKEY_assign_DSA(evp, dsa); return evp; } int isns_dsa_encode_public(EVP_PKEY *pkey, void **ptr, size_t *len) { int bytes; *ptr = NULL; bytes = i2d_DSA_PUBKEY(pkey->pkey.dsa, (unsigned char **) ptr); if (bytes < 0) return 0; *len = bytes; return 1; } EVP_PKEY * isns_dsa_load_public(const char *name) { return isns_dsasig_load_public_pem(NULL, name); } int isns_dsa_store_private(const char *name, EVP_PKEY *key) { FILE *fp; int rv, fd; if ((fd = open(name, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) { isns_error("Cannot save DSA key to %s: %m\n", name); return 0; } if (!(fp = fdopen(fd, "w"))) { isns_error("fdopen(%s): %m\n", name); close(fd); return 0; } rv = PEM_write_PrivateKey(fp, key, NULL, NULL, 0, 0, NULL); fclose(fp); if (rv == 0) isns_dsasig_report_errors("Failed to store private key", isns_error); return rv; } int isns_dsa_store_public(const char *name, EVP_PKEY *key) { FILE *fp; int rv; if (!(fp = fopen(name, "w"))) { isns_error("Unable to open %s: %m\n", name); return 0; } rv = PEM_write_PUBKEY(fp, key); fclose(fp); if (rv == 0) isns_dsasig_report_errors("Failed to store public key", isns_error); return rv; } /* * DSA key generation */ EVP_PKEY * isns_dsa_generate_key(void) { EVP_PKEY *pkey; DSA *dsa = NULL; if (!(dsa = isns_dsa_load_params(isns_config.ic_dsa.param_file))) goto failed; if (!DSA_generate_key(dsa)) { isns_dsasig_report_errors("Failed to generate DSA key", isns_error); goto failed; } pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(pkey, dsa); return pkey; failed: if (dsa) DSA_free(dsa); return NULL; } DSA * isns_dsa_load_params(const char *filename) { FILE *fp; DSA *dsa; if (!filename) { isns_error("Cannot generate key - no DSA parameter file\n"); return NULL; } if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open %s: %m\n", filename); return NULL; } dsa = PEM_read_DSAparams(fp, NULL, NULL, NULL); fclose(fp); if (dsa == NULL) { isns_dsasig_report_errors("Error loading DSA parameters", isns_error); } return dsa; } static void isns_dsa_param_gen_callback(int stage, int index, void *dummy) { if (stage == 0) write(1, "+", 1); else if (stage == 1) write(1, ".", 1); else if (stage == 2) write(1, "/", 1); } int isns_dsa_init_params(const char *filename) { FILE *fp; DSA *dsa; if (access(filename, R_OK) == 0) return 1; isns_mkdir_recursive(isns_dirname(filename)); if (!(fp = fopen(filename, "w"))) { isns_error("Unable to open %s: %m\n", filename); return 0; } isns_notice("Generating DSA parameters; this may take a while\n"); dsa = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, isns_dsa_param_gen_callback, NULL); write(1, "\n", 1); if (dsa == NULL) { isns_dsasig_report_errors("Error generating DSA parameters", isns_error); fclose(fp); return 0; } if (!PEM_write_DSAparams(fp, dsa)) { isns_dsasig_report_errors("Error writing DSA parameters", isns_error); DSA_free(dsa); fclose(fp); return 0; } DSA_free(dsa); fclose(fp); return 1; } /* * Make sure the authentication key is present. */ int isns_dsa_init_key(const char *filename) { char pubkey_path[1024]; EVP_PKEY *pkey; isns_mkdir_recursive(isns_dirname(filename)); snprintf(pubkey_path, sizeof(pubkey_path), "%s.pub", filename); if (access(filename, R_OK) == 0 && access(pubkey_path, R_OK) == 0) return 1; if (!(pkey = isns_dsa_generate_key())) { isns_error("Failed to generate AuthKey\n"); return 0; } if (!isns_dsa_store_private(filename, pkey)) { isns_error("Unable to write private key to %s\n", filename); return 0; } isns_notice("Stored private key in %s\n", filename); if (!isns_dsa_store_public(pubkey_path, pkey)) { isns_error("Unable to write public key to %s\n", pubkey_path); return 0; } isns_notice("Stored private key in %s\n", pubkey_path); return 1; } /* * Simple keystore - this is a flat directory, with * public key files using the SPI as their name. */ typedef struct isns_simple_keystore isns_simple_keystore_t; struct isns_simple_keystore { isns_keystore_t sc_base; char * sc_dirpath; }; /* * Load a DSA key from the cert store * In fact, this will load RSA keys as well. */ static EVP_PKEY * __isns_simple_keystore_find(isns_keystore_t *store_base, const char *name, size_t namelen) { isns_simple_keystore_t *store = (isns_simple_keystore_t *) store_base; char pathname[PATH_MAX]; /* Refuse to open key files with names * that refer to parent directories */ if (memchr(name, '/', namelen) || name[0] == '.') return NULL; snprintf(pathname, sizeof(pathname), "%s/%.*s", store->sc_dirpath, (int) namelen, name); if (access(pathname, R_OK) < 0) return NULL; return isns_dsasig_load_public_pem(NULL, pathname); } isns_keystore_t * isns_create_simple_keystore(const char *dirname) { isns_simple_keystore_t *store; store = isns_calloc(1, sizeof(*store)); store->sc_base.ic_name = "simple key store"; store->sc_base.ic_find = __isns_simple_keystore_find; store->sc_dirpath = isns_strdup(dirname); return (isns_keystore_t *) store; } #if OPADDRCONFIGENSSL_VERSION_NUMBER < 0x00906070L #undef i2d_DSA_PUBKEY int i2d_DSA_PUBKEY_backwards(DSA *dsa, unsigned char **ptr) { unsigned char *buf; int len; len = i2d_DSA_PUBKEY(dsa, NULL); if (len < 0) return 0; *ptr = buf = OPENSSL_malloc(len); return i2d_DSA_PUBKEY(dsa, &buf); } #endif #endif /* WITH_SECURITY */ open-iscsi-2.0.873/utils/open-isns/policy.c000066400000000000000000000313311175631155400204730ustar00rootroot00000000000000/* * Open-iSNS policy engine * * Copyright (C) 2007 Olaf Kirch * * For now, policy is static. We can make it configurable * later. */ #include #include "isns.h" #include "security.h" #include "objects.h" #include "message.h" #include "util.h" /* A brief discussion of policy For now, a principal's name (ie its SPI string) *must* match the iSNS source name it uses. Special care needs to be taken to restrict which principals are permitted to act as a control node. For now, we don't implement control node semantics. */ static unsigned int isns_policy_gen = 0; /* * Administrative policy (everything allowed, * talks to entity "CONTROL" */ static isns_policy_t isns_superhero_powers = { .ip_name = "administrator", .ip_users = 1, .ip_gen = 0, .ip_entity = ISNS_ENTITY_CONTROL, .ip_functions = ~0, .ip_object_types = ~0, .ip_node_types = ~0, }; /* * Policy for anon user */ static isns_policy_t isns_dweeb_powers = { .ip_name = "anonymous", .ip_users = 1, .ip_gen = 0, .ip_functions = 1 << ISNS_DEVICE_ATTRIBUTE_QUERY, .ip_object_types = 0, .ip_node_types = 0, }; #define IS_ANON_POLICY(p) ((p) == &isns_dweeb_powers) /* * These are used when security is turned off. * Essentially the same as superhero, except * no eid specified. */ static isns_policy_t isns_flyingpigs_powers = { .ip_name = "insecure", .ip_users = 1, .ip_gen = 0, .ip_functions = ~0, .ip_object_types = ~0, .ip_node_types = ~0, }; isns_policy_t * isns_policy_bind(const isns_message_t *msg) { isns_policy_t *policy = NULL; isns_principal_t *princ = NULL; /* When the admin turns off gravity, * pigs can fly, too. */ if (isns_config.ic_security == 0) { policy = &isns_flyingpigs_powers; goto found; } /* If the caller is the local root user, s/he can * do anything. */ if (msg->im_creds && msg->im_creds->uid == 0) { policy = &isns_superhero_powers; goto found; } /* Tie the SPI given in the auth block to a * source name. * For now, the names have to match. Down the road, * there may be more flexible schemes. */ if ((princ = msg->im_security) != NULL) { if ((policy = princ->is_policy) != NULL) goto found; isns_error("Internal error - no policy for " "principal %s!\n", princ->is_name); } policy = &isns_dweeb_powers; found: policy->ip_users++; return policy; } /* * Check whether the call is permitted. * This is particularly useful to prevent rogue * clients from messing with Discovery Domains. */ int isns_policy_validate_function(const isns_policy_t *policy, const isns_message_t *msg) { uint32_t function = msg->im_header.i_function; int rv = 0; if (function >= 32) { isns_debug_auth("Bad function code %08x\n", function); return 0; } if (!(policy->ip_functions & (1 << function))) goto reject; rv = 1; reject: isns_debug_auth(":: policy %s function %s (%04x) %s\n", policy->ip_name, isns_function_name(function), function, rv? "permitted" : "DENIED"); return rv; } /* * Helper function to validate node names and source names */ static int __validate_node_name(const isns_policy_t *policy, const char *name) { const struct string_array *ap; unsigned int i; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) return 1; ap = &policy->ip_node_names; for (i = 0; i < ap->count; ++i) { const char *s; s = ap->list[i]; if (s == NULL) continue; if (isns_source_pattern_match(s, name)) return 1; } return 0; } /* * Validate the source of a message */ int isns_policy_validate_source(const isns_policy_t *policy, const isns_source_t *source) { const char *src_name = isns_source_name(source); int rv = 0; if (!__validate_node_name(policy, src_name)) goto reject; rv = 1; reject: isns_debug_auth(":: policy %s source %s %s\n", policy->ip_name, src_name, rv? "permitted" : "DENIED"); return rv; } /* * Check whether the entity name specified by the client * is actually his to use. */ int isns_policy_validate_entity(const isns_policy_t *policy, const char *eid) { int rv = 0, eidlen; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; /* For anonymous clients, refuse any attempt to * create an entity */ if (IS_ANON_POLICY(policy)) goto reject; /* If no entity is assigned, this means the client * is not permitted to specify its own entity name, * and accept what we assign it. */ if (policy->ip_entity == NULL) goto reject; eidlen = strlen(policy->ip_entity); if (strncasecmp(policy->ip_entity, eid, eidlen) && (eid[eidlen] == ':' || eid[eidlen] == '\0')) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s entity ID %s %s\n", policy->ip_name, eid, rv? "permitted" : "DENIED"); return rv; } const char * isns_policy_default_entity(const isns_policy_t *policy) { return policy->ip_entity; } int isns_policy_validate_node_name(const isns_policy_t *policy, const char *node_name) { int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (!__validate_node_name(policy, node_name)) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s storage node name %s %s\n", policy->ip_name, node_name, rv? "permitted" : "DENIED"); return rv; } /* * Check whether the client is allowed to access * the given object in a particular way. */ static int __isns_policy_validate_object_access(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, isns_object_template_t *tmpl, unsigned int function) { uint32_t mask, perm = ISNS_PERMISSION_WRITE; int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (function == ISNS_DEVICE_ATTRIBUTE_QUERY || function == ISNS_DEVICE_GET_NEXT) perm = ISNS_PERMISSION_READ; /* * 5.6.1. Source Attribute * * For messages that change the contents of the iSNS * database, the iSNS server MUST verify that the Source * Attribute identifies either a Control Node or a Storage * Node that is a part of the Network Entity containing * the added, deleted, or modified objects. * * Note: this statement makes sense for nodes, portals * etc, but not for discovery domains, which are not * part of any network entity (but the Control Node clause * above still applies). */ if (perm == ISNS_PERMISSION_WRITE && obj != NULL) { const isns_object_t *entity; entity = obj->ie_container; if (entity && entity != source->is_entity) goto refuse; /* You're not allowed to modify virtual objects */ if (obj->ie_rebuild) goto refuse; } /* Check whether the client is permitted to access such an object */ mask = ISNS_ACCESS(tmpl->iot_handle, perm); if (!(policy->ip_object_types & mask)) goto refuse; if (source->is_untrusted && (obj->ie_flags & ISNS_OBJECT_PRIVATE)) goto refuse; accept: rv = 1; refuse: if (obj) { isns_debug_auth(":: policy %s operation %s on object %08x (%s) %s\n", policy->ip_name, isns_function_name(function), obj->ie_index, tmpl->iot_name, rv? "permitted" : "DENIED"); } else { isns_debug_auth(":: policy %s operation %s on %s object %s\n", policy->ip_name, isns_function_name(function), tmpl->iot_name, rv? "permitted" : "DENIED"); } return rv; } /* * Check whether the client is allowed to access * the given object. This is called for read functions. */ int isns_policy_validate_object_access(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, unsigned int function) { return __isns_policy_validate_object_access(policy, source, obj, obj->ie_template, function); } /* * Check whether the client is allowed to update * the given object. */ int isns_policy_validate_object_update(const isns_policy_t *policy, const isns_source_t *source, const isns_object_t *obj, const isns_attr_list_t *attrs, unsigned int function) { return __isns_policy_validate_object_access(policy, source, obj, obj->ie_template, function); } /* * Check whether the client is allowed to create an object * with the given attrs. */ int isns_policy_validate_object_creation(const isns_policy_t *policy, const isns_source_t *source, isns_object_template_t *tmpl, const isns_attr_list_t *keys, const isns_attr_list_t *attrs, unsigned int function) { const char *name = NULL; if (tmpl == &isns_entity_template) { /* DevReg messages may contain an empty EID * string, which means the server should select * one. */ if (isns_attr_list_get_string(keys, ISNS_TAG_ENTITY_IDENTIFIER, &name) && !isns_policy_validate_entity(policy, name)) return 0; } if (tmpl == &isns_iscsi_node_template) { if (isns_attr_list_get_string(keys, ISNS_TAG_ISCSI_NAME, &name) && !isns_policy_validate_node_name(policy, name)) return 0; } /* Should we also include the permitted portals * in the policy? */ return __isns_policy_validate_object_access(policy, source, NULL, tmpl, function); } /* * Check whether the client is permitted to access * or create an object of this type. * FIXME: Pass R/W permission bit */ int isns_policy_validate_object_type(const isns_policy_t *policy, isns_object_template_t *tmpl, unsigned int function) { uint32_t mask; int rv = 0; /* Control nodes get to do everything */ if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; mask = ISNS_ACCESS_R(tmpl->iot_handle); if (!(policy->ip_object_types & mask)) goto reject; accept: rv = 1; reject: isns_debug_auth(":: policy %s operation %s on object type %s %s\n", policy->ip_name, isns_function_name(function), tmpl->iot_name, rv? "permitted" : "DENIED"); return rv; } int isns_policy_validate_node_type(const isns_policy_t *policy, uint32_t type) { int rv = 0; if ((~policy->ip_node_types & type) == 0) rv = 1; isns_debug_auth(":: policy %s registration of node type 0x%x %s\n", policy->ip_name, type, rv? "permitted" : "DENIED"); return rv; } /* * 6.4.4. * Management SCNs provide information about all changes to the network, * regardless of discovery domain membership. Registration for management * SCNs is indicated by setting bit 26 to 1. Only Control Nodes may * register for management SCNs. Bits 30 and 31 may only be enabled if * bit 26 is set to 1. */ int isns_policy_validate_scn_bitmap(const isns_policy_t *policy, uint32_t bitmap) { int rv = 1; if (policy->ip_node_types & ISNS_ISCSI_CONTROL_MASK) goto accept; if (!(bitmap & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK)) { if (bitmap & (ISNS_SCN_DD_MEMBER_ADDED_MASK | ISNS_SCN_DD_MEMBER_REMOVED_MASK)) goto reject; goto accept; } reject: rv = 0; accept: isns_debug_auth(":: policy %s scn bitmap 0x%x %s\n", policy->ip_name, bitmap, rv? "permitted" : "DENIED"); return rv; } /* * Create the default policy for a given SPI */ isns_policy_t * isns_policy_default(const char *spi, size_t len) { return __isns_policy_alloc(spi, len); } /* * Create the policy object for the server we're * talking to. The server is allowed to send us * ESI and SCN messages, and that's about it. */ isns_policy_t * isns_policy_server(void) { isns_policy_t *policy; policy = __isns_policy_alloc("", 8); policy->ip_functions = (1 << ISNS_ENTITY_STATUS_INQUIRY) | (1 << ISNS_STATE_CHANGE_NOTIFICATION); policy->ip_node_types = 0; policy->ip_object_types = 0; isns_string_array_append(&policy->ip_node_names, "*"); return policy; } /* * Allocate an empty policy object */ isns_policy_t * __isns_policy_alloc(const char *spi, size_t len) { isns_policy_t *policy; policy = isns_calloc(1, sizeof(*policy)); policy->ip_name = isns_malloc(len + 1); policy->ip_users = 1; policy->ip_gen = isns_policy_gen; memcpy(policy->ip_name, spi, len); policy->ip_name[len] = '\0'; /* Only register/query allowed */ policy->ip_functions = (1 << ISNS_DEVICE_ATTRIBUTE_REGISTER) | (1 << ISNS_DEVICE_ATTRIBUTE_QUERY) | (1 << ISNS_DEVICE_GET_NEXT) | (1 << ISNS_DEVICE_DEREGISTER) | (1 << ISNS_SCN_REGISTER); /* Can only register initiator node(s) */ policy->ip_node_types = ISNS_ISCSI_INITIATOR_MASK; /* Can only view/modify standard objects */ policy->ip_object_types = ISNS_DEFAULT_OBJECT_ACCESS; return policy; } /* * Release a policy object */ void isns_policy_release(isns_policy_t *policy) { if (!policy) return; isns_assert(policy->ip_users); if (--(policy->ip_users)) return; isns_assert(policy != &isns_superhero_powers); isns_assert(policy != &isns_flyingpigs_powers); isns_assert(policy != &isns_dweeb_powers); isns_free(policy->ip_name); isns_free(policy->ip_entity); isns_free(policy->ip_dd_default); isns_string_array_destroy(&policy->ip_node_names); isns_free(policy); } open-iscsi-2.0.873/utils/open-isns/portal-group.c000066400000000000000000000172701175631155400216350ustar00rootroot00000000000000/* * iSNS object model - portal group specific code * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "objects.h" #include "vendor.h" #include "attrs.h" #include "util.h" /* For relationship stuff - should go */ #include "db.h" /* * Retrieve attribute @old_tag from object @obj, create a copy with * tag @new_tag, and append it to list @dst. * (Helper function for the portal group stuff) */ static int __isns_object_translate_attr(isns_object_t *obj, uint32_t old_tag, uint32_t new_tag, isns_attr_list_t *dst) { isns_value_t value; if (!isns_attr_list_get_value(&obj->ie_attrs, old_tag, &value)) return 0; isns_attr_list_append_value(dst, new_tag, NULL, &value); return 1; } /* * Portal Group */ static isns_object_t * __isns_pg_create(const isns_attr_list_t *attrs, uint32_t pg_tag, isns_object_t *portal, isns_object_t *node) { isns_object_t *obj; obj = isns_create_object(&isns_iscsi_pg_template, attrs, isns_object_get_entity(portal)); /* * 3.4 * * Each Portal and iSCSI Storage Node registered in an Entity can * be associated using a Portal Group (PG) object. The PG Tag * (PGT), if non-NULL, indicates that the associated Portal * provides access to the associated iSCSI Storage Node in * the Entity. All Portals that have the same PGT value for * a specific iSCSI Storage Node allow coordinated access to * that node. * * 5.6.5.2 * * If the PGT of the Portal Group is not NULL, then a relationship * exists between the indicated Storage Node and Portal; if the * PGT is NULL, then no relationship exists. */ if (pg_tag != 0) { isns_object_set_uint32(obj, ISNS_TAG_PG_TAG, pg_tag); } else { /* A NULL PGT indicates that the * storage node cannot be accessed through * this portal. */ isns_object_set_nil(obj, ISNS_TAG_PG_TAG); } /* This object represents a relationship between portal and storage node. Create a relation. */ obj->ie_relation = isns_create_relation(obj, ISNS_RELATION_PORTAL_GROUP, portal, node); return obj; } /* * Find the portal for a given portal group */ static isns_object_t * __isns_pg_find_portal(isns_db_t *db, isns_object_t *pg, const isns_object_list_t *extra_objs) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_t *obj = NULL; /* FIXME: ISNS_TAG_PG_PORTAL_IP_ADDR -> ...ADDRESS */ if (!__isns_object_translate_attr(pg, ISNS_TAG_PG_PORTAL_IP_ADDR, ISNS_TAG_PORTAL_IP_ADDRESS, &key_attrs)) goto out; if (!__isns_object_translate_attr(pg, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, ISNS_TAG_PORTAL_TCP_UDP_PORT, &key_attrs)) goto out; obj = isns_db_lookup(db, &isns_portal_template, &key_attrs); if (!obj && extra_objs) obj = isns_object_list_lookup(extra_objs, &isns_portal_template, &key_attrs); out: isns_attr_list_destroy(&key_attrs); return obj; } /* * Find the node for a given portal group */ static isns_object_t * __isns_pg_find_node(isns_db_t *db, isns_object_t *pg, const isns_object_list_t *extra_objs) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_t *obj = NULL; if (!__isns_object_translate_attr(pg, ISNS_TAG_PG_ISCSI_NAME, ISNS_TAG_ISCSI_NAME, &key_attrs)) goto out; obj = isns_db_lookup(db, &isns_iscsi_node_template, &key_attrs); if (!obj && extra_objs) obj = isns_object_list_lookup(extra_objs, &isns_iscsi_node_template, &key_attrs); out: isns_attr_list_destroy(&key_attrs); return obj; } /* * When creating a portal group, it must not connect nodes and * portals from other entities. However, it is perfectly fine to * link objects in limbo. */ static inline int __isns_pg_may_relate(isns_object_t *entity, isns_object_t *subordinate) { isns_object_t *other; other = isns_object_get_entity(subordinate); return other == NULL || other == entity; } /* * Given a portal group object, create the relationship */ isns_relation_t * isns_db_build_pg_relation(isns_db_t *db, isns_object_t *pg, const isns_object_list_t *extra_objs) { isns_object_t *entity, *node = NULL, *portal = NULL; entity = isns_object_get_entity(pg); node = __isns_pg_find_node(db, pg, extra_objs); if (node == NULL) { isns_error("Trying to register PG for non-existant node\n"); goto failed; } if (!__isns_pg_may_relate(entity, node)) { isns_error("Trying to register PG for node in other entity\n"); goto failed; } portal = __isns_pg_find_portal(db, pg, extra_objs); if (portal == NULL) { isns_error("Trying to register PG for non-existant portal\n"); goto failed; } if (!__isns_pg_may_relate(entity, portal)) { isns_error("Trying to register PG for portal in other entity\n"); goto failed; } pg->ie_relation = isns_create_relation(pg, ISNS_RELATION_PORTAL_GROUP, node, portal); isns_object_release(portal); isns_object_release(node); return pg->ie_relation; failed: if (portal) isns_object_release(portal); if (node) isns_object_release(node); return NULL; } /* * Create a portal group given node, portal and PGT */ isns_object_t * isns_create_portal_group(isns_object_t *portal, isns_object_t *node, uint32_t pg_tag) { isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT; isns_object_t *obj = NULL; if (portal == NULL || node == NULL) return NULL; if (node->ie_container != portal->ie_container) { isns_error("Refusing to create portal group " "linking objects from different entities\n"); return NULL; } if (__isns_object_translate_attr(node, ISNS_TAG_ISCSI_NAME, ISNS_TAG_PG_ISCSI_NAME, &key_attrs) && __isns_object_translate_attr(portal, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PG_PORTAL_IP_ADDR, &key_attrs) && __isns_object_translate_attr(portal, ISNS_TAG_PORTAL_TCP_UDP_PORT, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, &key_attrs)) { obj = __isns_pg_create(&key_attrs, pg_tag, portal, node); } isns_attr_list_destroy(&key_attrs); return obj; } /* * 5.6.5.1 * New PG objects are registered when an associated Portal or * iSCSI Node object is registered. An explicit PG object * registration MAY follow a Portal or iSCSI Node object * registration in a DevAttrReg message. * [...] * If the PGT value is not included in the Storage Node or * Portal object registration, and if a PGT value was not * previously registered for the relationship, then the PGT for * the corresponding PG object SHALL be registered with a value * of 0x00000001. * * We return non-NULL if the object was created. */ isns_object_t * isns_create_default_portal_group(isns_db_t *db, isns_object_t *portal, isns_object_t *node) { isns_object_t *obj; if (portal == NULL || node == NULL) return 0; /* See if there is a PG already */ obj = isns_db_get_relationship_object(db, node, portal, ISNS_RELATION_PORTAL_GROUP); if (obj != NULL) { isns_object_release(obj); return NULL; } return isns_create_portal_group(portal, node, 1); } static uint32_t iscsi_pg_attrs[] = { ISNS_TAG_PG_ISCSI_NAME, ISNS_TAG_PG_PORTAL_IP_ADDR, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, ISNS_TAG_PG_TAG, ISNS_TAG_PG_INDEX, }; static uint32_t iscsi_pg_key_attrs[] = { ISNS_TAG_PG_ISCSI_NAME, ISNS_TAG_PG_PORTAL_IP_ADDR, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, }; isns_object_template_t isns_iscsi_pg_template = { .iot_name = "iSCSI Portal Group", .iot_handle = ISNS_OBJECT_TYPE_PG, .iot_attrs = iscsi_pg_attrs, .iot_num_attrs = array_num_elements(iscsi_pg_attrs), .iot_keys = iscsi_pg_key_attrs, .iot_num_keys = array_num_elements(iscsi_pg_key_attrs), .iot_attrs = iscsi_pg_attrs, .iot_keys = iscsi_pg_key_attrs, .iot_index = ISNS_TAG_PG_INDEX, .iot_next_index = ISNS_TAG_PG_NEXT_INDEX, .iot_container = &isns_entity_template, .iot_relation_type = ISNS_RELATION_PORTAL_GROUP, .iot_build_relation = isns_db_build_pg_relation, }; open-iscsi-2.0.873/utils/open-isns/query.c000066400000000000000000000134561175631155400203510ustar00rootroot00000000000000/* * Handle iSNS Device Attribute Query * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "message.h" #include "security.h" #include "objects.h" #include "db.h" #include "util.h" /* * Create a query, and set the source name */ static isns_simple_t * __isns_create_query(isns_source_t *source, const isns_attr_list_t *key) { return isns_simple_create(ISNS_DEVICE_ATTRIBUTE_QUERY, source, key); } isns_simple_t * isns_create_query(isns_client_t *clnt, const isns_attr_list_t *key) { return __isns_create_query(clnt->ic_source, key); } isns_simple_t * isns_create_query2(isns_client_t *clnt, const isns_attr_list_t *key, isns_source_t *source) { return __isns_create_query(source?: clnt->ic_source, key); } int isns_query_request_attr_tag(isns_simple_t *qry, uint32_t tag) { isns_attr_list_append_nil(&qry->is_operating_attrs, tag); return ISNS_SUCCESS; } int isns_query_request_attr(isns_simple_t *qry, isns_attr_t *attr) { if (!ISNS_ATTR_IS_NIL(attr)) { isns_error("Query operating attribute must be NIL\n"); return ISNS_INVALID_QUERY; } isns_attr_list_append_attr(&qry->is_operating_attrs, attr); return ISNS_SUCCESS; } static unsigned int isns_query_get_requested_types(const isns_attr_list_t *attrs) { unsigned int i, mask = 0; for (i = 0; i < attrs->ial_count; ++i) { uint32_t tag = attrs->ial_data[i]->ia_tag_id; isns_object_template_t *tmpl; tmpl = isns_object_template_find(tag); /* Ignore unknown tags */ if (tmpl == NULL) continue; mask |= 1 << tmpl->iot_handle; } return mask; } /* * Get the list of objects matching this query */ static int isns_query_get_objects(isns_simple_t *qry, isns_db_t *db, isns_object_list_t *result) { isns_scope_t *scope = NULL; isns_object_list_t matching = ISNS_OBJECT_LIST_INIT; isns_attr_list_t *keys = &qry->is_message_attrs; isns_object_template_t *query_type = NULL; unsigned int i, qry_mask = 0; int status; /* 5.6.5.2 * If multiple attributes are used as the Message Key, then they * MUST all be from the same object type (e.g., IP address and * TCP/UDP Port are attributes of the Portal object type). */ for (i = 0; i < keys->ial_count; ++i) { isns_object_template_t *tmpl; uint32_t tag = keys->ial_data[i]->ia_tag_id; tmpl = isns_object_template_for_tag(tag); if (tmpl == NULL) return ISNS_ATTRIBUTE_NOT_IMPLEMENTED; if (query_type == NULL) query_type = tmpl; else if (tmpl != query_type) return ISNS_INVALID_QUERY; } /* * 5.6.5.2 * An empty Message Key field indicates the query is scoped to * the entire database accessible by the source Node. */ if (keys->ial_count == 0) { query_type = &isns_entity_template; keys = NULL; } /* Policy: check whether the client is allowed to * query this type of object. */ if (!isns_policy_validate_object_type(qry->is_policy, query_type, qry->is_function)) return ISNS_SOURCE_UNAUTHORIZED; /* No scope means that the source is not part of * any discovery domain, and there's no default DD. * Just return an empty reply. */ scope = isns_scope_for_call(db, qry); if (scope == NULL) return ISNS_SUCCESS; status = isns_scope_gang_lookup(scope, query_type, keys, &matching); if (status != ISNS_SUCCESS) goto out; /* Extract the mask of requested objects */ qry_mask = isns_query_get_requested_types(&qry->is_operating_attrs); /* * 5.6.5.2 * The DevAttrQry response message returns attributes of objects * listed in the Operating Attributes that are related to the * Message Key of the original DevAttrQry message. */ for (i = 0; i < matching.iol_count; ++i) { isns_object_t *obj = matching.iol_data[i]; if (!isns_policy_validate_object_access(qry->is_policy, qry->is_source, obj, qry->is_function)) continue; if (obj->ie_container) isns_object_list_append(result, obj->ie_container); isns_object_list_append(result, obj); isns_scope_get_related(scope, obj, qry_mask, result); } out: isns_object_list_destroy(&matching); isns_scope_release(scope); return status; } /* * Create a Query Response */ static isns_simple_t * isns_create_query_response(isns_server_t *srv, const isns_simple_t *qry, const isns_object_list_t *objects) { const isns_attr_list_t *req_attrs = NULL; isns_simple_t *resp; unsigned int i; resp = __isns_create_query(srv->is_source, &qry->is_message_attrs); /* * 5.7.5.2. * If no Operating Attributes are included in the original * query, then all Operating Attributes SHALL be returned * in the response. */ if (qry->is_operating_attrs.ial_count != 0) req_attrs = &qry->is_operating_attrs; for (i = 0; i < objects->iol_count; ++i) { isns_object_t *obj = objects->iol_data[i]; if (obj->ie_rebuild) obj->ie_rebuild(obj, srv->is_db); isns_object_get_attrlist(obj, &resp->is_operating_attrs, req_attrs); } return resp; } int isns_process_query(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *reply = NULL; isns_db_t *db = srv->is_db; int status; /* Get the objects matching the query */ status = isns_query_get_objects(call, db, &objects); if (status != ISNS_SUCCESS) goto done; /* Success: build the response */ reply = isns_create_query_response(srv, call, &objects); if (reply == NULL) { status = ISNS_INTERNAL_ERROR; goto done; } /* There's nothing in the spec that tells us what to * return if the query matches no object. */ if (objects.iol_count == 0) { status = ISNS_NO_SUCH_ENTRY; goto done; } done: isns_object_list_destroy(&objects); *result = reply; return status; } /* * Parse the list of objects in a query response */ int isns_query_response_get_objects(isns_simple_t *qry, isns_object_list_t *result) { return isns_simple_response_get_objects(qry, result); } open-iscsi-2.0.873/utils/open-isns/register.c000066400000000000000000000636431175631155400210330ustar00rootroot00000000000000/* * Handle iSNS Device Attribute Registration * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" static int isns_create_default_pgs_for_object(isns_db_t *, isns_object_t *); /* * Create a registration, and set the source name */ static isns_simple_t * __isns_create_registration(isns_source_t *source, isns_object_t *key_obj) { isns_simple_t *reg; reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, source, NULL); if (reg == NULL) return NULL; /* * When sending a registration, you can either specify * the object to be modified in the key attrs, or leave * the key empty. */ if (key_obj == NULL) return reg; /* User gave us a key object. We need to put the key * attributes into the message attrs, and *all* attrs * into the operating attrs. */ if (!isns_object_extract_keys(key_obj, ®->is_message_attrs)) { /* bummer - seems the object is missing some * vital organs. */ isns_warning("%s: object not fully specified, key attrs missing\n", __FUNCTION__); goto failed; } /* * The Message Key identifies the object the DevAttrReg message * acts upon. [...] The key attribute(s) identifying this object * MUST also be included among the Operating Attributes. * * We do not enforce this here, we rely on the caller to get this * right. */ #if 0 if (!isns_object_extract_all(key_obj, ®->is_operating_attrs)) { isns_warning("%s: unable to extract attrs from key objects\n", __FUNCTION__); goto failed; } #endif return reg; failed: isns_simple_free(reg); return NULL; } isns_simple_t * isns_create_registration(isns_client_t *clnt, isns_object_t *key_obj) { return __isns_create_registration(clnt->ic_source, key_obj); } isns_simple_t * isns_create_registration2(isns_client_t *clnt, isns_object_t *key_obj, isns_source_t *source) { return __isns_create_registration(source?: clnt->ic_source, key_obj); } /* * Set the replace flag */ void isns_registration_set_replace(isns_simple_t *reg, int replace) { reg->is_replace = !!replace; } /* * Add an object to the registration */ void isns_registration_add_object(isns_simple_t *reg, isns_object_t *obj) { isns_object_extract_writable(obj, ®->is_operating_attrs); } void isns_registration_add_object_list(isns_simple_t *reg, isns_object_list_t *list) { unsigned int i; for (i = 0; i < list->iol_count; ++i) { isns_object_extract_writable(list->iol_data[i], ®->is_operating_attrs); } } /* * Get the key object given in this message * * It doesn't say anywhere explicitly in the RFC, but * the message key can contain both key and non-key * attributes. For instance, you can search by * Portal Group Index (section 3.4). */ static int isns_registration_get_key(isns_simple_t *reg, isns_db_t *db, isns_object_t **key_obj) { isns_attr_list_t *keys = ®->is_message_attrs; isns_attr_list_t dummy_keys = ISNS_ATTR_LIST_INIT; isns_attr_t *attr; isns_object_t *obj = NULL; const char *eid = NULL; char eidbuf[128]; int status = ISNS_SUCCESS; int obj_must_exist = 0; /* * 5.6.5.1 * If the Message Key is not present, then the DevAttrReg message * implicitly registers a new Network Entity. In this case, * the replace bit SHALL be ignored; a new Network Entity SHALL * be created. * * Note that some clients seem to leave the message key * empty, but hide the entity identifier in the operating * attrs. */ if (keys->ial_count != 0) { attr = keys->ial_data[0]; /* * 5.6.5.1 * If the Message Key does not contain an EID, and no * pre-existing objects match the Message Key, then the * DevAttrReg message SHALL be rejected with a status * code of 3 (Invalid Registration). */ if (keys->ial_count != 1 || attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) obj_must_exist = 1; } else { /* Empty message key. But the client may have hidden * the EID in the operating attrs :-/ */ if (reg->is_operating_attrs.ial_count == 0) goto create_entity; attr = reg->is_operating_attrs.ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ENTITY_IDENTIFIER) goto create_entity; isns_attr_list_append_attr(&dummy_keys, attr); keys = &dummy_keys; } /* If the caller specifies an EID, extract it while * we know what we're doing :-) */ if (attr->ia_tag_id == ISNS_TAG_ENTITY_IDENTIFIER && ISNS_ATTR_IS_STRING(attr)) eid = attr->ia_value.iv_string; /* Look up the object identified by the keys. * We do not scope the lookup, as the client * may want to add nodes to an entity that's * currently empty - and hence not visible to * any DD. */ if (!ISNS_ATTR_IS_NIL(attr)) obj = isns_db_lookup(db, NULL, keys); if (obj == NULL && obj_must_exist) goto err_invalid; if (obj != NULL) { /* * Policy: verify that the client is permitted * to access this object. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow modification of * this object type. */ if (!isns_policy_validate_object_access(reg->is_policy, reg->is_source, obj, reg->is_function)) goto err_unauthorized; found_object: if (reg->is_replace) { isns_object_t *container = NULL; if (!ISNS_IS_ENTITY(obj)) { container = isns_object_get_entity(obj); if (container == NULL) { isns_error("Trying to replace %s (id %u) " "which has no container\n", obj->ie_template->iot_name, obj->ie_index); goto err_invalid; } } isns_debug_state("Replacing %s (id %u)\n", obj->ie_template->iot_name, obj->ie_index); isns_db_remove(db, obj); isns_object_release(obj); /* Purge the deleted objects from the database now */ isns_db_purge(db); /* We need to flush pending SCNs because the * objects may be resurrected from limbo, * and we might be looking at stale data. */ isns_scn_transmit_all(); /* It's an entity. Nuke it and create * a new one. */ if (container == NULL) { isns_source_set_entity(reg->is_source, NULL); goto create_entity; } obj = isns_object_get(container); } goto out; } /* * If the Message Key contains an EID and no pre-existing objects * match the Message Key, then the DevAttrReg message SHALL create a * new Entity with the specified EID and any new object(s) specified * by the Operating Attributes. The replace bit SHALL be ignored. * * Implementer's note: the EID attribute may be empty, in which case * we also create a new entity. */ create_entity: if (!isns_policy_validate_object_creation(reg->is_policy, reg->is_source, &isns_entity_template, keys, NULL, reg->is_function)) goto err_unauthorized; /* * 5.6.5.1 * A registration message that creates a new Network Entity object * MUST contain at least one Portal or one Storage Node. If the * message does not, then it SHALL be considered invalid and result * in a response with Status Code of 3 (Invalid Registration). */ /* FIXME: Implement this check */ /* We try to play nice with lazy clients and attempt to * look up the network entity given the source name. * But we don't do this if a non-NULL EID was given, * because the client may explicitly want to specify more * than one Network Entity. */ if (eid == NULL) { obj = reg->is_source->is_entity; if (obj != NULL) { isns_object_get(obj); goto found_object; } /* The policy may define a default entity name. * If that is the case, use it. */ eid = isns_policy_default_entity(reg->is_policy); if (eid) { obj = isns_db_vlookup(db, &isns_entity_template, ISNS_TAG_ENTITY_IDENTIFIER, eid, 0); if (obj) { reg->is_source->is_entity = isns_object_get(obj); goto found_object; } } } /* * 5.6.5.1 * If the Message Key and Operating Attributes do not contain * an EID attribute, or if the EID attribute has a length of 0, * then a new Network Entity object SHALL be created and the iSNS * server SHALL supply a unique EID value for it. */ if (eid == NULL) eid = isns_db_generate_eid(db, eidbuf, sizeof(eidbuf)); /* * 6.2.2. Entity Protocol * * This attribute is required during initial registration of * the Network Entity. * * Implementer's note: we don't rely on this. Instead, the * Entity Protocol is selected based on the source type. * If the client specifies the protocol, the auto-selected * value is overwritten. */ obj = isns_create_entity_for_source(reg->is_source, eid); if (obj == NULL) goto err_invalid; isns_source_set_entity(reg->is_source, obj); /* * 6.2.6 * If a Registration Period is not requested by the iSNS * client and Entity Status Inquiry (ESI) messages are not * enabled for that client, then the Registration Period * SHALL be set to a non-zero value by the iSNS server. * This implementation-specific value for the Registration * Period SHALL be returned in the registration response to the * iSNS client. The Registration Period may be set to zero, * indicating its non-use, only if ESI messages are enabled for * that Network Entity. * * Implementer's note: we diverge from this in two ways: * - the admin may choose to disable registration timeout, * by setting RegistrationPeriod=0 in the config file * * - When a new entity is created, we always set the * registration interval because we cannot know yet * whether the client will subsequently enable ESI or * not. * * - The control entity (holding policy objects) will * not expire. */ if (isns_config.ic_registration_period && strcasecmp(eid, ISNS_ENTITY_CONTROL)) { isns_object_set_uint32(obj, ISNS_TAG_REGISTRATION_PERIOD, isns_config.ic_registration_period); isns_object_set_uint64(obj, ISNS_TAG_TIMESTAMP, time(NULL)); } /* Insert into database, and set the object's owner */ isns_db_insert(db, obj); reg->is_replace = 0; out: *key_obj = obj; isns_attr_list_destroy(&dummy_keys); return ISNS_SUCCESS; error: if (obj) isns_object_release(obj); isns_attr_list_destroy(&dummy_keys); return status; err_unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto error; err_invalid: status = ISNS_INVALID_REGISTRATION; goto error; } static int isns_registration_get_next_object(isns_db_t *db, struct isns_attr_list_scanner *st, isns_object_list_t *result) { isns_object_t *current; int status, esi = 0; status = isns_attr_list_scanner_next(st); /* We get here if the registration has a trailing PGT */ if (status == ISNS_NO_SUCH_ENTRY) return ISNS_SUCCESS; if (status) return status; /* * Validate the attrlist. * This makes sure the client does not include * duplicate attributes, readonly attributes * such as Registration Timestamp, Index and Next Index, * or privileged data (such as marking a storage node as * control node). */ status = isns_attr_list_validate(&st->attrs, st->policy, ISNS_DEVICE_ATTRIBUTE_REGISTER); if (status) { isns_debug_protocol("invalid attr in message\n"); return status; } /* * 6.3.4. Entity Status Inquiry Interval * * If the iSNS server is unable to support ESI messages * or the ESI Interval requested, it SHALL [...] reject * the ESI request by returning an "ESI Not Available" * Status Code [...] * * Implementer's note: In section 5.7.5.1, the RFC talks * about modifying the requested ESI interval; so it seems * it's okay to be liberal about the ESI intervals we accept, * and update them quietly. */ if (isns_attr_list_contains(&st->attrs, ISNS_TAG_ESI_PORT)) { if (!isns_esi_enabled) { isns_debug_esi("Refusing to accept portal " "registration with ESI port\n"); return ISNS_ESI_NOT_AVAILABLE; } esi = 1; } /* * Override any registration period specified by the client. */ if (isns_attr_list_contains(&st->attrs, ISNS_TAG_REGISTRATION_PERIOD)) { isns_value_t value = ISNS_VALUE_INIT(uint32, isns_config.ic_registration_period); isns_attr_list_update_value(&st->attrs, ISNS_TAG_REGISTRATION_PERIOD, NULL, &value); } if (st->tmpl == &isns_entity_template) { /* * 5.6.5.1. * A maximum of one Network Entity object can be * created or updated with a single DevAttrReg * message. Consequently, the Operating Attributes * MUST NOT contain more than one Network Entity * object. */ if (st->entities++) { isns_debug_protocol("More than one entity in DevAttrReg msg\n"); return ISNS_INVALID_REGISTRATION; } /* This should be the key object. * The EID specified by by the client may be * empty, so don't overwrite the value we * assigned with something else. */ if (!isns_object_match(st->key_obj, &st->keys)) { isns_debug_protocol("Entity mismatch in message vs. operating attrs\n"); return ISNS_INVALID_REGISTRATION; } current = isns_object_get(st->key_obj); } else if (st->tmpl == &isns_dd_template || st->tmpl == &isns_ddset_template) { isns_debug_protocol("DevAttrReg of type %s not allowed\n", st->tmpl->iot_name); return ISNS_INVALID_REGISTRATION; } else { /* This will also catch objects in limbo. */ current = isns_db_lookup(db, st->tmpl, &st->keys); } if (current != NULL) { /* * If the replace bit is not set, then the message updates * the attributes of the object identified by the Message Key * and its subordinate objects. Existing object containment * relationships MUST NOT be changed. For existing objects, * key attributes MUST NOT be modified, but new subordinate * objects MAY be added. */ /* * [...] * If the Node identified by the Source Attribute is * not a Control Node, then the objects in the operating * attributes MUST be members of the same Network Entity * as the Source Node. */ if (!isns_policy_validate_object_update(st->policy, st->source, current, &st->attrs, ISNS_DEVICE_ATTRIBUTE_REGISTER)) { isns_object_release(current); return ISNS_SOURCE_UNAUTHORIZED; } /* We shouldn't allow messages affecting one Entity * to modify objects owned by a different Entity. * * However, there may be orphan objects (created * while populating discovery domains). These will * not be associated with any Network Entity, so * they're up for grabs. */ if (st->key_obj == current || st->key_obj == current->ie_container) { /* All is well. The current object is the * key object itself, or a direct descendant of the * key object. */ /* FIXME: with FC we can get deeper nesting; * this needs work. */ } else if (!isns_object_is_valid_container(st->key_obj, st->tmpl)) { isns_error("Client attempts to add %s object to a %s - tsk tsk.\n", st->tmpl->iot_name, st->key_obj->ie_template->iot_name); goto invalid_registration; } else if (current->ie_container) { /* We shouldn't get here in authenticated mode, * but in insecure mode we still may. */ isns_error("Client attempts to move %s %u to a different %s\n", current->ie_template->iot_name, current->ie_index, st->key_obj->ie_template->iot_name); goto invalid_registration; } } else { if (!isns_object_is_valid_container(st->key_obj, st->tmpl)) { isns_error("Client attempts to add %s object to a %s - tsk tsk.\n", st->tmpl->iot_name, st->key_obj->ie_template->iot_name); goto invalid_registration; } if (!isns_policy_validate_object_creation(st->policy, st->source, st->tmpl, &st->keys, &st->attrs, ISNS_DEVICE_ATTRIBUTE_REGISTER)) { return ISNS_SOURCE_UNAUTHORIZED; } current = isns_create_object(st->tmpl, &st->keys, isns_object_get_entity(st->key_obj)); /* We do not insert the new object into the database yet. * That happens after we're done with parsing *all* * objects. */ } if (!isns_object_set_attrlist(current, &st->attrs)) { isns_debug_state("Error updating object's attrlist\n"); isns_object_release(current); return ISNS_INTERNAL_ERROR; } /* If the client specifies an ESI port, make sure the * ESI interval is set and within bounds. */ if (esi) { uint32_t esi_interval; if (!isns_object_get_uint32(current, ISNS_TAG_ESI_INTERVAL, &esi_interval)) { esi_interval = isns_config.ic_esi_min_interval; } else if (esi_interval < isns_config.ic_esi_min_interval) { esi_interval = isns_config.ic_esi_min_interval; } else if (esi_interval > isns_config.ic_esi_max_interval) { esi_interval = isns_config.ic_esi_max_interval; } else { esi_interval = 0; } if (esi_interval) isns_object_set_uint32(current, ISNS_TAG_ESI_INTERVAL, esi_interval); } /* Append it to the result list. * We do not return the key object, otherwise * we end up putting it into the response twice. */ if (current != st->key_obj) isns_object_list_append(result, current); /* * When a Portal is registered, the Portal attributes MAY immediately be * followed by a PGT attribute. * [...] * When an iSCSI Storage Node is registered, the Storage Node attributes * MAY immediately be followed by a PGT attribute. */ if (st->tmpl == &isns_portal_template || st->tmpl == &isns_iscsi_node_template) { st->pgt_next_attr = ISNS_TAG_PG_TAG; st->pgt_base_object = current; } else if (st->tmpl != &isns_iscsi_pg_template) { st->pgt_next_attr = 0; st->pgt_base_object = NULL; } isns_object_release(current); return ISNS_SUCCESS; invalid_registration: if (current) isns_object_release(current); return ISNS_INVALID_REGISTRATION; } /* * Extract the list of objects to be registered from * the list of operating attributes. */ static int isns_registration_get_objects(isns_simple_t *reg, isns_db_t *db, isns_object_t *key_obj, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, key_obj, ®->is_operating_attrs); state.source = reg->is_source; state.policy = reg->is_policy; /* * 5.6.4. * The ordering of Operating Attributes in the message is * important for determining the relationships among objects * and their ownership of non-key attributes. iSNS protocol * messages that violate these ordering rules SHALL be rejected * with the Status Code of 2 (Message Format Error). */ /* FIXME: Implement this check */ while (state.pos < state.orig_attrs.ial_count) { status = isns_registration_get_next_object(db, &state, result); if (status) break; } isns_attr_list_scanner_destroy(&state); return status; } /* * 5.6.5.1 * New PG objects are registered when an associated Portal or * iSCSI Node object is registered. An explicit PG object * registration MAY follow a Portal or iSCSI Node object * registration in a DevAttrReg message. * [...] * If the PGT value is not included in the Storage Node or * Portal object registration, and if a PGT value was not * previously registered for the relationship, then the PGT for * the corresponding PG object SHALL be registered with a value * of 0x00000001. */ static int isns_create_registration_pgs(isns_db_t *db, const isns_object_list_t *list) { unsigned int i, num_created = 0; for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; if (ISNS_IS_ISCSI_NODE(obj) || ISNS_IS_PORTAL(obj)) num_created += isns_create_default_pgs_for_object(db, obj); } return num_created; } static int isns_create_default_pgs_for_object(isns_db_t *db, isns_object_t *this) { isns_object_template_t *match_tmpl; isns_object_t *entity; unsigned int i, num_created = 0; if (ISNS_IS_ISCSI_NODE(this)) match_tmpl = &isns_portal_template; else match_tmpl = &isns_iscsi_node_template; entity = isns_object_get_entity(this); for (i = 0; i < entity->ie_children.iol_count; ++i) { isns_object_t *that = entity->ie_children.iol_data[i], *pg; if (that->ie_template != match_tmpl) continue; /* Create the portal group if it does not * exist. * Note: we do not return these implicitly * created portal groups - that's a matter * of sheer laziness. We would have to * splice these into the list in the * appropriate location, and I guess it's * not really worth the hassle. */ if (ISNS_IS_ISCSI_NODE(this)) pg = isns_create_default_portal_group(db, that, this); else pg = isns_create_default_portal_group(db, this, that); /* There already is a PG linking these two * objects. */ if (pg == NULL) continue; isns_db_insert(db, pg); isns_debug_message("--Created default PG:--\n"); isns_object_print(pg, isns_debug_message); isns_object_release(pg); num_created++; } return num_created; } /* * Commit all changes to the DB */ static int isns_commit_registration(isns_db_t *db, isns_object_t *key_obj, isns_object_list_t *list) { unsigned int i; /* * If there are any Portal Groups in this registration, build * the relationship handle: * * 3.4 * A new PG object can only be registered by referencing * its associated iSCSI Storage Node or Portal object. * A pre-existing PG object can be modified or queried * by using its Portal Group Index as message key, or * by referencing its associated iSCSI Storage Node or * Portal object. * * Implementation note: isns_db_create_pg_relation * checks whether the referenced node and portal exist, * and belong to the same entity as the PG. If this is * not the case, NULL is returned, and no relation is * defined. */ for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_template_t *tmpl; tmpl = obj->ie_template; if (tmpl->iot_build_relation && !obj->ie_relation && !tmpl->iot_build_relation(db, obj, list)) { isns_debug_protocol("Unable to build relation for new %s\n", tmpl->iot_name); return ISNS_INVALID_REGISTRATION; } } for (i = 0; i < list->iol_count; ++i) { isns_object_t *obj = list->iol_data[i]; isns_object_template_t *tmpl; tmpl = obj->ie_template; if (key_obj != obj && !obj->ie_container) { if (!isns_object_attach(obj, key_obj)) { /* This should not fail any longer */ isns_debug_protocol("Unable to attach %s %u to %s\n", tmpl->iot_name, obj->ie_index, key_obj->ie_template->iot_name); return ISNS_INVALID_REGISTRATION; } } if (obj->ie_state != ISNS_OBJECT_STATE_MATURE) isns_db_insert(db, obj); } return ISNS_SUCCESS; } /* * Process a registration */ int isns_process_registration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_object_list_t objects = ISNS_OBJECT_LIST_INIT; isns_simple_t *reply = NULL; isns_object_t *key_obj = NULL; isns_db_t *db = srv->is_db; int status; unsigned int i; /* * 5.6.1 * For messages that change the contents of the iSNS database, * the iSNS server MUST verify that the Source Attribute * identifies either a Control Node or a Storage Node that is * a part of the Network Entity containing the added, deleted, * or modified objects. * * This check happens in isns_registration_get_key by calling * isns_policy_validate_object_access. */ /* Get the key object (usually a Network Entity) */ status = isns_registration_get_key(call, db, &key_obj); if (status) goto done; /* Get the objects to register */ status = isns_registration_get_objects(call, db, key_obj, &objects); if (status != ISNS_SUCCESS) goto done; /* We parsed the request alright; all semantic checks passed. * Now insert the modified/new objects. * We do this in two passes, by first committing all nodes and * portals, and then committing the portal groups. */ status = isns_commit_registration(db, key_obj, &objects); if (status != ISNS_SUCCESS) goto done; /* The client may have registered a bunch of storage nodes, * and created an entity in the process. However, there's the * odd chance that the source node name it used was not * registered. However, we need to be able to later find * the entity it registered based on its source name. * So we implicitly create a dummy storage node with the given * source name and attach it. */ #if 1 if (ISNS_IS_ENTITY(key_obj) && !isns_source_set_node(call->is_source, db)) { isns_attr_list_t attrs = ISNS_ATTR_LIST_INIT; isns_source_t *source = call->is_source; isns_object_t *obj; isns_attr_list_append_attr(&attrs, isns_source_attr(source)); isns_attr_list_append_uint32(&attrs, ISNS_TAG_ISCSI_NODE_TYPE, 0); obj = isns_create_object(&isns_iscsi_node_template, &attrs, key_obj); if (obj) { isns_db_insert(db, obj); } else { isns_warning("Unable to create dummy storage node " "for source %s\n", isns_source_name(source)); } isns_attr_list_destroy(&attrs); } #endif /* * 5.6.5.1 * New PG objects are registered when an associated Portal or * iSCSI Node object is registered. An explicit PG object * registration MAY follow a Portal or iSCSI Node object * registration in a DevAttrReg message. * [...] * If the PGT value is not included in the Storage Node or * Portal object registration, and if a PGT value was not * previously registered for the relationship, then the PGT for * the corresponding PG object SHALL be registered with a value * of 0x00000001. */ isns_create_registration_pgs(db, &objects); /* Success: create a new registration message, and * send it in our reply. */ reply = __isns_create_registration(srv->is_source, key_obj); if (reply == NULL) { status = ISNS_INTERNAL_ERROR; goto done; } /* If the key object was modified (or created) * include it in the response. * We really ought to restrict ourselves to the * key attrs plus those that were modified by this * registration. But right now have no way of * finding out. */ if (key_obj->ie_flags & ISNS_OBJECT_DIRTY) isns_registration_add_object(reply, key_obj); for (i = 0; i < objects.iol_count; ++i) { isns_registration_add_object(reply, objects.iol_data[i]); } done: isns_object_list_destroy(&objects); isns_object_release(key_obj); *result = reply; return status; } /* * Extract the list of objects from the DevAttrReg response */ int isns_registration_response_get_objects(isns_simple_t *reg, isns_object_list_t *result) { return isns_simple_response_get_objects(reg, result); } open-iscsi-2.0.873/utils/open-isns/relation.c000066400000000000000000000147361175631155400210230ustar00rootroot00000000000000/* * iSNS object relationships * * Relations are used to express a connection between two * objects. Currently, two relationship types are implemented: * * - portal group: this relates a storage node and a portal * - visibility: this relates a nodes nodes that share a * common discovery domain. * * Relation objects are nice for portals groups, but kind of * awkward for DDs. A better way of expressing DD membership * (which also allows for a fast visibility check) could be * to store a [bit] vector of DD IDs in each storage node. * A visibility check would amount to just doing the bitwise * AND of two vectors, and checking for NULL. The only thing * to take care of would be to make sure a DD object takes a * reference on its members (this is necessary so that objects * maintain their ID/name associations even when removed from * the database). * * Aug 22 2007 - changed DD code to use bit vectors. A lot * of code in this file is now obsolete. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include "isns.h" #include "objects.h" #include "util.h" #include "db.h" struct isns_relation_soup { /* For now, use one plain list. For better * scalability, we'll need a hash table or * something similar later. */ isns_relation_list_t irs_data; }; static void isns_relation_list_append(isns_relation_list_t *, isns_relation_t *); static int isns_relation_list_remove(isns_relation_list_t *, isns_relation_t *); isns_relation_soup_t * isns_relation_soup_alloc(void) { return isns_calloc(1, sizeof(isns_relation_soup_t)); } void isns_relation_add(isns_relation_soup_t *soup, isns_relation_t *rp) { isns_relation_list_append(&soup->irs_data, rp); } isns_relation_t * isns_relation_find_edge(isns_relation_soup_t *soup, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type) { isns_relation_list_t *list = &soup->irs_data; unsigned int i; for (i = 0; i < list->irl_count; ++i) { isns_relation_t *rp = list->irl_data[i]; if (rp->ir_type != relation_type) continue; if (rp->ir_subordinate[0].obj == left && rp->ir_subordinate[1].obj == right) return rp; if (rp->ir_subordinate[0].obj == right && rp->ir_subordinate[1].obj == left) return rp; } return NULL; } void isns_relation_get_edge_objects(isns_relation_soup_t *soup, const isns_object_t *left, unsigned int relation_type, isns_object_list_t *result) { isns_relation_list_t *list = &soup->irs_data; unsigned int i; for (i = 0; i < list->irl_count; ++i) { isns_relation_t *rp = list->irl_data[i]; if (rp->ir_type != relation_type) continue; if (rp->ir_object == NULL) continue; if (rp->ir_subordinate[0].obj == left || rp->ir_subordinate[1].obj == left) { isns_object_list_append(result, rp->ir_object); } } } void isns_relation_halfspace(isns_relation_soup_t *soup, const isns_object_t *left, unsigned int relation_type, isns_object_list_t *result) { isns_relation_list_t *list = &soup->irs_data; unsigned int i; for (i = 0; i < list->irl_count; ++i) { isns_relation_t *rp = list->irl_data[i]; if (rp->ir_type != relation_type) continue; if (rp->ir_subordinate[0].obj == left) { isns_object_list_append(result, rp->ir_subordinate[1].obj); } else if (rp->ir_subordinate[1].obj == left) { isns_object_list_append(result, rp->ir_subordinate[0].obj); } } } int isns_relation_exists(isns_relation_soup_t *soup, const isns_object_t *relating_object, const isns_object_t *left, const isns_object_t *right, unsigned int relation_type) { isns_relation_list_t *list = &soup->irs_data; unsigned int i; for (i = 0; i < list->irl_count; ++i) { isns_relation_t *rp = list->irl_data[i]; if (rp->ir_type != relation_type) continue; if (rp->ir_object != relating_object) continue; if (rp->ir_subordinate[0].obj == left && rp->ir_subordinate[1].obj == right) return 1; if (rp->ir_subordinate[0].obj == right && rp->ir_subordinate[1].obj == left) return 1; } return 0; } isns_object_t * isns_relation_get_other(const isns_relation_t *rp, const isns_object_t *this) { if (rp->ir_subordinate[0].obj == this) return rp->ir_subordinate[1].obj; if (rp->ir_subordinate[1].obj == this) return rp->ir_subordinate[0].obj; return NULL; } void isns_relation_remove(isns_relation_soup_t *soup, isns_relation_t *rp) { isns_object_release(rp->ir_object); rp->ir_object = NULL; isns_relation_list_remove(&soup->irs_data, rp); } isns_relation_t * isns_create_relation(isns_object_t *relating_object, unsigned int relation_type, isns_object_t *subordinate_object1, isns_object_t *subordinate_object2) { isns_relation_t *rp; rp = isns_calloc(1, sizeof(*rp)); rp->ir_type = relation_type; rp->ir_users = 1; rp->ir_object = isns_object_get(relating_object); isns_object_reference_set(&rp->ir_subordinate[0], subordinate_object1); isns_object_reference_set(&rp->ir_subordinate[1], subordinate_object2); #if 0 if (relating_object) { relating_object->ie_relation = rp; rp->ir_users++; } #endif return rp; } void isns_relation_sever(isns_relation_t *rp) { isns_object_release(rp->ir_object); rp->ir_object = NULL; isns_object_reference_drop(&rp->ir_subordinate[0]); isns_object_reference_drop(&rp->ir_subordinate[1]); } void isns_relation_release(isns_relation_t *rp) { if (--(rp->ir_users)) return; isns_relation_sever(rp); isns_free(rp); } /* * Check whether the relation references two dead/limbo objects. * This is used for dead PG removal. */ int isns_relation_is_dead(const isns_relation_t *rel) { isns_object_t *left, *right; left = rel->ir_subordinate[0].obj; right = rel->ir_subordinate[1].obj; if ((left->ie_flags & ISNS_OBJECT_DEAD) && (right->ie_flags & ISNS_OBJECT_DEAD)) return 1; return 0; } void isns_relation_list_append(isns_relation_list_t *list, isns_relation_t *rp) { if ((list->irl_count % 128) == 0) { list->irl_data = isns_realloc(list->irl_data, (list->irl_count + 128) * sizeof(void *)); if (list->irl_data == NULL) isns_fatal("out of memory!\n"); } list->irl_data[list->irl_count++] = rp; rp->ir_users++; } int isns_relation_list_remove(isns_relation_list_t *list, isns_relation_t *rp) { unsigned int i, count = list->irl_count; for (i = 0; i < count; ++i) { if (list->irl_data[i] != rp) continue; if (i < count - 1) list->irl_data[i] = list->irl_data[count-1]; isns_relation_release(rp); list->irl_count -= 1; return 1; } return 0; } open-iscsi-2.0.873/utils/open-isns/scn.c000066400000000000000000000562701175631155400177700ustar00rootroot00000000000000/* * Handle SCN registration/deregistration/events * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" typedef struct isns_scn isns_scn_t; typedef struct isns_scn_funnel isns_scn_funnel_t; struct isns_scn { isns_scn_t * scn_next; char * scn_name; isns_object_t * scn_entity; isns_object_t * scn_owner; isns_attr_t * scn_attr; isns_simple_t * scn_message; isns_simple_t * scn_pending; unsigned int scn_retries; time_t scn_timeout; uint16_t scn_xid; time_t scn_last_update; isns_scn_funnel_t * scn_current_funnel; isns_scn_funnel_t * scn_funnels; }; struct isns_scn_funnel { isns_scn_funnel_t * scn_next; isns_portal_info_t scn_portal; isns_socket_t * scn_socket; unsigned int scn_bad; }; static isns_server_t * isns_scn_server = NULL; static isns_scn_t * isns_scn_list; static isns_scn_t * isns_scn_create_scn(isns_object_t *, uint32_t, isns_db_t *); static void isns_scn_delete_scn(isns_object_t *); static isns_scn_t * isns_scn_setup(isns_scn_t *, isns_object_t *); static void isns_scn_callback(const isns_db_event_t *, void *); static void isns_scn_free(isns_scn_t *); /* * Initialize SCN machinery */ void isns_scn_init(isns_server_t *srv) { isns_db_t *db = srv->is_db; isns_object_list_t nodes = ISNS_OBJECT_LIST_INIT; isns_scn_t **tail; unsigned int i; isns_scn_server = srv; isns_register_callback(isns_scn_callback, db); /* Recover SCN state. */ isns_db_gang_lookup(db, &isns_iscsi_node_template, NULL, &nodes); #ifdef notyet isns_db_gang_lookup(db, &isns_fc_node_template, NULL, &nodes); #endif tail = &isns_scn_list; for (i = 0; i < nodes.iol_count; ++i) { isns_object_t *node = nodes.iol_data[i]; isns_scn_t *scn; if (!node->ie_scn_mask) continue; isns_debug_state("Recovering SCN state for %s %u\n", node->ie_template->iot_name, node->ie_index); scn = isns_scn_setup(NULL, node); if (scn) { *tail = scn; tail = &scn->scn_next; } } } /* * Support for SCNRegister calls */ isns_simple_t * isns_create_scn_registration2(isns_client_t *clnt, unsigned int bitmap, isns_source_t *source) { isns_simple_t *call; if (!source) source = clnt->ic_source; call = isns_simple_create(ISNS_SCN_REGISTER, source, NULL); if (call) { isns_attr_list_append_attr(&call->is_message_attrs, isns_source_attr(source)); isns_attr_list_append_uint32(&call->is_operating_attrs, ISNS_TAG_ISCSI_SCN_BITMAP, bitmap); } return call; } isns_simple_t * isns_create_scn_registration(isns_client_t *clnt, unsigned int bitmap) { return isns_create_scn_registration2(clnt, bitmap, clnt->ic_source); } /* * Create an SCN */ isns_simple_t * isns_create_scn(isns_source_t *source, isns_attr_t *nodeattr, isns_attr_t *tsattr) { isns_simple_t *call; call = isns_simple_create(ISNS_STATE_CHANGE_NOTIFICATION, source, NULL); if (call && nodeattr) isns_attr_list_append_attr(&call->is_message_attrs, nodeattr); if (call && tsattr) isns_attr_list_append_attr(&call->is_message_attrs, tsattr); return call; } static void isns_scn_add_event(isns_simple_t *call, uint32_t scn_bits, const isns_object_t *obj, const isns_object_t *dd) { isns_attr_list_t *attrs = &call->is_message_attrs; isns_attr_list_append_uint32(attrs, ISNS_TAG_ISCSI_SCN_BITMAP, scn_bits); isns_object_extract_keys(obj, attrs); if (dd) isns_object_extract_keys(dd, attrs); } /* * Process a SCN registration */ int isns_process_scn_register(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_attr_list_t *keys = &call->is_message_attrs; isns_attr_list_t *attrs = &call->is_operating_attrs; isns_db_t *db = srv->is_db; isns_attr_t *attr; isns_object_t *node = NULL; uint32_t scn_bitmap; isns_scn_t *scn; int status = ISNS_SUCCESS; /* * 5.6.5.5 * The SCNReg request PDU Payload contains a Source Attribute, a Message * Key Attribute, and an Operating Attribute. Valid Message Key * Attributes for a SCNReg are shown below: * * Valid Message Key Attributes for SCNReg * --------------------------------------- * iSCSI Name * FC Port Name WWPN */ if (keys->ial_count != 1 || attrs->ial_count != 1) return ISNS_SCN_REGISTRATION_REJECTED; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_NAME && attr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) return ISNS_SCN_REGISTRATION_REJECTED; /* Look up the storage node for this source. If it does * not exist, reject the message. */ node = isns_db_lookup(db, NULL, keys); if (node == NULL) return ISNS_SOURCE_UNKNOWN; /* * Policy: verify that the client is permitted * to access this entity. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow monitoring of * this object type. */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, node, call->is_function)) goto unauthorized; /* * 5.6.5.5 * The SCN Bitmap is the only operating attribute of this message * [...] * Control Nodes MAY conduct registrations for management SCNs; * iSNS clients that are not supporting Control Nodes MUST NOT * conduct registrations for management SCNs. * * Implementer's note: for iFCP sources, we should check for * ISNS_TAG_IFCP_SCN_BITMAP. */ attr = attrs->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_SCN_BITMAP || !ISNS_ATTR_IS_UINT32(attr)) goto rejected; scn_bitmap = attr->ia_value.iv_uint32; if (!isns_policy_validate_scn_bitmap(call->is_policy, scn_bitmap)) goto unauthorized; /* * 5.6.5.5 * If no SCN Port fields of any Portals of the Storage Node are * registered to receive SCN messages, then the SCNReg message SHALL * be rejected with Status Code 17 (SCN Registration Rejected). */ if (!(scn = isns_scn_create_scn(node, scn_bitmap, db))) goto rejected; *result = isns_simple_create(ISNS_SCN_REGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: if (node) isns_object_release(node); return status; rejected: status = ISNS_SCN_REGISTRATION_REJECTED; goto out; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Process a SCNDereg message */ int isns_process_scn_deregistration(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result) { isns_attr_list_t *keys = &call->is_message_attrs; isns_db_t *db = srv->is_db; isns_attr_t *attr; isns_object_t *node = NULL; int status = ISNS_SUCCESS; /* * 5.6.5.6 * The SCNDereg request message PDU Payload contains a Source Attribute * and Message Key Attribute(s). Valid Message Key Attributes for a * SCNDereg are shown below: * * Valid Message Key Attributes for SCNDereg * ----------------------------------------- * iSCSI Name * FC Port Name WWPN * * There are no Operating Attributes in the SCNDereg message. */ if (keys->ial_count != 1) return ISNS_SCN_REGISTRATION_REJECTED; attr = keys->ial_data[0]; if (attr->ia_tag_id != ISNS_TAG_ISCSI_NAME && attr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) return ISNS_SCN_REGISTRATION_REJECTED; /* Look up the storage node for this source. If it does * not exist, reject the message. */ node = isns_db_lookup(db, NULL, keys); if (node == NULL) return ISNS_SUCCESS; /* * Policy: verify that the client is permitted * to access this entity. * * This includes * - the client node must be the object owner, * or a control node. * - the policy must allow monitoring of * this object type. */ if (!isns_policy_validate_object_access(call->is_policy, call->is_source, node, call->is_function)) goto unauthorized; isns_object_set_scn_mask(node, 0); isns_scn_delete_scn(node); *result = isns_simple_create(ISNS_SCN_DEREGISTER, srv->is_source, NULL); status = ISNS_SUCCESS; out: if (node) isns_object_release(node); return status; unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto out; } /* * Set up the SCN object. */ static isns_scn_t * isns_scn_setup(isns_scn_t *scn, isns_object_t *node) { isns_object_list_t portals = ISNS_OBJECT_LIST_INIT; isns_object_t *entity; unsigned int i; entity = isns_object_get_entity(node); if (entity == NULL || !isns_object_find_descendants(entity, &isns_portal_template, NULL, &portals)) return NULL; for (i = 0; i < portals.iol_count; ++i) { isns_object_t *portal = portals.iol_data[i]; isns_portal_info_t info; isns_scn_funnel_t *funnel; /* Extract address and SCN port from portal */ if (!isns_portal_from_object(&info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_SCN_PORT, portal)) continue; /* We know where to send our notifications! */ if (scn == NULL) { isns_attr_t *attr; if (!isns_object_get_attr(node, ISNS_TAG_ISCSI_NAME, &attr) && !isns_object_get_attr(node, ISNS_TAG_FC_PORT_NAME_WWPN, &attr)) { isns_error("Attempt to set up SCN for strange node type\n"); return NULL; } scn = isns_calloc(1, sizeof(*scn)); scn->scn_entity = isns_object_get(entity); scn->scn_owner = isns_object_get(node); scn->scn_attr = isns_attr_get(attr); scn->scn_name = isns_strdup(attr->ia_value.iv_string); } funnel = isns_calloc(1, sizeof(*funnel)); funnel->scn_portal = info; funnel->scn_next = scn->scn_funnels; scn->scn_funnels = funnel; } isns_object_list_destroy(&portals); return scn; } /* * See if an SCN object exists for the given target; * if it doesn't, then create one. */ static isns_scn_t * isns_scn_create_scn(isns_object_t *node, uint32_t bitmap, isns_db_t *db) { isns_scn_t *scn; for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_owner == node) goto done; } /* Not found - create it */ scn = isns_scn_setup(NULL, node); if (scn == NULL) return NULL; scn->scn_next = isns_scn_list; isns_scn_list = scn; done: /* We're all set - update the bitmap */ isns_object_set_scn_mask(node, bitmap); return scn; } static void isns_scn_delete_scn(isns_object_t *node) { isns_scn_t *scn, **pos; pos = &isns_scn_list; while ((scn = *pos) != NULL) { if (scn->scn_owner == node) { isns_debug_scn("Deregistering SCN for node %u\n", node->ie_index); *pos = scn->scn_next; isns_scn_free(scn); return; } pos = &scn->scn_next; } } static void isns_scn_release_funnels(isns_scn_t *scn) { isns_scn_funnel_t *funnel; while ((funnel = scn->scn_funnels) != NULL) { scn->scn_funnels = funnel->scn_next; if (funnel->scn_socket) isns_socket_free(funnel->scn_socket); isns_free(funnel); } } static void isns_scn_free(isns_scn_t *scn) { isns_scn_release_funnels(scn); isns_object_release(scn->scn_owner); isns_object_release(scn->scn_entity); isns_attr_release(scn->scn_attr); isns_free(scn->scn_name); isns_free(scn); } /* * Check whether we should send an event to the target */ static inline int isns_scn_match(isns_scn_t *scn, uint32_t event, const isns_object_t *node, uint32_t node_type) { if (event == 0) return 0; if (node->ie_scn_mask & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK) return event | ISNS_SCN_MANAGEMENT_REGISTRATION_MASK; #if 0 /* This is a normal (non-control) node. Check whether the object * is in the scope of this client. */ if (!isns_object_in_scope(scn->scn_owner, node)) return 0; #endif if (node->ie_scn_mask & ISNS_SCN_TARGET_AND_SELF_ONLY_MASK) { if (node != scn->scn_owner && !(node_type & ISNS_ISCSI_TARGET_MASK)) return 0; } if (node->ie_scn_mask & ISNS_SCN_INITIATOR_AND_SELF_ONLY_MASK) { if (node != scn->scn_owner && !(node_type & ISNS_ISCSI_INITIATOR_MASK)) return 0; } return event; } /* * Helper to create time stamp attr */ static isns_attr_t * isns_create_timestamp_attr(void) { isns_value_t value = ISNS_VALUE_INIT(uint64, time(NULL)); return isns_attr_alloc(ISNS_TAG_TIMESTAMP, NULL, &value); } /* * This function is invoked whenever someone changes the * database. * * SCNs are another area where the RFC is fabulously wishy washy. * It is not entirely clear when DD/DDS information should be * included in a management SCN - one *reasonable* interpretation * would be that this happens for DDReg/DDDereg/DDSReg/DDSDereg * events only. But some sections make it sound as if DD * information is included for all management SCNs. */ void isns_scn_callback(const isns_db_event_t *ev, void *ptr) { isns_object_t *obj = ev->ie_object; isns_scn_t *scn, **pos; isns_attr_t *timestamp; uint32_t node_type; /* Never send out notifications for policy objects and the like. */ if (obj->ie_flags & ISNS_OBJECT_PRIVATE) return; /* When an entity is nuked, remove all SCNs to nodes * that registered from there */ if (ISNS_IS_ENTITY(obj) && (ev->ie_bits & ISNS_SCN_OBJECT_REMOVED_MASK)) { pos = &isns_scn_list; while ((scn = *pos) != NULL) { if (scn->scn_entity != obj) { pos = &scn->scn_next; continue; } isns_debug_scn("Deleting SCN registration for %s\n", scn->scn_name); *pos = scn->scn_next; isns_scn_free(scn); } return; } /* For now we handle iSCSI nodes only. Maybe later we'll * do iFC nodes as well. */ if (!ISNS_IS_ISCSI_NODE(obj)) return; if (!isns_object_get_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, &node_type)) return; if (ev->ie_recipient) { isns_object_t *dst = ev->ie_recipient; isns_debug_scn("SCN unicast <%s %u, %s> -> %s %u\n", obj->ie_template->iot_name, obj->ie_index, isns_event_string(ev->ie_bits), dst->ie_template->iot_name, dst->ie_index); } else { isns_debug_scn("SCN multicast <%s %u, %s>\n", obj->ie_template->iot_name, obj->ie_index, isns_event_string(ev->ie_bits)); } timestamp = isns_create_timestamp_attr(); pos = &isns_scn_list; while ((scn = *pos) != NULL) { unsigned int scn_bits, management; isns_object_t *recipient, *dd = NULL; isns_simple_t *call; recipient = scn->scn_owner; /* Check if the node has gone away completely. */ if (recipient->ie_scn_mask == 0) { *pos = scn->scn_next; isns_scn_free(scn); continue; } if (recipient->ie_container == NULL) { isns_warning("Internal bug - SCN recipient without container\n"); /* Clear the bitmask and loop over - this will remove it */ recipient->ie_scn_mask = 0; continue; } /* See if portals were added/removed. * This does not catch updates that modified *just* * the SCN port */ if (recipient->ie_container->ie_mtime != scn->scn_last_update) { /* Rebuild the list of SCN portals */ isns_scn_release_funnels(scn); scn->scn_last_update = 0; } pos = &scn->scn_next; /* Check for unicast events (triggered for DD addition/removal). * For unicast events, we do not mask the SCN bits, so that * clients who have registered for non-management events * will see the membership events for their DDs nevertheless. */ if (ev->ie_recipient == NULL) { scn_bits = ev->ie_bits & recipient->ie_scn_mask; if (scn_bits == 0) continue; /* Management SCNs should not be delivered to nodes * that have not registered for them. */ if ((ev->ie_bits & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK) && !(recipient->ie_scn_mask & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK)) continue; } else if (recipient == ev->ie_recipient) { scn_bits = ev->ie_bits; } else { /* No match, skip this recipient */ continue; } if (scn->scn_last_update == 0) { scn->scn_last_update = recipient->ie_container->ie_mtime; isns_scn_setup(scn, recipient); } /* We check for SCN capable portals when processing * the SCN registration. But the portals may go away * in the meantime. */ if (scn->scn_funnels == NULL) continue; /* Check SCN bitmask. This will modify the event bits. */ scn_bits = isns_scn_match(scn, scn_bits, obj, node_type); if (scn_bits == 0) continue; management = !!(scn_bits & ISNS_SCN_MANAGEMENT_REGISTRATION_MASK); /* * 2.2.3 * A regular SCN registration indicates that the * Discovery Domain Service SHALL be used to control the * distribution of SCN messages. Receipt of regular * SCNs is limited to the discovery domains in which * the SCN-triggering event takes place. Regular SCNs * do not contain information about discovery domains. * * Implementer's note: We override check for unicast events. * The reason is that DDDereg will sever the * relationship, and we would never send an SCN for that * event. */ if (!management && !ev->ie_recipient) { if (!isns_object_test_visibility(obj, recipient)) continue; } isns_debug_scn("preparing to send SCN to %s\n", scn->scn_name); if ((call = scn->scn_message) == NULL) { call = isns_create_scn(isns_scn_server->is_source, scn->scn_attr, timestamp); if (call == NULL) continue; scn->scn_message = call; } /* * If the SCN is a Management SCN, then the SCN message * SHALL also list the DD_ID and/or DDS_ID of the * Discovery Domains and Discovery Domain Sets (if any) * that caused the change in state for that Storage Node. * These additional attributes (i.e., DD_ID and/or DDS_ID) * shall immediately follow the iSCSI Name or FC Port * Name and precede the next SCN bitmap for the next * notification message (if any). */ if (management && ev->ie_trigger) dd = ev->ie_trigger; isns_scn_add_event(call, scn_bits, obj, dd); } isns_attr_release(timestamp); } /* * Obtain a socket to talk to this guy. * Not entirely trivial - this can be both an established * (incoming) connection, or one that we should establish. * * Note, we do not support transmission on the incoming * connection yet. */ static isns_socket_t * isns_scn_get_socket(isns_scn_t *scn) { isns_scn_funnel_t *f, *best = NULL; isns_socket_t *sock; unsigned int worst = 0, loops = 0, nfunnels; /* Keep it simple for now */ if ((f = scn->scn_current_funnel) != NULL && f->scn_socket) { if (!f->scn_bad) return f->scn_socket; /* Oops, we've seen timeouts on this socket. */ isns_socket_free(f->scn_socket); f->scn_socket = NULL; } again: nfunnels = 0; for (f = scn->scn_funnels; f; f = f->scn_next) { unsigned int badness = f->scn_bad; if (!best || badness < best->scn_bad) best = f; if (badness > worst) worst = badness; nfunnels++; } if (!best) return NULL; sock = isns_connect_to_portal(&best->scn_portal); if (sock == NULL) { /* Make sure we try each funnel exactly once */ best->scn_bad = worst + 1; if (++loops < nfunnels) goto again; return NULL; } /* Set the security context */ isns_socket_set_security_ctx(sock, isns_default_security_context(1)); isns_debug_scn("SCN: %s using portal %s\n", scn->scn_name, isns_portal_string(&best->scn_portal)); scn->scn_current_funnel = best; best->scn_socket = sock; return sock; } /* * This is the callback function invoked when the SCN message reply * comes in, or when the message timed out. */ static void isns_process_scn_response(uint32_t xid, int status, isns_simple_t *msg) { isns_scn_t *scn; if (msg == NULL) { isns_debug_scn("SCN timed out\n"); return; } isns_debug_scn("Received an SCN response\n"); for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_pending && scn->scn_xid == xid) { isns_debug_scn("SCN: %s acknowledged notification\n", scn->scn_name); isns_simple_free(scn->scn_pending); scn->scn_pending = NULL; if (scn->scn_current_funnel) scn->scn_current_funnel->scn_bad = 0; } } } /* * Transmit all pending SCN messages * * 2.9.2 * If a Network Entity has multiple Portals with registered SCN UDP Ports, * then SCN messages SHALL be delivered to each Portal registered to * receive such messages. * * FIXME: we should make this timer based just as the ESI code. */ time_t isns_scn_transmit_all(void) { time_t now = time(NULL), next_timeout; isns_scn_t *scn; for (scn = isns_scn_list; scn; scn = scn->scn_next) { isns_simple_t *call; isns_socket_t *sock; /* We do not allow more than one outstanding * notification for now. */ if ((call = scn->scn_pending) != NULL) { if (scn->scn_timeout > now) continue; scn->scn_current_funnel->scn_bad++; if (--(scn->scn_retries)) goto retry; isns_warning("SCN for %s timed out\n", scn->scn_name); isns_simple_free(call); scn->scn_pending = NULL; } if ((call = scn->scn_message) == NULL) continue; isns_debug_scn("SCN: transmit pending message for %s\n", scn->scn_name); scn->scn_retries = isns_config.ic_scn_retries; scn->scn_pending = call; scn->scn_message = NULL; retry: if ((sock = isns_scn_get_socket(scn)) == NULL) { /* Sorry, no can do. */ isns_warning("SCN for %s dropped - no portal\n", scn->scn_name); scn->scn_pending = NULL; isns_simple_free(call); continue; } isns_simple_transmit(sock, call, NULL, isns_config.ic_scn_timeout, isns_process_scn_response); scn->scn_xid = call->is_xid; scn->scn_timeout = now + isns_config.ic_scn_timeout; } next_timeout = now + 3600; for (scn = isns_scn_list; scn; scn = scn->scn_next) { if (scn->scn_pending && scn->scn_timeout < next_timeout) next_timeout = scn->scn_timeout; } return next_timeout; } /* * Process an incoming State Change Notification */ int isns_process_scn(isns_server_t *srv, isns_simple_t *call, isns_simple_t **reply) { isns_attr_list_t *list = &call->is_message_attrs; isns_attr_t *dstattr, *tsattr; const char *dst_name; unsigned int i; /* The first attribute is the destination, and should match * our source name. Don't bother checking. The second is the * time stamp. */ if (list->ial_count < 2) goto rejected; dstattr = list->ial_data[0]; if (dstattr->ia_tag_id != ISNS_TAG_ISCSI_NAME && dstattr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) goto rejected; if (!ISNS_ATTR_IS_STRING(dstattr)) goto rejected; dst_name = dstattr->ia_value.iv_string; tsattr = list->ial_data[1]; if (tsattr->ia_tag_id != ISNS_TAG_TIMESTAMP) return ISNS_SCN_EVENT_REJECTED; for (i = 2; i < list->ial_count; ) { isns_object_template_t *tmpl; isns_attr_t *bmattr, *srcattr; const char *node_name; uint32_t bitmap; if (i + 1 >= list->ial_count) goto rejected; bmattr = list->ial_data[i++]; srcattr = list->ial_data[i++]; /* Validate that bitmap and node type match */ switch (bmattr->ia_tag_id) { case ISNS_TAG_ISCSI_SCN_BITMAP: if (srcattr->ia_tag_id != ISNS_TAG_ISCSI_NAME) goto rejected; tmpl = &isns_iscsi_node_template; break; case ISNS_TAG_IFCP_SCN_BITMAP: if (srcattr->ia_tag_id != ISNS_TAG_FC_PORT_NAME_WWPN) goto rejected; tmpl = &isns_fc_port_template; break; default: goto rejected; } /* Skip over and DD_ID or DDS_ID attrs */ while (i < list->ial_count) { isns_attr_t *ddattr = list->ial_data[i]; if (ddattr->ia_tag_id == ISNS_TAG_ISCSI_SCN_BITMAP || ddattr->ia_tag_id == ISNS_TAG_IFCP_SCN_BITMAP) break; ++i; } if (!ISNS_ATTR_IS_UINT32(bmattr)) goto rejected; bitmap = bmattr->ia_value.iv_uint32; if (!ISNS_ATTR_IS_STRING(srcattr)) goto rejected; node_name = srcattr->ia_value.iv_string; if (srv->is_scn_callback) srv->is_scn_callback(srv->is_db, bitmap, tmpl, node_name, dst_name); } /* * 5.7.5.8. SCN Response (SCNRsp) * The SCNRsp response contains the SCN Destination Attribute * representing the Node identifier that received the SCN. */ *reply = isns_create_scn(srv->is_source, list->ial_data[0], NULL); return ISNS_SUCCESS; rejected: return ISNS_SCN_EVENT_REJECTED; } open-iscsi-2.0.873/utils/open-isns/scope.c000066400000000000000000000313171175631155400203110ustar00rootroot00000000000000/* * Handle object visibility and scope. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "attrs.h" #include "objects.h" #include "message.h" #include "security.h" #include "util.h" #include "db.h" struct isns_scope { isns_db_t * ic_db; unsigned int ic_users; isns_object_t * ic_source_node; isns_object_template_t * ic_query_class; isns_object_list_t ic_dd_nodes; isns_object_list_t ic_dd_portals; isns_object_list_t ic_objects; }; static int __isns_scope_collect_dd(uint32_t, void *); /* * Allocate an empty scope */ isns_scope_t * isns_scope_alloc(isns_db_t *db) { isns_scope_t *scope; scope = isns_calloc(1, sizeof(*scope)); scope->ic_db = db; scope->ic_users = 1; return scope; } isns_scope_t * isns_scope_get(isns_scope_t *scope) { if (scope) { isns_assert(scope->ic_users); scope->ic_users++; } return scope; } void isns_scope_release(isns_scope_t *scope) { if (!scope) return; isns_assert(scope->ic_users); if (--(scope->ic_users)) return; isns_object_release(scope->ic_source_node); isns_object_list_destroy(&scope->ic_dd_nodes); isns_object_list_destroy(&scope->ic_dd_portals); isns_object_list_destroy(&scope->ic_objects); isns_free(scope); } /* * Get the scope for this operation */ isns_scope_t * isns_scope_for_call(isns_db_t *db, const isns_simple_t *call) { isns_source_t *source = call->is_source; isns_object_t *node; isns_scope_t *scope; uint32_t node_type; /* FIXME use source->is_node and source->is_node_type */ /* When we get here, we already know that the client * represents the specified source node. */ node = isns_db_lookup_source_node(db, source); /* Allow unknown nodes to query the DB */ if (node == NULL) { node = isns_create_storage_node2(source, 0, NULL); if (node == NULL) return NULL; source->is_untrusted = 1; } if (isns_object_get_uint32(node, ISNS_TAG_ISCSI_NODE_TYPE, &node_type) && (node_type & ISNS_ISCSI_CONTROL_MASK)) { isns_object_release(node); return isns_scope_get(db->id_global_scope); } scope = isns_scope_alloc(db); scope->ic_source_node = node; { isns_object_list_t members = ISNS_OBJECT_LIST_INIT; unsigned int i; isns_object_get_visible(node, db, &members); isns_object_list_uniq(&members); /* If the node is not a member of any DD, allow it * to at least talk to itself. */ if (members.iol_count == 0) isns_object_list_append(&members, node); /* Sort DD members into nodes and portals */ for (i = 0; i < members.iol_count; ++i) { isns_object_t *obj = members.iol_data[i]; if (obj->ie_state != ISNS_OBJECT_STATE_MATURE) continue; if (!isns_policy_validate_object_access(call->is_policy, source, obj, call->is_function)) continue; if (ISNS_IS_ISCSI_NODE(obj)) isns_object_list_append(&scope->ic_dd_nodes, obj); else if (ISNS_IS_PORTAL(obj)) isns_object_list_append(&scope->ic_dd_portals, obj); } isns_object_list_destroy(&members); } return scope; } /* * Add an object to a scope */ void isns_scope_add(isns_scope_t *scope, isns_object_t *obj) { isns_object_list_append(&scope->ic_objects, obj); } int isns_scope_remove(isns_scope_t *scope, isns_object_t *obj) { return isns_object_list_remove(&scope->ic_objects, obj); } /* * Get all objects related through a portal group, optionally * including the portal group objects themselves */ static void __isns_scope_get_pg_related(isns_scope_t *scope, const isns_object_t *obj, isns_object_list_t *result) { isns_object_list_t temp = ISNS_OBJECT_LIST_INIT; unsigned int i; /* Get all portal groups related to this object */ isns_db_get_relationship_objects(scope->ic_db, obj, ISNS_RELATION_PORTAL_GROUP, &temp); /* Include all portals/nodes that we can reach. */ for (i = 0; i < temp.iol_count; ++i) { isns_object_t *pg, *other; uint32_t pgt; pg = temp.iol_data[i]; /* Skip any portal group objects with a PG tag of 0; * these actually deny access. */ if (!isns_object_get_uint32(pg, ISNS_TAG_PG_TAG, &pgt) || pgt == 0) continue; /* Get the other object. * Note that isns_relation_get_other doesn't * bump the reference count, so there's no need * to call isns_object_release(other). */ other = isns_relation_get_other(pg->ie_relation, obj); if (other->ie_state != ISNS_OBJECT_STATE_MATURE) continue; isns_object_list_append(result, other); isns_object_list_append(result, pg); } isns_object_list_destroy(&temp); } /* * Get all portals related to the given node. * * 2.2.2 * Placing Portals of a Network Entity into Discovery Domains allows * administrators to indicate the preferred IP Portal interface through * which storage traffic should access specific Storage Nodes of that * Network Entity. If no Portals of a Network Entity have been placed * into a DD, then queries scoped to that DD SHALL report all Portals of * that Network Entity. If one or more Portals of a Network Entity have * been placed into a DD, then queries scoped to that DD SHALL report * only those Portals that have been explicitly placed in the DD. */ static void __isns_scope_get_portals(isns_scope_t *scope, const isns_object_t *node, isns_object_list_t *portals, isns_object_list_t *pgs, int unique) { isns_object_list_t related = ISNS_OBJECT_LIST_INIT; unsigned int i, specific = 0; /* Get all portals and portal groups related to the * given node. This will put pairs of (portal, portal-group) * on the list. */ __isns_scope_get_pg_related(scope, node, &related); /* If we're querying for our own portals, don't limit * visibility. */ if (node == scope->ic_source_node) goto report_all_portals; /* Check if any of the portals is mentioned in the DD * FIXME: There is some ambiguity over what the right * answer is when you have two nodes (initiator, target), * and two discovery domains linking the two. One * DD mentions a specific portal through which target * should be accessed; the other DD does not (allowing * use of any portal in that entity). Which portals * to return here? * We go for the strict interpretation, ie if *any* DD * restricts access to certain portals, we report only * those. */ for (i = 0; i < related.iol_count; i += 2) { isns_object_t *portal = related.iol_data[i]; if (isns_object_list_contains(&scope->ic_dd_portals, portal)) { if (portals && !(unique || isns_object_list_contains(portals, portal))) isns_object_list_append(portals, portal); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); specific++; } } if (specific) goto out; report_all_portals: /* No specific portal given for this node. Add them all. */ for (i = 0; i < related.iol_count; i += 2) { isns_object_t *portal = related.iol_data[i]; if (portals && !(unique && isns_object_list_contains(portals, portal))) isns_object_list_append(portals, portal); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); } out: isns_object_list_destroy(&related); } /* * Get all nodes reachable through a given portal * This is really the same as __isns_scope_get_portals * minus the special casing for preferred portals. * Still, let's put this into it's own function - the whole * thing is already complex enough already. */ static void __isns_scope_get_nodes(isns_scope_t *scope, const isns_object_t *portal, isns_object_list_t *nodes, isns_object_list_t *pgs, int unique) { isns_object_list_t related = ISNS_OBJECT_LIST_INIT; unsigned int i; /* Get all nodes and portal groups related to the * given node. This will put pairs of (nodes, portal-group) * on the list. */ __isns_scope_get_pg_related(scope, portal, &related); for (i = 0; i < related.iol_count; i += 2) { isns_object_t *node = related.iol_data[i]; if (nodes && !(unique && isns_object_list_contains(nodes, node))) isns_object_list_append(nodes, node); if (pgs) isns_object_list_append(pgs, related.iol_data[i + 1]); } isns_object_list_destroy(&related); } static void __isns_scope_get_default_dd(isns_scope_t *scope) { isns_object_t *obj; if (isns_config.ic_use_default_domain) { obj = isns_create_default_domain(); isns_object_list_append(&scope->ic_objects, obj); isns_object_release(obj); } } /* * Scope the query */ static void __isns_scope_prepare_query(isns_scope_t *scope, isns_object_template_t *tmpl) { isns_object_list_t *nodes; unsigned int i; /* Global and default scope have no source node; they're just * a list of objects. */ if (scope->ic_source_node == NULL) return; if (scope->ic_query_class) { if (scope->ic_query_class == tmpl) return; isns_object_list_destroy(&scope->ic_objects); } scope->ic_query_class = tmpl; nodes = &scope->ic_dd_nodes; if (tmpl == &isns_entity_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; if (obj->ie_container) isns_object_list_append(&scope->ic_objects, obj->ie_container); } } else if (tmpl == &isns_iscsi_node_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; isns_object_list_append(&scope->ic_objects, obj); } } else if (tmpl == &isns_portal_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; __isns_scope_get_portals(scope, obj, &scope->ic_objects, NULL, 0); } } else if (tmpl == &isns_iscsi_pg_template) { for (i = 0; i < nodes->iol_count; ++i) { isns_object_t *obj = nodes->iol_data[i]; __isns_scope_get_portals(scope, obj, NULL, &scope->ic_objects, 0); } } else if (tmpl == &isns_dd_template) { isns_object_t *node = scope->ic_source_node; if (node && !isns_bitvector_is_empty(node->ie_membership)) isns_bitvector_foreach(node->ie_membership, __isns_scope_collect_dd, scope); else __isns_scope_get_default_dd(scope); } isns_object_list_uniq(&scope->ic_objects); } static int __isns_scope_collect_dd(uint32_t dd_id, void *ptr) { isns_scope_t *scope = ptr; isns_object_t *dd; dd = isns_db_vlookup(scope->ic_db, &isns_dd_template, ISNS_TAG_DD_ID, dd_id, 0); if (dd) { isns_object_list_append(&scope->ic_objects, dd); isns_object_release(dd); } return 0; } /* * Lookup functions for scope */ int isns_scope_gang_lookup(isns_scope_t *scope, isns_object_template_t *tmpl, const isns_attr_list_t *match, isns_object_list_t *result) { isns_assert(tmpl); if (!scope) return 0; __isns_scope_prepare_query(scope, tmpl); return isns_object_list_gang_lookup(&scope->ic_objects, tmpl, match, result); } /* * Get related objects. * This is used by the query code. */ void isns_scope_get_related(isns_scope_t *scope, const isns_object_t *origin, unsigned int type_mask, isns_object_list_t *result) { isns_object_template_t *tmpl = origin->ie_template; isns_object_list_t nodes_result = ISNS_OBJECT_LIST_INIT; isns_object_list_t portals_result = ISNS_OBJECT_LIST_INIT; isns_object_list_t *members = &scope->ic_dd_nodes; unsigned int i; if (tmpl == &isns_entity_template) { /* Entity: include all storage nodes contained, * the portals through which to reach them, and * the portal groups for those. */ for (i = 0; i < members->iol_count; ++i) { isns_object_t *obj = members->iol_data[i]; if (obj->ie_container != origin) continue; isns_object_list_append(&nodes_result, obj); __isns_scope_get_portals(scope, obj, &portals_result, &portals_result, 1); } } else if (tmpl == &isns_iscsi_node_template) { /* Storage node: include all portals through * which it can be reached, and the portal * groups for those. */ __isns_scope_get_portals(scope, origin, &portals_result, &portals_result, 1); /* FIXME: Include all discovery domains the * node is a member of. */ } else if (tmpl == &isns_portal_template) { /* Portal: include all storage nodes which can * be reached through it, and the portal groups * for those. */ __isns_scope_get_nodes(scope, origin, &portals_result, &portals_result, 1); } else if (tmpl == &isns_iscsi_pg_template) { /* Portal group: PGs *are* a relationship, but * unclear how this should be handled. * Return nothing for now. */ } else if (tmpl == &isns_dd_template) { /* Discovery domain: no related objects. */ } isns_object_list_append_list(result, &nodes_result); isns_object_list_append_list(result, &portals_result); isns_object_list_destroy(&nodes_result); isns_object_list_destroy(&portals_result); } isns_object_t * isns_scope_get_next(isns_scope_t *scope, isns_object_template_t *tmpl, const isns_attr_list_t *current, const isns_attr_list_t *match) { if (!tmpl || !scope) return NULL; __isns_scope_prepare_query(scope, tmpl); return __isns_db_get_next(&scope->ic_objects, tmpl, current, match); } open-iscsi-2.0.873/utils/open-isns/security.c000066400000000000000000000217531175631155400210520ustar00rootroot00000000000000/* * Security functions for iSNS * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "security.h" #include "source.h" #include "util.h" #include "config.h" #ifdef WITH_SECURITY /* * Allocate a security peer */ static isns_principal_t * isns_create_principal(const char *spi, size_t spi_len, EVP_PKEY *pk) { char keydesc[32]; isns_principal_t *peer; peer = isns_calloc(1, sizeof(*peer)); peer->is_users = 1; if (spi) { peer->is_name = isns_malloc(spi_len + 1); memcpy(peer->is_name, spi, spi_len); peer->is_name[spi_len] = '\0'; peer->is_namelen = spi_len; } peer->is_key = pk; if (pk) { const char *algo; switch (pk->type) { case EVP_PKEY_DSA: algo = "DSA"; break; case EVP_PKEY_RSA: algo = "RSA"; break; default: algo = "unknown"; break; } snprintf(keydesc, sizeof(keydesc), " (%s/%u)", algo, EVP_PKEY_bits(pk)); } isns_debug_auth("Created security principal \"%s\"%s\n", peer->is_name, keydesc); return peer; } static void isns_principal_set_key(isns_principal_t *princ, EVP_PKEY *key) { if (princ->is_key == key) return; if (princ->is_key) EVP_PKEY_free(princ->is_key); princ->is_key = key; } void isns_principal_free(isns_principal_t *peer) { if (!peer) return; isns_assert(peer->is_users); if (--(peer->is_users)) return; if (peer->is_name) isns_free(peer->is_name); if (peer->is_key) EVP_PKEY_free(peer->is_key); isns_policy_release(peer->is_policy); isns_free(peer); } /* * Set the principal's name */ void isns_principal_set_name(isns_principal_t *princ, const char *spi) { isns_assign_string(&princ->is_name, spi); isns_debug_auth("Setting principal name to \"%s\"\n", spi); } const char * isns_principal_name(const isns_principal_t *princ) { return princ->is_name; } /* * Cache policy in the principal object. */ void isns_principal_set_policy(isns_principal_t *princ, isns_policy_t *policy) { if (policy) policy->ip_users++; isns_policy_release(princ->is_policy); princ->is_policy = policy; } /* * Key management functions for a security context. */ isns_principal_t * isns_security_load_privkey(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; isns_debug_auth("Loading private %s key from %s\n", ctx->is_name, filename); if (!ctx->is_load_private) return NULL; if (!(pkey = ctx->is_load_private(ctx, filename))) { isns_error("Unable to load private %s key from %s\n", ctx->is_name, filename); return NULL; } return isns_create_principal(NULL, 0, pkey); } isns_principal_t * isns_security_load_pubkey(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; isns_debug_auth("Loading public %s key from %s\n", ctx->is_name, filename); if (!ctx->is_load_public) return NULL; if (!(pkey = ctx->is_load_public(ctx, filename))) { isns_error("Unable to load public %s key from %s\n", ctx->is_name, filename); return NULL; } return isns_create_principal(NULL, 0, pkey); } void isns_security_set_identity(isns_security_t *ctx, isns_principal_t *princ) { if (princ) princ->is_users++; if (ctx->is_self) isns_principal_free(ctx->is_self); ctx->is_self = princ; } void isns_add_principal(isns_security_t *ctx, isns_principal_t *princ) { if (princ) princ->is_users++; princ->is_next = ctx->is_peers; ctx->is_peers = princ; } isns_principal_t * isns_get_principal(isns_security_t *ctx, const char *spi, size_t spi_len) { isns_principal_t *princ; isns_policy_t *policy; isns_keystore_t *ks; EVP_PKEY *pk; ks = ctx->is_peer_keys; for (princ = ctx->is_peers; princ; princ = princ->is_next) { /* In a client socket, we set the (expected) * public key of the peer through * isns_security_set_peer_key, which will * just put it on the peers list. * This key usually has no name. */ if (princ->is_name == NULL) { princ->is_users++; return princ; } if (spi_len == princ->is_namelen && !memcmp(princ->is_name, spi, spi_len)) { /* Check whether the cached key and policy * might be stale. */ if (ks && ks->ic_generation != princ->is_generation) { pk = ks->ic_find(ks, spi, spi_len); if (pk == NULL) { isns_debug_auth("Unable to refresh key " "for principal %.*s - probably deleted\n", spi_len, spi); return NULL; } isns_debug_auth("Refresh key for principal %.*s\n", spi_len, spi); isns_principal_set_key(princ, pk); princ->is_users++; goto refresh_policy; } princ->is_users++; return princ; } } if ((ks = ctx->is_peer_keys) == NULL) return NULL; if (!(pk = ks->ic_find(ks, spi, spi_len))) return NULL; princ = isns_create_principal(spi, spi_len, pk); /* Add it to the list */ princ->is_next = ctx->is_peers; ctx->is_peers = princ; princ->is_users++; /* Bind the policy for this peer */ refresh_policy: if (!ks->ic_get_policy || !(policy = ks->ic_get_policy(ks, spi, spi_len))) policy = isns_policy_default(spi, spi_len); /* If no entity is set, use the SPI */ if (policy->ip_entity == NULL) isns_assign_string(&policy->ip_entity, policy->ip_name); /* If the list of permitted node names is empty, * default to the standard pattern derived from * the reversed entity name */ if (policy->ip_node_names.count == 0) { char *pattern; pattern = isns_build_source_pattern(policy->ip_entity); if (pattern != NULL) isns_string_array_append(&policy->ip_node_names, pattern); isns_free(pattern); } isns_principal_set_policy(princ, policy); isns_policy_release(policy); /* Remember the keystore generation number */ princ->is_generation = ks->ic_generation; return princ; } /* * Create a keystore for a security context. * Key stores let the server side retrieve the * keys associated with a given SPI. * * For now, we support just simple key stores, * but this could be extended to support * URLs such as ldaps://ldap.example.com */ isns_keystore_t * isns_create_keystore(const char *spec) { if (*spec != '/') return NULL; return isns_create_simple_keystore(spec); } /* * Attach the keystore to the security context */ void isns_security_set_keystore(isns_security_t *ctx, isns_keystore_t *ks) { ctx->is_peer_keys = ks; } /* * Check that the client supplied time stamp is within a * certain window. */ static int isns_security_check_timestamp(isns_security_t *ctx, isns_principal_t *peer, uint64_t timestamp) { int64_t delta; /* The time stamp must not be earlier than timestamp_jitter * before the last message received. */ if (peer->is_timestamp) { delta = timestamp - peer->is_timestamp; if (delta < -(int64_t) ctx->is_timestamp_jitter) return 0; } /* We allow the client's clock to diverge from ours, within * certain limits. */ if (ctx->is_replay_window != 0) { time_t now = time(NULL); delta = timestamp - now; if (delta < 0) delta = -delta; if (delta > ctx->is_replay_window) return 0; } peer->is_timestamp = timestamp; return 1; } int isns_security_sign(isns_security_t *ctx, isns_principal_t *peer, buf_t *bp, struct isns_authblk *auth) { if (!ctx->is_sign) { isns_debug_auth("isns_security_sign: auth context without " "sign handler.\n"); return 0; } if (!ctx->is_sign(ctx, peer, bp, auth)) { isns_debug_auth("Failed to sign message, spi=%s\n", peer->is_name); return 0; } return 1; } int isns_security_verify(isns_security_t *ctx, isns_principal_t *peer, buf_t *bp, struct isns_authblk *auth) { if (!isns_security_check_timestamp(ctx, peer, auth->iab_timestamp)) { isns_debug_auth("Possible replay attack (bad timestamp) " "from spi=%s\n", peer->is_name); return 0; } if (!ctx->is_verify) { isns_debug_auth("isns_security_verify: auth context without " "verify handler.\n"); return 0; } if (!ctx->is_verify(ctx, peer, bp, auth)) { isns_debug_auth("Failed to authenticate message, spi=%s\n", peer->is_name); return 0; } return 1; } /* * Initialize security services. */ int isns_security_init(void) { if (!isns_config.ic_dsa.param_file) { isns_error("No DSA parameter file - please edit configuration\n"); return 0; } if (!isns_dsa_init_params(isns_config.ic_dsa.param_file)) return 0; if (!isns_config.ic_auth_key_file) { isns_error("No AuthKey specified; please edit configuration\n"); return 0; } if (!isns_dsa_init_key(isns_config.ic_auth_key_file)) return 0; return 1; } #else /* WITH_SECURITY */ static void isns_no_security(void) { static int complain = 0; if (complain++ < 5) isns_error("iSNS authentication disabled in this build\n"); } int isns_security_init(void) { isns_no_security(); return 0; } isns_keystore_t * isns_create_keystore(const char *spec) { isns_no_security(); return NULL; } void isns_security_set_keystore(isns_security_t *ctx, isns_keystore_t *ks) { isns_no_security(); } void isns_principal_free(isns_principal_t *peer) { } isns_principal_t * isns_get_principal(isns_security_t *ctx, const char *spi, size_t spi_len) { return NULL; } const char * isns_principal_name(const isns_principal_t *princ) { return NULL; } #endif /* WITH_SECURITY */ open-iscsi-2.0.873/utils/open-isns/security.h000066400000000000000000000130341175631155400210500ustar00rootroot00000000000000/* * Security functions for iSNS * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_SECURITY_H #define ISNS_SECURITY_H #include "buffer.h" #include "util.h" #ifdef WITH_SECURITY #include #else #define EVP_PKEY void #endif /* * Security context */ struct isns_security { const char * is_name; unsigned int is_type; unsigned int is_replay_window; unsigned int is_timestamp_jitter; /* Our own key and identity */ isns_principal_t * is_self; /* Key store for peer keys */ isns_principal_t * is_peers; isns_keystore_t * is_peer_keys; EVP_PKEY * (*is_load_private)(isns_security_t *ctx, const char *filename); EVP_PKEY * (*is_load_public)(isns_security_t *ctx, const char *filename); int (*is_verify)(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, const struct isns_authblk *); int (*is_sign)(isns_security_t *ctx, isns_principal_t *peer, buf_t *pdu, struct isns_authblk *); }; struct isns_principal { unsigned int is_users; isns_principal_t * is_next; char * is_name; unsigned int is_namelen; EVP_PKEY * is_key; unsigned int is_generation; uint64_t is_timestamp; isns_policy_t * is_policy; }; struct isns_policy { unsigned int ip_users; unsigned int ip_gen; /* SPI */ char * ip_name; /* The client's entity name. This is usually * the FQDN. */ char * ip_entity; /* Bitmap of functions the client is * permitted to call. */ unsigned int ip_functions; /* Bitmap of object types the client is * permitted to register (uses iot_handle) */ unsigned int ip_object_types; /* Names of storage nodes the client is permitted * to register. */ struct string_array ip_node_names; /* Storage node types the client is permitted * to read or modify. */ unsigned int ip_node_types; /* The client's default Discovery Domain */ char * ip_dd_default; }; #define ISNS_PERMISSION_READ 0x01 #define ISNS_PERMISSION_WRITE 0x02 #define ISNS_ACCESS(t, p) ((p) << (2 * (t))) #define ISNS_ACCESS_W(t) ISNS_ACCESS(t, ISNS_PERMISSION_WRITE) #define ISNS_ACCESS_R(t) ISNS_ACCESS(t, ISNS_PERMISSION_READ) #define ISNS_ACCESS_RW(t) ISNS_ACCESS(t, ISNS_PERMISSION_READ|ISNS_PERMISSION_WRITE) #define ISNS_DEFAULT_OBJECT_ACCESS \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_ENTITY) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_NODE) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_FC_PORT) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_FC_NODE) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_PORTAL) | \ ISNS_ACCESS_RW(ISNS_OBJECT_TYPE_PG) | \ ISNS_ACCESS_R(ISNS_OBJECT_TYPE_DD) struct isns_keystore { char * ic_name; unsigned int ic_generation; EVP_PKEY * (*ic_find)(isns_keystore_t *, const char *, size_t); isns_policy_t * (*ic_get_policy)(isns_keystore_t *, const char *, size_t); }; extern isns_principal_t * isns_get_principal(isns_security_t *, const char *, size_t); extern int isns_security_sign(isns_security_t *, isns_principal_t *, buf_t *, struct isns_authblk *); extern int isns_security_verify(isns_security_t *, isns_principal_t *, buf_t *, struct isns_authblk *); extern int isns_security_protected_entity(isns_security_t *, const char *); extern isns_keystore_t * isns_create_keystore(const char *); extern isns_keystore_t * isns_create_simple_keystore(const char *); extern isns_keystore_t * isns_create_db_keystore(isns_db_t *); extern int isns_authblock_encode(buf_t *, const struct isns_authblk *); extern int isns_authblock_decode(buf_t *, struct isns_authblk *); extern isns_policy_t * __isns_policy_alloc(const char *, size_t); extern isns_policy_t * isns_policy_bind(const isns_message_t *); extern void isns_principal_set_policy(isns_principal_t *, isns_policy_t *); extern void isns_policy_release(isns_policy_t *); extern int isns_policy_validate_function(const isns_policy_t *, const isns_message_t *); extern int isns_policy_validate_source(const isns_policy_t *, const isns_source_t *); extern int isns_policy_validate_object_access(const isns_policy_t *, const isns_source_t *, const isns_object_t *, unsigned int); extern int isns_policy_validate_object_update(const isns_policy_t *, const isns_source_t *, const isns_object_t *, const isns_attr_list_t *, unsigned int); extern int isns_policy_validate_object_creation(const isns_policy_t *, const isns_source_t *, isns_object_template_t *, const isns_attr_list_t *, const isns_attr_list_t *, unsigned int); extern int isns_policy_validate_object_type(const isns_policy_t *, isns_object_template_t *, unsigned int function); extern int isns_policy_validate_node_type(const isns_policy_t *, uint32_t type); extern int isns_policy_validate_entity(const isns_policy_t *, const char *); extern int isns_policy_validate_node_name(const isns_policy_t *, const char *); extern int isns_policy_validate_scn_bitmap(const isns_policy_t *, uint32_t); extern const char * isns_policy_default_entity(const isns_policy_t *); extern isns_policy_t * isns_policy_default(const char *, size_t); extern isns_policy_t * isns_policy_server(void); extern EVP_PKEY * isns_dsa_decode_public(const void *, size_t); extern int isns_dsa_encode_public(EVP_PKEY *, void **, size_t *); extern EVP_PKEY * isns_dsa_load_public(const char *); extern int isns_dsa_store_private(const char *, EVP_PKEY *); extern EVP_PKEY * isns_dsa_generate_key(void); extern int isns_dsa_init_params(const char *); extern int isns_dsa_init_key(const char *); #endif /* ISNS_SECURITY_H */ open-iscsi-2.0.873/utils/open-isns/server.c000066400000000000000000000147151175631155400205110ustar00rootroot00000000000000/* * iSNS server side functions * * Copyright (C) 2007 Olaf Kirch */ #include "isns.h" #include "util.h" #include "security.h" #include "message.h" static int isns_not_supported(isns_server_t *, isns_simple_t *, isns_simple_t **); struct isns_service_ops isns_default_service_ops = { .process_registration = isns_process_registration, .process_query = isns_process_query, .process_getnext = isns_process_getnext, .process_deregistration = isns_process_deregistration, .process_scn_registration = isns_process_scn_register, .process_scn_deregistration = isns_process_scn_deregistration, .process_scn_event = isns_not_supported, .process_dd_registration = isns_process_dd_registration, .process_dd_deregistration= isns_process_dd_deregistration, }; struct isns_service_ops isns_callback_service_ops = { .process_esi = isns_process_esi, .process_scn = isns_process_scn, }; /* * Create a server object */ isns_server_t * isns_create_server(isns_source_t *source, isns_db_t *db, struct isns_service_ops *ops) { isns_server_t *srv; if (source == NULL) { isns_error("%s: source name not set\n", __FUNCTION__); return NULL; } srv = isns_calloc(1, sizeof(*srv)); srv->is_source = isns_source_get(source); srv->is_db = db; srv->is_ops = ops; return srv; } void isns_server_set_scn_callback(isns_server_t *srv, isns_scn_callback_fn_t *func) { srv->is_scn_callback = func; } /* * Try to handle transactions safely. * This isn't perfect, because there's state outside the DB (for instance * the DD information) */ static int isns_begin_write_operation(isns_server_t *srv, isns_simple_t *msg, int *status) { isns_db_begin_transaction(srv->is_db); return 1; } static void isns_end_write_operation(isns_server_t *srv, isns_simple_t *msg, int *status) { if (*status == ISNS_SUCCESS) isns_db_commit(srv->is_db); else isns_db_rollback(srv->is_db); } static inline int isns_begin_read_operation(isns_server_t *srv, isns_simple_t *msg, int *status) { return 1; } static void isns_end_read_operation(isns_server_t *srv, isns_simple_t *msg, int *status) { } /* * Process an incoming message */ isns_message_t * isns_process_message(isns_server_t *srv, isns_message_t *msg) { struct isns_service_ops *ops = srv->is_ops; uint16_t function = msg->im_header.i_function; int status = ISNS_SUCCESS; isns_simple_t *call = NULL, *reply = NULL; isns_message_t *res_msg = NULL; isns_db_t *db = srv->is_db; status = isns_simple_decode(msg, &call); if (status) { isns_debug_message("Failed to decode %s request: %s\n", isns_function_name(msg->im_header.i_function), isns_strerror(status)); goto reply; } isns_simple_print(call, isns_debug_message); /* Set policy and privileges based on the * sender's identity. */ if (!(call->is_policy = isns_policy_bind(msg))) goto err_unauthorized; if (!isns_policy_validate_function(call->is_policy, msg)) goto err_unauthorized; /* Checks related to the message source. * Note - some messages do not use a source. */ if (call->is_source) { /* Validate the message source. This checks whether the client * is permitted to use this source node name. * Beware - not all messages include a source. */ if (!isns_policy_validate_source(call->is_policy, call->is_source)) goto err_unauthorized; /* This may fail if the source node isn't in the DB yet. */ isns_source_set_node(call->is_source, db); /* * 6.2.6. Registration Period * * The registration SHALL be removed from the iSNS database * if an iSNS Protocol message is not received from the * iSNS client before the registration period has expired. * Receipt of any iSNS Protocol message from the iSNS client * automatically refreshes the Entity Registration Period and * Entity Registration Timestamp. To prevent a registration * from expiring, the iSNS client should send an iSNS Protocol * message to the iSNS server at intervals shorter than the * registration period. Such a message can be as simple as a * query for one of its own attributes, using its associated * iSCSI Name or FC Port Name WWPN as the Source attribute. */ /* Thusly, we update the timestamps of all entities * registered by this source. */ isns_entity_touch(call->is_source->is_entity); } /* Handle the requested function. If the function vector is * NULL, silently discard the message. */ switch (function) { #define DO(rw, FUNCTION, __function) \ case FUNCTION: \ if (!ops->__function) \ goto no_reply; \ \ if (!isns_begin_##rw##_operation(srv, call, &status)) \ break; \ status = ops->__function(srv, call, &reply); \ isns_end_##rw##_operation(srv, call, &status); \ break DO(write, ISNS_DEVICE_ATTRIBUTE_REGISTER, process_registration); DO(read, ISNS_DEVICE_ATTRIBUTE_QUERY, process_query); DO(read, ISNS_DEVICE_GET_NEXT, process_getnext); DO(write, ISNS_DEVICE_DEREGISTER, process_deregistration); DO(write, ISNS_DD_REGISTER, process_dd_registration); DO(write, ISNS_DD_DEREGISTER, process_dd_deregistration); DO(read, ISNS_SCN_REGISTER, process_scn_registration); DO(read, ISNS_SCN_DEREGISTER, process_scn_deregistration); DO(read, ISNS_SCN_EVENT, process_scn_event); DO(read, ISNS_STATE_CHANGE_NOTIFICATION, process_scn); DO(read, ISNS_ENTITY_STATUS_INQUIRY, process_esi); DO(read, ISNS_HEARTBEAT, process_heartbeat); #undef DO default: isns_error("Function %s not supported\n", isns_function_name(function)); status = ISNS_MESSAGE_NOT_SUPPORTED; break; } reply: /* Commit any changes to the DB before we reply */ if (db) isns_db_sync(db); /* Send out SCN notifications */ isns_flush_events(); if (reply != NULL) { reply->is_function |= 0x8000; isns_simple_print(reply, isns_debug_message); /* Encode the whole thing */ status = isns_simple_encode_response(reply, msg, &res_msg); } /* No reply, or error when encoding it: * just send the error, nothing else. */ if (res_msg == NULL) { res_msg = isns_create_reply(msg); if (status == ISNS_SUCCESS) status = ISNS_INTERNAL_ERROR; } isns_debug_message("response status 0x%04x (%s)\n", status, isns_strerror(status)); if (status != ISNS_SUCCESS) isns_message_set_error(res_msg, status); no_reply: isns_simple_free(call); if (reply) isns_simple_free(reply); return res_msg; err_unauthorized: status = ISNS_SOURCE_UNAUTHORIZED; goto reply; } int isns_not_supported(isns_server_t *srv, isns_simple_t *call, isns_simple_t **replyp) { return ISNS_MESSAGE_NOT_SUPPORTED; } open-iscsi-2.0.873/utils/open-isns/simple.c000066400000000000000000000421221175631155400204650ustar00rootroot00000000000000/* * Common handling for iSNS message parsing * * Copyright (C) 2007 Olaf Kirch * */ #include #include #include "isns.h" #include "attrs.h" #include "message.h" #include "objects.h" #include "security.h" #include "socket.h" #include "util.h" typedef void isns_simple_callback_fn_t(uint32_t, int status, isns_simple_t *); static int isns_attr_list_scanner_get_pg(struct isns_attr_list_scanner *st); /* * Allocate an empty simple message */ static isns_simple_t * __isns_alloc_simple(void) { isns_simple_t *simp; simp = isns_calloc(1, sizeof(*simp)); isns_attr_list_init(&simp->is_message_attrs); isns_attr_list_init(&simp->is_operating_attrs); return simp; } /* * Create a simple message, and set the source name */ isns_simple_t * isns_simple_create(uint32_t function, isns_source_t *source, const isns_attr_list_t *key) { isns_simple_t *simp; simp = __isns_alloc_simple(); simp->is_function = function; simp->is_source = source; if (source != NULL) source->is_users++; if (key) isns_attr_list_copy(&simp->is_message_attrs, key); return simp; } /* * Perform a call to the server, waiting for the response. */ int isns_simple_call(isns_socket_t *sock, isns_simple_t **inout) { isns_simple_t *simp = *inout; isns_message_t *msg, *resp; int status; isns_simple_print(simp, isns_debug_message); status = isns_simple_encode(simp, &msg); if (status != ISNS_SUCCESS) { isns_error("Unable to encode %s: %s\n", isns_function_name(simp->is_function), isns_strerror(status)); return status; } isns_debug_message("Sending request, len=%d\n", buf_avail(msg->im_payload)); resp = isns_socket_call(sock, msg, isns_config.ic_network.call_timeout); isns_assert(msg->im_users == 1); isns_message_release(msg); if (resp == NULL) { isns_error("Timed out while waiting for reply\n"); return ISNS_INTERNAL_ERROR; } isns_debug_message("Received reply, len=%d\n", buf_avail(resp->im_payload)); isns_assert(resp->im_users == 1); status = isns_message_status(resp); if (status != ISNS_SUCCESS) { isns_message_release(resp); return status; } status = isns_simple_decode(resp, &simp); isns_message_release(resp); if (status) { isns_error("Unable to decode server response: %s (status 0x%04x)\n", isns_strerror(status), status); return status; } isns_simple_print(simp, isns_debug_message); isns_simple_free(*inout); *inout = simp; return ISNS_SUCCESS; } /* * This callback is invoked from the network layer when * we received a response to an async message */ static void isns_simple_recv_response(isns_message_t *cmsg, isns_message_t *rmsg) { isns_simple_callback_fn_t *user_callback; isns_simple_t *resp = NULL; int status = ISNS_INTERNAL_ERROR; /* rmsg being NULL means the call timed out. */ if (rmsg == NULL) goto callback; status = isns_message_status(rmsg); if (status != ISNS_SUCCESS) { isns_error("Server flags error: %s (status 0x%04x)\n", isns_strerror(status), status); goto callback; } status = isns_simple_decode(rmsg, &resp); if (status) { isns_error("Unable to decode server response: %s (status 0x%04x)\n", isns_strerror(status), status); resp = NULL; goto callback; } isns_simple_print(resp, isns_debug_message); callback: user_callback = cmsg->im_calldata; if (user_callback) user_callback(cmsg->im_xid, status, resp); if (resp) isns_simple_free(resp); } /* * Transmit a call, without waiting for the response. */ int isns_simple_transmit(isns_socket_t *sock, isns_simple_t *call, const isns_portal_info_t *dest, unsigned int timeout, isns_simple_callback_fn_t *user_callback) { isns_message_t *msg; int status; isns_simple_print(call, isns_debug_message); status = isns_simple_encode(call, &msg); if (status != ISNS_SUCCESS) { isns_error("Unable to encode %s: %s\n", isns_function_name(call->is_function), isns_strerror(status)); return status; } isns_debug_message("Sending message, len=%d\n", buf_avail(msg->im_payload)); if (user_callback) { msg->im_callback = isns_simple_recv_response; msg->im_calldata = user_callback; } if (!isns_socket_submit(sock, msg, timeout)) status = ISNS_INTERNAL_ERROR; isns_message_release(msg); return status; } /* * Delete the simple message object */ void isns_simple_free(isns_simple_t *simp) { if (simp == NULL) return; isns_attr_list_destroy(&simp->is_message_attrs); isns_attr_list_destroy(&simp->is_operating_attrs); isns_source_release(simp->is_source); isns_policy_release(simp->is_policy); isns_free(simp); } /* * Get the source associated with this simple message */ isns_source_t * isns_simple_get_source(isns_simple_t *simp) { return simp->is_source; } const isns_attr_list_t * isns_simple_get_attrs(isns_simple_t *simp) { return &simp->is_operating_attrs; } /* * Determine whether message includes a source attr. */ static inline int isns_simple_include_source(uint16_t function) { if (function & 0x8000) return 0; switch (function) { case ISNS_STATE_CHANGE_NOTIFICATION: case ISNS_ENTITY_STATUS_INQUIRY: return 0; } return 1; } /* * Decode a simple message */ int isns_simple_decode(isns_message_t *msg, isns_simple_t **result) { isns_simple_t *simp = __isns_alloc_simple(); buf_t *bp = msg->im_payload; int status = ISNS_SUCCESS; simp->is_function = msg->im_header.i_function; simp->is_xid = msg->im_xid; if (isns_simple_include_source(simp->is_function)) { status = isns_source_decode(bp, &simp->is_source); if (status != ISNS_SUCCESS) goto out; } switch (simp->is_function & 0x7FFF) { case ISNS_ENTITY_STATUS_INQUIRY: case ISNS_STATE_CHANGE_NOTIFICATION: /* Server messages do not include a source */ status = isns_attr_list_decode(bp, &simp->is_message_attrs); break; default: status = isns_attr_list_decode_delimited(bp, &simp->is_message_attrs); if (status == ISNS_SUCCESS) status = isns_attr_list_decode(bp, &simp->is_operating_attrs); } if (msg->im_header.i_flags & ISNS_F_REPLACE) simp->is_replace = 1; out: if (status == ISNS_SUCCESS) { *result = simp; } else { isns_simple_free(simp); *result = NULL; } return status; } /* * Encode a simple message reply or response */ static int __isns_simple_encode(isns_simple_t *simp, buf_t *bp) { int status = ISNS_SUCCESS; if (isns_simple_include_source(simp->is_function)) { if (simp->is_source == NULL) { isns_error("Cannot encode %s message - caller forgot to set source\n", isns_function_name(simp->is_function)); return ISNS_SOURCE_UNKNOWN; } status = isns_source_encode(bp, simp->is_source); } if (status == ISNS_SUCCESS) status = isns_attr_list_encode(bp, &simp->is_message_attrs); /* Some functions have just one set of attrs. */ switch (simp->is_function & 0x7fff) { /* It's not entirely clear which calls actually have the delimiter. * The spec is sometimes a little vague on this. */ case ISNS_SCN_DEREGISTER: case ISNS_ENTITY_STATUS_INQUIRY: case ISNS_STATE_CHANGE_NOTIFICATION: break; default: if (status == ISNS_SUCCESS) status = isns_encode_delimiter(bp); if (status == ISNS_SUCCESS) status = isns_attr_list_encode(bp, &simp->is_operating_attrs); break; } return status; } int isns_simple_encode(isns_simple_t *simp, isns_message_t **result) { isns_message_t *msg; int status, flags; flags = ISNS_F_CLIENT; if (simp->is_replace) flags |= ISNS_F_REPLACE; msg = isns_create_message(simp->is_function, flags); /* FIXME: for UDP sockets, isns_simple_t may contain a destination address. */ status = __isns_simple_encode(simp, msg->im_payload); if (status != ISNS_SUCCESS) { isns_message_release(msg); msg = NULL; } /* Report the XID to the caller */ simp->is_xid = msg->im_xid; *result = msg; return status; } int isns_simple_encode_response(isns_simple_t *reg, const isns_message_t *request, isns_message_t **result) { isns_message_t *msg; int status; msg = isns_create_reply(request); status = __isns_simple_encode(reg, msg->im_payload); if (status != ISNS_SUCCESS) { isns_message_release(msg); msg = NULL; } *result = msg; return status; } int isns_simple_decode_response(isns_message_t *resp, isns_simple_t **result) { return isns_simple_decode(resp, result); } /* * Extract the list of objects from a DevAttrReg/DevAttrQry * response or similar. */ int isns_simple_response_get_objects(isns_simple_t *resp, isns_object_list_t *result) { struct isns_attr_list_scanner state; int status = ISNS_SUCCESS; isns_attr_list_scanner_init(&state, NULL, &resp->is_operating_attrs); while (1) { isns_object_t *obj; status = isns_attr_list_scanner_next(&state); if (status == ISNS_NO_SUCH_ENTRY) { status = ISNS_SUCCESS; break; } if (status) break; obj = isns_create_object(state.tmpl, &state.keys, NULL); isns_object_set_attrlist(obj, &state.attrs); if (obj != state.key_obj) isns_object_list_append(result, obj); isns_object_release(obj); } isns_attr_list_scanner_destroy(&state); return status; } /* * Print a simple message object */ void isns_simple_print(isns_simple_t *simp, isns_print_fn_t *fn) { char buffer[256]; if (fn == isns_debug_message && !isns_debug_enabled(DBG_MESSAGE)) return; fn("---%s%s---\n", isns_function_name(simp->is_function), simp->is_replace? "[REPLACE]" : ""); if (simp->is_source) { fn("Source:\n", buffer); isns_attr_print(simp->is_source->is_attr, fn); } else { fn("Source: \n"); } if (simp->is_message_attrs.ial_count == 0) { fn("Message attributes: \n"); } else { fn("Message attributes:\n"); isns_attr_list_print(&simp->is_message_attrs, fn); } if (simp->is_operating_attrs.ial_count == 0) { fn("Operating attributes: \n"); } else { fn("Operating attributes:\n"); isns_attr_list_print(&simp->is_operating_attrs, fn); } } /* * This set of functions analyzes the operating attrs of a registration, * or a query response, and chops it up into separate chunks, one * per objects. * * It always returns the keys and attrs for one object, * following the ordering constraints laid out in the RFC. */ void isns_attr_list_scanner_init(struct isns_attr_list_scanner *st, isns_object_t *key_obj, const isns_attr_list_t *attrs) { memset(st, 0, sizeof(*st)); st->orig_attrs = *attrs; st->key_obj = key_obj; } void isns_attr_list_scanner_destroy(struct isns_attr_list_scanner *st) { isns_attr_list_destroy(&st->keys); isns_attr_list_destroy(&st->attrs); memset(st, 0, sizeof(*st)); } int isns_attr_list_scanner_next(struct isns_attr_list_scanner *st) { isns_attr_t *attr; unsigned int i, pos = st->pos; isns_attr_list_destroy(&st->keys); isns_attr_list_destroy(&st->attrs); if (st->orig_attrs.ial_count <= pos) return ISNS_NO_SUCH_ENTRY; attr = st->orig_attrs.ial_data[pos]; /* handle those funky inlined PGT definitions */ if (st->pgt_next_attr && attr->ia_tag_id == st->pgt_next_attr) return isns_attr_list_scanner_get_pg(st); /* This isn't really structured programming anymore */ if (st->index_acceptable && (st->tmpl = isns_object_template_for_index_tag(attr->ia_tag_id))) goto copy_attrs; /* * Find the object template for the given key attr(s). * This function also enforces restrictions on the * order of key attributes. */ st->tmpl = isns_object_template_find(attr->ia_tag_id); if (st->tmpl == NULL) { isns_debug_protocol("%s: attr %u is not a key attr\n", __FUNCTION__, attr->ia_tag_id); return ISNS_INVALID_REGISTRATION; } /* Copy the key attrs */ for (i = 0; i < st->tmpl->iot_num_keys; ++i, ++pos) { if (pos >= st->orig_attrs.ial_count) { isns_debug_protocol("%s: incomplete %s object " "(key attr %u missing)\n", __FUNCTION__, st->tmpl->iot_name, pos); return ISNS_INVALID_REGISTRATION; } attr = st->orig_attrs.ial_data[pos]; /* Make sure key attrs are complete and in order */ if (attr->ia_tag_id != st->tmpl->iot_keys[i]) { isns_debug_protocol("%s: incomplete %s object " "(key attr %u missing)\n", __FUNCTION__, st->tmpl->iot_name, pos); return ISNS_INVALID_REGISTRATION; } isns_attr_list_append_attr(&st->keys, attr); } /* * Consume all non-key attributes corresponding to the * object class. We stop whenever we hit another * key attribute, or an attribute that does not belong to * the object type (eg when a storage node is followed by * a PGT attribute, as described in section 5.6.5.1). */ copy_attrs: while (pos < st->orig_attrs.ial_count) { uint32_t tag; attr = st->orig_attrs.ial_data[pos]; tag = attr->ia_tag_id; if (!isns_object_attr_valid(st->tmpl, tag) || isns_object_template_find(tag) != NULL) break; pos++; isns_attr_list_append_attr(&st->attrs, attr); } st->pos = pos; return ISNS_SUCCESS; } int isns_attr_list_scanner_get_pg(struct isns_attr_list_scanner *st) { isns_attr_t *attr, *next = NULL; unsigned int pos = st->pos; attr = st->orig_attrs.ial_data[st->pos++]; if (st->pgt_next_attr == ISNS_TAG_PG_TAG) { isns_object_t *base = st->pgt_base_object; if (ISNS_ATTR_IS_NIL(attr)) st->pgt_value = 0; else if (ISNS_ATTR_IS_UINT32(attr)) st->pgt_value = attr->ia_value.iv_uint32; else return ISNS_INVALID_REGISTRATION; if (ISNS_IS_PORTAL(base) && isns_portal_from_object(&st->pgt_portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, base)) { st->pgt_next_attr = ISNS_TAG_PG_ISCSI_NAME; } else if (ISNS_IS_ISCSI_NODE(base) && isns_object_get_string(base, ISNS_TAG_ISCSI_NAME, &st->pgt_iscsi_name)) { st->pgt_next_attr = ISNS_TAG_PORTAL_IP_ADDRESS; } else { return ISNS_INTERNAL_ERROR; } /* Trailing PGT at end of list. Shrug. */ if (st->pos >= st->orig_attrs.ial_count) return ISNS_NO_SUCH_ENTRY; attr = st->orig_attrs.ial_data[st->pos++]; if (attr->ia_tag_id != st->pgt_next_attr) { /* Some clients may do this; catch them so * we can fix it. */ isns_error("Oops, client sends PGT followed by <%s>\n", attr->ia_tag->it_name); return ISNS_INVALID_REGISTRATION; } } st->tmpl = &isns_iscsi_pg_template; if (st->pgt_next_attr == ISNS_TAG_PG_ISCSI_NAME) { isns_attr_list_append_attr(&st->keys, attr); isns_portal_to_attr_list(&st->pgt_portal_info, ISNS_TAG_PG_PORTAL_IP_ADDR, ISNS_TAG_PG_PORTAL_TCP_UDP_PORT, &st->keys); } else if (st->pgt_next_attr == ISNS_TAG_PG_PORTAL_IP_ADDR) { if (st->pos >= st->orig_attrs.ial_count) return ISNS_INVALID_REGISTRATION; next = st->orig_attrs.ial_data[st->pos++]; if (next->ia_tag_id != ISNS_TAG_PORTAL_TCP_UDP_PORT) return ISNS_INVALID_REGISTRATION; isns_attr_list_append_string(&st->keys, ISNS_TAG_PG_ISCSI_NAME, st->pgt_iscsi_name); isns_attr_list_append_attr(&st->keys, attr); isns_attr_list_append_attr(&st->keys, next); } else { return ISNS_INTERNAL_ERROR; } isns_attr_list_append_uint32(&st->attrs, ISNS_TAG_PG_TAG, st->pgt_value); /* Copy other PG attributes if present */ for (pos = st->pos; pos < st->orig_attrs.ial_count; ++pos) { uint32_t tag; attr = st->orig_attrs.ial_data[pos]; tag = attr->ia_tag_id; /* * Additional sets of PGTs and PG iSCSI Names to be * associated to the registered Portal MAY follow. */ if (tag == ISNS_TAG_PG_TAG) { st->pgt_next_attr = tag; break; } if (tag == ISNS_TAG_PG_ISCSI_NAME || tag == ISNS_TAG_PG_PORTAL_IP_ADDR || tag == ISNS_TAG_PG_PORTAL_TCP_UDP_PORT || !isns_object_attr_valid(st->tmpl, tag)) break; isns_attr_list_append_attr(&st->attrs, attr); } st->pos = pos; return ISNS_SUCCESS; } /* * Get the name of a function */ #define __ISNS_MAX_FUNCTION 16 static const char * isns_req_function_names[__ISNS_MAX_FUNCTION] = { [ISNS_DEVICE_ATTRIBUTE_REGISTER]= "DevAttrReg", [ISNS_DEVICE_ATTRIBUTE_QUERY] = "DevAttrQry", [ISNS_DEVICE_GET_NEXT] = "DevGetNext", [ISNS_DEVICE_DEREGISTER] = "DevDereg", [ISNS_SCN_REGISTER] = "SCNReg", [ISNS_SCN_DEREGISTER] = "SCNDereg", [ISNS_SCN_EVENT] = "SCNEvent", [ISNS_STATE_CHANGE_NOTIFICATION]= "SCN", [ISNS_DD_REGISTER] = "DDReg", [ISNS_DD_DEREGISTER] = "DDDereg", [ISNS_DDS_REGISTER] = "DDSReg", [ISNS_DDS_DEREGISTER] = "DDSDereg", [ISNS_ENTITY_STATUS_INQUIRY] = "ESI", [ISNS_HEARTBEAT] = "Heartbeat", }; static const char * isns_resp_function_names[__ISNS_MAX_FUNCTION] = { [ISNS_DEVICE_ATTRIBUTE_REGISTER]= "DevAttrRegResp", [ISNS_DEVICE_ATTRIBUTE_QUERY] = "DevAttrQryResp", [ISNS_DEVICE_GET_NEXT] = "DevGetNextResp", [ISNS_DEVICE_DEREGISTER] = "DevDeregResp", [ISNS_SCN_REGISTER] = "SCNRegResp", [ISNS_SCN_DEREGISTER] = "SCNDeregResp", [ISNS_SCN_EVENT] = "SCNEventResp", [ISNS_STATE_CHANGE_NOTIFICATION]= "SCNResp", [ISNS_DD_REGISTER] = "DDRegResp", [ISNS_DD_DEREGISTER] = "DDDeregResp", [ISNS_DDS_REGISTER] = "DDSRegResp", [ISNS_DDS_DEREGISTER] = "DDSDeregResp", [ISNS_ENTITY_STATUS_INQUIRY] = "ESIRsp", /* No response code for heartbeat */ }; const char * isns_function_name(uint32_t function) { static char namebuf[32]; const char **names, *name; unsigned int num = function; names = isns_req_function_names; if (num & 0x8000) { names = isns_resp_function_names; num &= 0x7fff; } name = NULL; if (num < __ISNS_MAX_FUNCTION) name = names[num]; if (name == NULL) { snprintf(namebuf, sizeof(namebuf), "", function); name = namebuf; } return name; } open-iscsi-2.0.873/utils/open-isns/slp.c000066400000000000000000000111311175631155400177660ustar00rootroot00000000000000/* * SLP registration and query of iSNS * * Copyright (C) 2007 Olaf Kirch */ #include "config.h" #include #ifdef HAVE_SLP_H # include #endif #include "isns.h" #include "util.h" #include "internal.h" #define ISNS_SLP_SERVICE_NAME "iscsi:sms" /* * RFC 4018 says we would use scope initiator-scope-list. * But don't we want targets to find the iSNS server, too? */ #define ISNS_SLP_SCOPE "initiator-scope-list" #ifdef WITH_SLP struct isns_slp_url_state { SLPError slp_err; char * slp_url; }; static void isns_slp_report(SLPHandle handle, SLPError err, void *cookie) { *(SLPError *) cookie = err; } /* * Register a service with SLP */ int isns_slp_register(const char *url) { SLPError err, callbackerr; SLPHandle handle = NULL; err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return 0; } err = SLPReg(handle, url, SLP_LIFETIME_MAXIMUM, ISNS_SLP_SCOPE, "(description=iSNS Server),(protocols=isns)", SLP_TRUE, isns_slp_report, &callbackerr); SLPClose(handle); if (err == SLP_OK) err = callbackerr; if (err != SLP_OK) { isns_error("Failed to register with SLP (err %d)\n", err); return 0; } return 1; } /* * DeRegister a service */ int isns_slp_unregister(const char *url) { SLPError err, callbackerr; SLPHandle handle = NULL; isns_debug_general("SLP: Unregistering \"%s\"\n", url); err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return 0; } err = SLPDereg(handle, url, isns_slp_report, &callbackerr); SLPClose(handle); if (err == SLP_OK) err = callbackerr; if (err != SLP_OK) { isns_error("Failed to deregister with SLP (err %d)\n", err); return 0; } return 1; } /* * Find an iSNS server through SLP */ static SLPBoolean isns_slp_url_callback(SLPHandle handle, const char *url, unsigned short lifetime, SLPError err, void *cookie) { struct isns_slp_url_state *sp = cookie; SLPSrvURL *parsed_url = NULL; int want_more = SLP_TRUE; char buffer[1024]; if (err != SLP_OK && err != SLP_LAST_CALL) return SLP_FALSE; if (!url) goto out; isns_debug_general("SLP: Found URL \"%s\"\n", url); err = SLPParseSrvURL(url, &parsed_url); if (err != SLP_OK) { isns_error("Error parsing SLP service URL \"%s\"\n", url); goto out; } if (parsed_url->s_pcNetFamily && parsed_url->s_pcNetFamily[0] && strcasecmp(parsed_url->s_pcNetFamily, "ip")) { isns_error("Ignoring SLP service URL \"%s\"\n", url); goto out; } if (parsed_url->s_iPort) { snprintf(buffer, sizeof(buffer), "%s:%u", parsed_url->s_pcHost, parsed_url->s_iPort); isns_assign_string(&sp->slp_url, buffer); } else { isns_assign_string(&sp->slp_url, parsed_url->s_pcHost); } want_more = SLP_FALSE; out: if (parsed_url) SLPFree(parsed_url); sp->slp_err = SLP_OK; return want_more; } /* * Locate the iSNS server using SLP. * This is not really an instantaneous process. Maybe we could * speed this up by using a cache. */ char * isns_slp_find(void) { static struct isns_slp_url_state state; SLPHandle handle = NULL; SLPError err; if (state.slp_url) return state.slp_url; isns_debug_general("Using SLP to locate iSNS server\n"); err = SLPOpen("en", SLP_FALSE, &handle); if(err != SLP_OK) { isns_error("Unable to obtain SLP handle (err %d)\n", err); return NULL; } err = SLPFindSrvs(handle, ISNS_SLP_SERVICE_NAME, NULL, "(protocols=isns)", isns_slp_url_callback, &state); SLPClose(handle); if (err == SLP_OK) err = state.slp_err; if (err != SLP_OK) { isns_error("Failed to find service in SLP (err %d)\n", err); return NULL; } if (state.slp_url == NULL) { isns_error("Service %s not registered with SLP\n", ISNS_SLP_SERVICE_NAME); return NULL; } isns_debug_general("Using iSNS server at %s\n", state.slp_url); return state.slp_url; } #else /* WITH_SLP */ int isns_slp_register(const char *url) { isns_error("SLP support disabled in this build\n"); return 0; } int isns_slp_unregister(const char *url) { isns_error("SLP support disabled in this build\n"); return 0; } char * isns_slp_find(void) { isns_error("SLP support disabled in this build\n"); return NULL; } #endif /* WITH_SLP */ char * isns_slp_build_url(uint16_t port) { char buffer[1024]; if (port) snprintf(buffer, sizeof(buffer), "service:%s://%s:%u", ISNS_SLP_SERVICE_NAME, isns_config.ic_host_name, port); else snprintf(buffer, sizeof(buffer), "service:%s://%s", ISNS_SLP_SERVICE_NAME, isns_config.ic_host_name); return isns_strdup(buffer); } open-iscsi-2.0.873/utils/open-isns/socket.c000066400000000000000000001462061175631155400204740ustar00rootroot00000000000000/* * Socket handling code * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "buffer.h" #include "isns.h" #include "socket.h" #include "security.h" #include "util.h" #include "config.h" #define SOCK_DEBUG_VERBOSE 0 #ifndef AI_ADDRCONFIG # define AI_ADDRCONFIG 0 #endif #ifndef AI_V4MAPPED # define AI_V4MAPPED 0 #endif enum { ISNS_MSG_DISCARD, ISNS_MSG_DONE, ISNS_MSG_RETURN }; static isns_socket_t *__isns_create_socket(struct addrinfo *src, struct addrinfo *dst, int sock_type); static struct addrinfo *isns_get_address_list(const char *, const char *, int, int, int); static void release_addrinfo(struct addrinfo *); static void isns_net_dgram_recv(isns_socket_t *); static void isns_net_dgram_xmit(isns_socket_t *); static void isns_net_stream_accept(isns_socket_t *); static void isns_net_stream_recv(isns_socket_t *); static void isns_net_stream_xmit(isns_socket_t *); static void isns_net_stream_hup(isns_socket_t *); static void isns_net_stream_error(isns_socket_t *, int); static void isns_net_stream_reconnect(isns_socket_t *); static void isns_net_stream_disconnect(isns_socket_t *); static isns_socket_t *isns_net_alloc(int); static int isns_socket_open(isns_socket_t *); static int isns_socket_queue_message(isns_socket_t *, isns_message_t *); static int isns_socket_retransmit_queued(isns_socket_t *); static ISNS_LIST_DECLARE(all_sockets); #define debug_verbose(args ...) do { \ if (SOCK_DEBUG_VERBOSE >= 1) isns_debug_socket(args); \ } while (0) #define debug_verbose2(args ...) do { \ if (SOCK_DEBUG_VERBOSE >= 2) isns_debug_socket(args); \ } while (0) /* * Helper function for looking at incoming PDUs */ static inline buf_t * isns_socket_next_pdu(isns_socket_t *sock) { buf_t *bp = sock->is_recv_buf; unsigned int avail; struct isns_hdr *hdr; uint32_t pdu_len = 0; if (bp == NULL) return NULL; avail = buf_avail(bp); if (avail < sizeof(*hdr)) return NULL; hdr = buf_head(bp); pdu_len = sizeof(*hdr) + ntohs(hdr->i_length); if (avail < pdu_len) return NULL; /* Check for presence of authentication block */ if (hdr->i_flags & htons(ISNS_F_AUTHBLK_PRESENT)) { uint32_t *authblk, authlen; authblk = (uint32_t *) ((char *) hdr + pdu_len); if (avail < pdu_len + ISNS_AUTHBLK_SIZE) return NULL; authlen = ntohl(authblk[1]); if (authlen < 20 || authlen > ISNS_MAX_MESSAGE) { /* The authblock is garbage. * The only reliable way to signal such a problem * is by dropping the connection. */ isns_error("socket error: bad auth block\n"); sock->is_state = ISNS_SOCK_DEAD; return NULL; } pdu_len += authlen; if (avail < pdu_len) return NULL; } return buf_split(&sock->is_recv_buf, pdu_len); } /* * Try to assemble the message from PDUs */ static inline int isns_msg_complete(struct isns_partial_msg *msg) { buf_t *msg_buf, **chain, *bp; /* Return if we haven't seen first and last frag */ if (((~msg->imp_flags) & (ISNS_F_FIRST_PDU|ISNS_F_LAST_PDU))) return 0; /* Simple - unfragmented case: just move * the PDU on the chain to the payload */ if (msg->imp_first_seq == msg->imp_last_seq) { msg->imp_payload = msg->imp_chain; buf_pull(msg->imp_payload, sizeof(struct isns_hdr)); msg->imp_chain = NULL; return 1; } /* Do we have all fragments? */ if (msg->imp_last_seq - msg->imp_first_seq + 1 != msg->imp_pdu_count) return 0; msg_buf = buf_alloc(msg->imp_msg_size); chain = &msg->imp_chain; while ((bp = *chain) != NULL) { /* Pull the header off */ buf_pull(bp, sizeof(struct isns_hdr)); buf_put(msg_buf, buf_head(bp), buf_avail(bp)); *chain = bp->next; buf_free(bp); } return 0; } /* * Clear the "partial" part of the message */ static void __isns_msg_clear_partial(struct isns_partial_msg *msg) { buf_list_free(msg->imp_chain); msg->imp_chain = NULL; } /* * Add an authentication block to an outgoing PDU */ #ifdef WITH_SECURITY static int isns_pdu_seal(isns_security_t *ctx, buf_t *pdu) { struct isns_authblk auth; isns_principal_t *self; if (!(self = ctx->is_self)) { isns_error("Cannot sign PDU: no sender identity for socket\n"); return 0; } auth.iab_bsd = ctx->is_type; auth.iab_timestamp = time(NULL); auth.iab_spi = self->is_name; auth.iab_spi_len = strlen(self->is_name); if (!isns_security_sign(ctx, self, pdu, &auth)) { isns_error("Cannot sign PDU: error creating signature\n"); return 0; } auth.iab_length = ISNS_AUTHBLK_SIZE + auth.iab_spi_len + auth.iab_sig_len; if (!isns_authblock_encode(pdu, &auth)) return 0; isns_debug_message("Successfully signed message (authlen=%u, spilen=%u, siglen=%u)\n", auth.iab_length, auth.iab_spi_len, auth.iab_sig_len); return 1; } /* * Authenticate a PDU * * The RFC is doing a bit of handwaving around the * authentication issue. For example, it never * spells out exactly which parts of the message * are included in the SHA1 hash to be signed. * * It also says that the auth block "is identical in format * to the SLP authentication block", but all fields * are twice as wide. * * There's not even an error code to tell the client * we were unable to authenticate him :-( * * Interoperability problems, here I come... */ static int isns_pdu_authenticate(isns_security_t *sec, struct isns_partial_msg *msg, buf_t *bp) { struct isns_hdr *hdr = buf_head(bp); unsigned int pdu_len, avail; struct isns_authblk authblk; isns_principal_t * peer = NULL; buf_t auth_buf; isns_debug_auth("Message has authblock; trying to authenticate\n"); /* In the TCP path, we checked this before, but * better safe than sorry. */ avail = buf_avail(bp); pdu_len = sizeof(*hdr) + ntohs(hdr->i_length); if (avail < pdu_len + ISNS_AUTHBLK_SIZE) { isns_debug_auth("authblock truncated\n"); return 0; } /* Get the auth block */ buf_set(&auth_buf, buf_head(bp) + pdu_len, avail - pdu_len); if (!isns_authblock_decode(&auth_buf, &authblk)) { isns_debug_auth("error decoding authblock\n"); return 0; } /* Truncate the buffer (this just sets the * tail pointer, but doesn't free memory */ if (!buf_truncate(bp, pdu_len)) { isns_debug_auth("buf_truncate failed - cosmic particles?\n"); return 0; } /* If the socket doesn't have a security context, * just ignore the auth block. */ if (sec == NULL) { msg->imp_header.i_flags &= ~ISNS_F_AUTHBLK_PRESENT; return 1; } if (authblk.iab_bsd != sec->is_type) goto failed; peer = isns_get_principal(sec, authblk.iab_spi, authblk.iab_spi_len); if (peer == NULL) { /* If the admin allows unknown peers, we must make * sure, however, to not allow an unauthenticated * PDU to be inserted into an authenticated message. */ if (isns_config.ic_auth.allow_unknown_peers && msg->imp_security == NULL) { isns_debug_message( "Accepting unknown peer spi=\"%.*s\" as " "anonymous peer\n", authblk.iab_spi_len, authblk.iab_spi); return 1; } isns_debug_message( "Unable to create security peer for spi=%.*s\n", authblk.iab_spi_len, authblk.iab_spi); goto failed; } if (!isns_security_verify(sec, peer, bp, &authblk)) { /* Authentication failed */ goto failed; } /* The RFC doesn't say how to deal with fragmented * messages with different BSDs or SPIs. * kickban seems the right approach. * We discard this segment rather than failing * the entire message. */ if (msg->imp_chain == NULL) { msg->imp_security = peer; peer->is_users++; } else if (msg->imp_security != peer) { goto failed; } isns_principal_free(peer); return 1; failed: isns_principal_free(peer); return 0; } #else /* WITH_SECURITY */ static int isns_pdu_authenticate(isns_security_t *sec, struct isns_partial_msg *msg, buf_t *bp) { return 0; } #endif /* * Enqueue an incoming PDU on the socket. * * A single iSNS message may be split up into * several PDUs, so we need to perform * reassembly here. * * This function also verifies the authentication * block, if present. */ static void isns_pdu_enqueue(isns_socket_t *sock, struct sockaddr_storage *addr, socklen_t alen, buf_t *segment, struct ucred *creds) { isns_message_queue_t *q = &sock->is_partial; struct isns_partial_msg *msg; buf_t **chain, *bp; struct isns_hdr *hdr; uint32_t xid, seq, flags; hdr = (struct isns_hdr *) buf_head(segment); xid = ntohs(hdr->i_xid); seq = ntohs(hdr->i_seq); flags = ntohs(hdr->i_flags); isns_debug_socket("Incoming PDU xid=%04x seq=%u len=%u func=%s%s%s%s%s%s\n", xid, seq, ntohs(hdr->i_length), isns_function_name(ntohs(hdr->i_function)), (flags & ISNS_F_CLIENT)? " client" : "", (flags & ISNS_F_SERVER)? " server" : "", (flags & ISNS_F_AUTHBLK_PRESENT)? " authblk" : "", (flags & ISNS_F_FIRST_PDU)? " first" : "", (flags & ISNS_F_LAST_PDU)? " last" : ""); /* Find the message matching (addr, xid) */ msg = (struct isns_partial_msg *) isns_message_queue_find(q, xid, addr, alen); if (msg != NULL) { if (msg->imp_creds && (!creds || memcmp(msg->imp_creds, creds, sizeof(*creds)))) { isns_warning("socket: credentials mismatch! Dropping PDU\n"); goto drop; } hdr = &msg->imp_header; goto found; } msg = (struct isns_partial_msg *) __isns_alloc_message(xid, sizeof(*msg), (void (*)(isns_message_t *)) __isns_msg_clear_partial); memcpy(&msg->imp_addr, addr, alen); msg->imp_addrlen = alen; msg->imp_header = *hdr; msg->imp_header.i_seq = 0; isns_message_queue_append(q, &msg->imp_base); isns_message_release(&msg->imp_base); /* Message is owned by is_partial now */ /* Fix up the PDU header */ hdr = &msg->imp_header; hdr->i_version = ntohs(hdr->i_version); hdr->i_function = ntohs(hdr->i_function); hdr->i_length = ntohs(hdr->i_length); hdr->i_flags = ntohs(hdr->i_flags); hdr->i_xid = ntohs(hdr->i_xid); hdr->i_seq = ntohs(hdr->i_seq); if (creds) { msg->imp_credbuf = *creds; msg->imp_creds = &msg->imp_credbuf; } found: if (flags & ISNS_F_AUTHBLK_PRESENT) { /* When authentication fails - should we drop the * message or treat it as unauthenticated? * For now we drop it, but a more user friendly * approach might be to just treat it as * unauthenticated. */ if (!isns_pdu_authenticate(sock->is_security, msg, segment)) goto drop; } else if (msg->imp_header.i_flags & ISNS_F_AUTHBLK_PRESENT) { /* Oops, unauthenticated fragment in an * authenticated message. */ isns_debug_message( "Oops, unauthenticated fragment in an " "authenticated message!\n"); goto drop; } if ((flags & ISNS_F_FIRST_PDU) && !(msg->imp_flags & ISNS_F_FIRST_PDU)) { /* FIXME: first seq must be zero */ msg->imp_first_seq = seq; msg->imp_flags |= ISNS_F_FIRST_PDU; } if ((flags & ISNS_F_LAST_PDU) && !(msg->imp_flags & ISNS_F_LAST_PDU)) { msg->imp_last_seq = seq; msg->imp_flags |= ISNS_F_LAST_PDU; } chain = &msg->imp_chain; while ((bp = *chain) != NULL) { struct isns_hdr *ohdr = buf_head(bp); /* Duplicate? Drop it! */ if (seq == ohdr->i_seq) goto drop; if (seq < ohdr->i_seq) break; chain = &bp->next; } segment->next = *chain; *chain = segment; msg->imp_msg_size += buf_avail(segment) - sizeof(*hdr); msg->imp_pdu_count++; /* We received first and last PDU - check if the * chain is complete */ if (isns_msg_complete(msg)) { /* Remove from partial queue. * We clean the part of the message that is * not in imp_base, so that we can pass this * to the caller and have him call * isns_message_release on it. */ __isns_msg_clear_partial(msg); /* Move from partial queue to complete queue. */ isns_message_queue_move(&sock->is_complete, &msg->imp_base); msg->imp_base.im_socket = sock; } return; drop: buf_free(segment); return; } /* * Send side handling */ static void isns_send_update(isns_socket_t *sock) { buf_t *bp = sock->is_xmit_buf; if (bp && buf_avail(bp) == 0) { sock->is_xmit_buf = bp->next; buf_free(bp); } if (sock->is_xmit_buf) sock->is_poll_mask |= POLLOUT; else sock->is_poll_mask &= ~POLLOUT; } /* * Close the socket */ static void isns_net_close(isns_socket_t *sock, int next_state) { if (sock->is_desc >= 0) { close(sock->is_desc); sock->is_desc = -1; } sock->is_poll_mask &= ~(POLLIN|POLLOUT); sock->is_state = next_state; buf_list_free(sock->is_xmit_buf); sock->is_xmit_buf = NULL; buf_free(sock->is_recv_buf); sock->is_recv_buf = NULL; isns_message_queue_destroy(&sock->is_partial); isns_message_queue_destroy(&sock->is_complete); } static void isns_net_set_timeout(isns_socket_t *sock, void (*func)(isns_socket_t *), unsigned int timeout) { gettimeofday(&sock->is_deadline, NULL); sock->is_deadline.tv_sec += timeout; sock->is_timeout = func; } static void isns_net_cancel_timeout(isns_socket_t *sock) { timerclear(&sock->is_deadline); } void isns_net_error(isns_socket_t *sock, int err_code) { if (sock->is_error) sock->is_error(sock, err_code); } /* * Create a passive socket (server side) */ isns_socket_t * isns_create_server_socket(const char *src_spec, const char *portspec, int af_hint, int sock_type) { struct addrinfo *src; src = isns_get_address_list(src_spec, portspec, af_hint, sock_type, AI_PASSIVE); if (src == NULL) return NULL; return __isns_create_socket(src, NULL, sock_type); } /* * Accept incoming connections. */ void isns_net_stream_accept(isns_socket_t *sock) { isns_socket_t *child; socklen_t optlen; int fd, passcred = 0; fd = accept(sock->is_desc, NULL, NULL); if (fd < 0) { if (errno != EINTR) isns_error("Error accepting connection: %m\n"); return; } optlen = sizeof(passcred); if (getsockopt(sock->is_desc, SOL_SOCKET, SO_PASSCRED, &passcred, &optlen) >= 0) { setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred)); } child = isns_net_alloc(fd); child->is_type = SOCK_STREAM; child->is_autoclose = 1; child->is_disconnect_fatal = 1; child->is_poll_in = isns_net_stream_recv; child->is_poll_out = isns_net_stream_xmit; child->is_poll_hup = isns_net_stream_hup; child->is_error = isns_net_stream_error; child->is_poll_mask = POLLIN|POLLHUP; child->is_security = sock->is_security; if (isns_config.ic_network.idle_timeout) isns_net_set_timeout(child, isns_net_stream_disconnect, isns_config.ic_network.idle_timeout); isns_list_append(&all_sockets, &child->is_list); } /* * This is called from the socket code when it detects * an error condition. */ static void isns_net_stream_error(isns_socket_t *sock, int err_code) { int timeo = 0, next_state = ISNS_SOCK_DEAD; if (err_code == EAGAIN) return; isns_debug_socket("isns_net_stream_error: %s\n", strerror(err_code)); switch (err_code) { case EINTR: /* ignored */ return; case ECONNREFUSED: case ECONNRESET: case EHOSTUNREACH: case ENETUNREACH: case ENOTCONN: case EPIPE: if (sock->is_disconnect_fatal) { isns_warning("socket disconnect, killing socket\n"); break; } /* fallthrough to disconnect */ timeo = isns_config.ic_network.reconnect_timeout; case ETIMEDOUT: /* Disconnect and try to reconnect */ if (sock->is_client) { /* FIXME: We don't want this warning for ESI and * SCN sockets on the server side. */ isns_warning("socket disconnect, retrying in %u sec\n", timeo); isns_net_set_timeout(sock, isns_net_stream_reconnect, timeo); next_state = ISNS_SOCK_DISCONNECTED; break; } /* fallthru */ default: isns_error("socket error: %s\n", strerror(err_code)); } /* Close the socket right away */ isns_net_close(sock, next_state); } /* * recvmsg wrapper handling SCM_CREDENTIALS passing */ static int isns_net_recvmsg(isns_socket_t *sock, void *buffer, size_t count, struct sockaddr *addr, socklen_t *alen, struct ucred **cred) { static struct ucred cred_buf; unsigned int control[128]; struct cmsghdr *cmsg; struct msghdr msg; struct iovec iov; int len; *cred = NULL; iov.iov_base = buffer; iov.iov_len = count; memset(&msg, 0, sizeof(msg)); msg.msg_name = addr; msg.msg_namelen = *alen; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control; msg.msg_controllen = sizeof(control); len = recvmsg(sock->is_desc, &msg, MSG_DONTWAIT); if (len < 0) return len; cmsg = CMSG_FIRSTHDR(&msg); while (cmsg) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) { memcpy(&cred_buf, CMSG_DATA(cmsg), sizeof(cred_buf)); *cred = &cred_buf; break; } cmsg = CMSG_NXTHDR(&msg, cmsg); } *alen = msg.msg_namelen; return len; } void isns_net_stream_recv(isns_socket_t *sock) { unsigned char buffer[ISNS_MAX_BUFFER]; struct sockaddr_storage addr; struct ucred *creds = NULL; socklen_t alen = sizeof(addr); buf_t *bp; size_t count, total = 0; int len; again: if ((bp = sock->is_recv_buf) == NULL) { bp = buf_alloc(ISNS_MAX_MESSAGE); sock->is_recv_buf = bp; } if ((count = buf_tailroom(bp)) > sizeof(buffer)) count = sizeof(buffer); if (count == 0) { /* Message too large */ isns_net_stream_error(sock, EMSGSIZE); return; } #if 0 len = recvfrom(sock->is_desc, buffer, count, MSG_DONTWAIT, (struct sockaddr *) &addr, &alen); #else len = isns_net_recvmsg(sock, buffer, count, (struct sockaddr *) &addr, &alen, &creds); #endif if (len < 0) { isns_net_stream_error(sock, errno); return; } if (len == 0) { if (total == 0) sock->is_poll_mask &= ~POLLIN; return; } /* We received some data from client, re-arm the * idle disconnect timer */ if (sock->is_autoclose && isns_config.ic_network.idle_timeout) isns_net_set_timeout(sock, isns_net_stream_disconnect, isns_config.ic_network.idle_timeout); buf_put(bp, buffer, len); total += len; /* Chop up the recv buffer into PDUs */ while ((bp = isns_socket_next_pdu(sock)) != NULL) { /* We have a full PDU; enqueue it */ /* We shouldn't have more than one partial message * on a TCP connection; we could check this here. */ isns_pdu_enqueue(sock, &addr, alen, bp, creds); } goto again; } void isns_net_stream_xmit(isns_socket_t *sock) { unsigned int count; buf_t *bp = sock->is_xmit_buf; int len; /* If a connecting socket can send, it has * the TCP three-way handshake. */ if (sock->is_state == ISNS_SOCK_CONNECTING) { sock->is_state = ISNS_SOCK_IDLE; sock->is_poll_mask |= POLLIN; isns_net_cancel_timeout(sock); } if (bp == NULL) return; count = buf_avail(bp); len = send(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT); if (len < 0) { isns_net_stream_error(sock, errno); return; } debug_verbose("isns_net_stream_xmit(%p, count=%u): transmitted %d\n", sock, count, len); buf_pull(bp, len); isns_send_update(sock); } void isns_net_stream_hup(isns_socket_t *sock) { sock->is_poll_mask &= ~(POLLIN|POLLOUT); /* POLLHUP while connecting means we failed */ if (sock->is_state == ISNS_SOCK_CONNECTING) isns_net_stream_error(sock, ECONNREFUSED); } /* * Clone an addrinfo list */ static struct addrinfo * clone_addrinfo(const struct addrinfo *ai) { struct addrinfo *res = NULL, **p; p = &res; for (; ai; ai = ai->ai_next) { struct addrinfo *new; if (ai->ai_addrlen > sizeof(struct sockaddr_storage)) continue; new = isns_calloc(1, sizeof(*new) + ai->ai_addrlen); new->ai_family = ai->ai_family; new->ai_socktype = ai->ai_socktype; new->ai_protocol = ai->ai_protocol; new->ai_addrlen = ai->ai_addrlen; new->ai_addr = (struct sockaddr *) (new + 1); memcpy(new->ai_addr, ai->ai_addr, new->ai_addrlen); *p = new; p = &new->ai_next; } return res; } static struct addrinfo * __make_addrinfo(const struct sockaddr *ap, socklen_t alen, int socktype) { struct addrinfo *new; new = isns_calloc(1, sizeof(*new) + alen); new->ai_family = ap->sa_family; new->ai_socktype = socktype; new->ai_protocol = 0; new->ai_addrlen = alen; new->ai_addr = (struct sockaddr *) (new + 1); memcpy(new->ai_addr, ap, alen); return new; } static struct addrinfo * make_addrinfo_unix(const char *pathname, int socktype) { unsigned int len = strlen(pathname); struct sockaddr_un sun; if (len + 1 > sizeof(sun.sun_path)) { isns_error("Can't set AF_LOCAL address: path too long!\n"); return NULL; } sun.sun_family = AF_LOCAL; strcpy(sun.sun_path, pathname); return __make_addrinfo((struct sockaddr *) &sun, SUN_LEN(&sun) + 1, socktype); } static struct addrinfo * make_addrinfo_any(int family, int socktype) { struct sockaddr_storage addr = { .ss_family = AF_UNSPEC }; struct addrinfo *res; if (family != AF_UNSPEC) { addr.ss_family = family; res = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype); } else { addr.ss_family = AF_INET6; res = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype); addr.ss_family = AF_INET; res->ai_next = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype); } return res; } /* * Release addrinfo created by functions above. * We cannot use freeaddrinfo, as we don't know how it * is implemented. */ static void release_addrinfo(struct addrinfo *ai) { struct addrinfo *next; for (; ai; ai = next) { next = ai->ai_next; isns_free(ai); } } static void __isns_sockaddr_set_current(struct __isns_socket_addr *info, const struct addrinfo *ai) { if (!ai) return; /* Cannot overflow; we check addrlen in clone_addrinfo */ memcpy(&info->addr, ai->ai_addr, ai->ai_addrlen); info->addrlen = ai->ai_addrlen; } static void isns_sockaddr_init(struct __isns_socket_addr *info, struct addrinfo *ai) { if (ai == NULL) return; __isns_sockaddr_set_current(info, ai); /* keep a copy so that we can loop through * all addrs */ info->list = ai; /* Make the list circular */ while (ai->ai_next) ai = ai->ai_next; ai->ai_next = info->list; } static void isns_sockaddr_destroy(struct __isns_socket_addr *info) { struct addrinfo *ai, *next; if ((ai = info->list) != NULL) { /* Break the circular list */ info->list = NULL; next = ai->ai_next; ai->ai_next = NULL; isns_assert(next); /* Can't use freeaddrinfo on homegrown * addrinfo lists. */ release_addrinfo(next); } } static int isns_sockaddr_set_next(struct __isns_socket_addr *info) { struct addrinfo *ai; if (!(ai = info->list)) return 0; info->list = ai->ai_next; __isns_sockaddr_set_current(info, info->list); return 1; } /* * This function is used to pick a matching source address * when connecting to some server. */ static int isns_sockaddr_select(struct __isns_socket_addr *info, const struct sockaddr_storage *hint) { struct addrinfo *head = info->list, *ai; if (info->list == NULL) return 0; if (hint->ss_family == AF_INET6) { struct addrinfo *good = NULL, *best = NULL; ai = head; do { if (ai->ai_family == AF_INET) { /* Possible improvement: when * destination is not a private network, * prefer non-private source. */ good = ai; } else if (ai->ai_family == AF_INET6) { /* Possible improvement: prefer IPv6 addr * with same address scope (local, global) */ best = ai; break; } ai = ai->ai_next; } while (ai != head); if (!best) best = good; if (best) { __isns_sockaddr_set_current(info, best); return 1; } } else if (hint->ss_family == AF_INET || hint->ss_family == AF_LOCAL) { ai = head; do { if (ai->ai_family == hint->ss_family) { __isns_sockaddr_set_current(info, ai); return 1; } ai = ai->ai_next; } while (ai != head); } return 0; } void isns_net_stream_reconnect(isns_socket_t *sock) { struct sockaddr *addr = (struct sockaddr *) &sock->is_dst.addr; debug_verbose("isns_net_stream_reconnect(%p)\n", sock); /* If we timed out while connecting, close the socket * and try again. */ if (sock->is_state == ISNS_SOCK_CONNECTING) { isns_net_close(sock, ISNS_SOCK_DISCONNECTED); isns_sockaddr_set_next(&sock->is_dst); } if (!isns_socket_open(sock)) { isns_error("isns_net_stream_reconnect: cannot create socket\n"); sock->is_state = ISNS_SOCK_DEAD; return; } if (connect(sock->is_desc, addr, sock->is_dst.addrlen) >= 0) { sock->is_state = ISNS_SOCK_IDLE; sock->is_poll_mask |= POLLIN; } else if (errno == EINTR || errno == EINPROGRESS) { sock->is_state = ISNS_SOCK_CONNECTING; isns_net_set_timeout(sock, isns_net_stream_reconnect, isns_config.ic_network.connect_timeout); sock->is_poll_mask |= POLLOUT; } else { isns_net_stream_error(sock, errno); return; } /* We're connected, or in the process of doing so. * Check if there are any pending messages, and * retransmit them. */ isns_socket_retransmit_queued(sock); } void isns_net_stream_disconnect(isns_socket_t *sock) { isns_debug_socket("Disconnecting idle socket\n"); isns_net_close(sock, ISNS_SOCK_DEAD); } /* * Datagram send/recv */ static int isns_net_dgram_connect(isns_socket_t *sock) { return connect(sock->is_desc, (struct sockaddr *) &sock->is_dst.addr, sock->is_dst.addrlen); } void isns_net_dgram_recv(isns_socket_t *sock) { unsigned char buffer[ISNS_MAX_BUFFER]; struct sockaddr_storage addr; socklen_t alen = sizeof(addr); buf_t *bp; int len; len = recvfrom(sock->is_desc, buffer, sizeof(buffer), MSG_DONTWAIT, (struct sockaddr *) &addr, &alen); if (len < 0) { isns_error("recv: %m\n"); return; } if (len == 0) return; bp = buf_alloc(len); if (bp == NULL) return; buf_put(bp, buffer, len); isns_pdu_enqueue(sock, &addr, alen, bp, NULL); } void isns_net_dgram_xmit(isns_socket_t *sock) { unsigned int count; buf_t *bp = sock->is_xmit_buf; int len; count = buf_avail(bp); if (bp->addrlen) { len = sendto(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT, (struct sockaddr *) &bp->addr, bp->addrlen); } else { len = sendto(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT, NULL, 0); } /* Even if sendto failed, we will pull the pending buffer * off the send chain. Else we'll loop forever on an * unreachable host. */ if (len < 0) isns_error("send: %m\n"); buf_pull(bp, count); isns_send_update(sock); } /* * Bind socket to random port */ static int __isns_socket_bind_random(int fd, const struct sockaddr *orig_addr, socklen_t src_len) { struct sockaddr_storage addr; struct sockaddr *src_addr; uint16_t min = 888, max = 1024; unsigned int loop = 0; /* Copy the address to a writable location */ isns_assert(src_len <= sizeof(addr)); memcpy(&addr, orig_addr, src_len); src_addr = (struct sockaddr *) &addr; /* Bind to a random port */ do { uint16_t port; port = random(); port = min + (port % (max - min)); isns_addr_set_port(src_addr, port); if (bind(fd, src_addr, src_len) == 0) return 1; if (errno == EACCES && min < 1024) { min = 1024; max = 65535; continue; } } while (errno == EADDRINUSE && ++loop < 128); isns_error("Unable to bind socket\n"); return 0; } /* * Create a socket */ isns_socket_t * __isns_create_socket(struct addrinfo *src, struct addrinfo *dst, int sock_type) { isns_socket_t *sock; sock = isns_net_alloc(-1); sock->is_type = sock_type; /* Set address lists */ isns_sockaddr_init(&sock->is_dst, dst); isns_sockaddr_init(&sock->is_src, src); if (dst) { /* This is an outgoing connection. */ sock->is_client = 1; if (!isns_socket_open(sock)) goto failed; if (sock_type == SOCK_DGRAM) { sock->is_poll_in = isns_net_dgram_recv; sock->is_poll_out = isns_net_dgram_xmit; sock->is_poll_mask = POLLIN; sock->is_retrans_timeout = isns_config.ic_network.udp_retrans_timeout; while (isns_net_dgram_connect(sock) < 0) { if (isns_sockaddr_set_next(&sock->is_dst) && sock->is_dst.list != dst) continue; isns_error("Unable to connect: %m\n"); goto failed; } } else { /* Stream socket */ sock->is_poll_in = isns_net_stream_recv; sock->is_poll_out = isns_net_stream_xmit; sock->is_poll_hup = isns_net_stream_hup; sock->is_error = isns_net_stream_error; sock->is_poll_mask = POLLHUP; sock->is_retrans_timeout = isns_config.ic_network.tcp_retrans_timeout; isns_net_stream_reconnect(sock); } } else { if (!isns_socket_open(sock)) goto failed; if (sock_type == SOCK_DGRAM) { sock->is_poll_in = isns_net_dgram_recv; sock->is_poll_out = isns_net_dgram_xmit; sock->is_state = ISNS_SOCK_IDLE; } else { sock->is_poll_in = isns_net_stream_accept; sock->is_error = isns_net_stream_error; sock->is_state = ISNS_SOCK_LISTENING; } sock->is_poll_mask = POLLIN; } isns_list_append(&all_sockets, &sock->is_list); return sock; failed: isns_socket_free(sock); return NULL; } /* * Connect to the master process */ isns_socket_t * isns_create_bound_client_socket(const char *src_spec, const char *dst_spec, const char *portspec, int af_hint, int sock_type) { struct addrinfo *src = NULL, *dst; if (src_spec) { src = isns_get_address_list(src_spec, NULL, af_hint, sock_type, 0); if (src == NULL) return NULL; } dst = isns_get_address_list(dst_spec, portspec, af_hint, sock_type, 0); if (dst == NULL) { release_addrinfo(src); return NULL; } return __isns_create_socket(src, dst, sock_type); } isns_socket_t * isns_create_client_socket(const char *dst_spec, const char *portspec, int af_hint, int sock_type) { return isns_create_bound_client_socket(NULL, dst_spec, portspec, af_hint, sock_type); } static inline int isns_socket_type_from_portal(const isns_portal_info_t *info) { switch (info->proto) { case IPPROTO_TCP: return SOCK_STREAM; case IPPROTO_UDP: return SOCK_DGRAM; default: isns_error("Unknown protocol %d in portal\n", info->proto); } return -1; } isns_socket_t * isns_connect_to_portal(const isns_portal_info_t *info) { struct sockaddr_storage dst_addr; struct addrinfo *ai; int dst_alen, sock_type; if ((sock_type = isns_socket_type_from_portal(info)) < 0) return NULL; dst_alen = isns_portal_to_sockaddr(info, &dst_addr); ai = __make_addrinfo((struct sockaddr *) &dst_addr, dst_alen, sock_type); return __isns_create_socket(NULL, ai, sock_type); } /* * Make server side disconnects isns_fatal. * Nice for command line apps. */ void isns_socket_set_disconnect_fatal(isns_socket_t *sock) { sock->is_disconnect_fatal = 1; } void isns_socket_set_report_failure(isns_socket_t *sock) { sock->is_report_failure = 1; } /* * Set the socket's security context */ void isns_socket_set_security_ctx(isns_socket_t *sock, isns_security_t *ctx) { sock->is_security = ctx; } /* * Create a socket */ static isns_socket_t * isns_net_alloc(int fd) { isns_socket_t *new; new = isns_calloc(1, sizeof(*new)); new->is_desc = fd; if (fd >= 0) new->is_state = ISNS_SOCK_IDLE; else new->is_state = ISNS_SOCK_DISCONNECTED; isns_message_queue_init(&new->is_partial); isns_message_queue_init(&new->is_complete); isns_message_queue_init(&new->is_pending); isns_list_init(&new->is_list); return new; } /* * Open the socket */ static int isns_socket_open(isns_socket_t *sock) { int af, fd, state = ISNS_SOCK_IDLE; if (sock->is_desc >= 0) return 1; af = sock->is_dst.addr.ss_family; if (af != AF_UNSPEC) { /* Select a matching source address */ if (sock->is_src.list && !isns_sockaddr_select(&sock->is_src, &sock->is_dst.addr)) { isns_warning("No matching source address for given destination\n"); return 0; } } else { af = sock->is_src.addr.ss_family; if (af == AF_UNSPEC) return 0; } if ((fd = socket(af, sock->is_type, 0)) < 0) { isns_error("Unable to create socket: %m\n"); return 0; } if (sock->is_src.addr.ss_family != AF_UNSPEC) { const struct sockaddr *src_addr; int src_len, on = 1, bound = 0; src_addr = (struct sockaddr *) &sock->is_src.addr; src_len = sock->is_src.addrlen; /* For debugging only! */ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) { isns_error("setsockopt(SO_REUSEADDR) failed: %m\n"); goto failed; } switch (af) { case AF_LOCAL: unlink(((struct sockaddr_un *) src_addr)->sun_path); if (sock->is_type == SOCK_STREAM && setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0) { isns_error("setsockopt(SO_PASSCRED) failed: %m\n"); goto failed; } break; case AF_INET: case AF_INET6: if (isns_addr_get_port(src_addr) == 0) { if (!__isns_socket_bind_random(fd, src_addr, src_len)) goto failed; bound++; } break; } if (!bound && bind(fd, src_addr, src_len) < 0) { isns_error("Unable to bind socket: %m\n"); goto failed; } } if (sock->is_client) { /* Set to nonblocking behavior; makes the connect * call return instantly. */ fcntl(fd, F_SETFL, O_NONBLOCK); } else { if (sock->is_type == SOCK_STREAM) { if (listen(fd, 128) < 0) { isns_error("Unable to listen on socket: %m\n"); goto failed; } state = ISNS_SOCK_LISTENING; } } sock->is_desc = fd; sock->is_state = state; return 1; failed: close(fd); return 0; } /* * Destroy a socket */ static inline void isns_socket_destroy(isns_socket_t *sock) { isns_sockaddr_destroy(&sock->is_dst); isns_sockaddr_destroy(&sock->is_src); isns_free(sock); } void isns_socket_free(isns_socket_t *sock) { isns_net_close(sock, ISNS_SOCK_DEAD); isns_list_del(&sock->is_list); sock->is_destroy = 1; if (sock->is_users == 0) isns_socket_destroy(sock); } int isns_socket_release(isns_socket_t *sock) { isns_assert(sock->is_users); sock->is_users -= 1; if (sock->is_destroy) { if (!sock->is_users) isns_socket_destroy(sock); return 0; } return 1; } /* * Display a socket */ #if SOCK_DEBUG_VERBOSE > 0 static const char * isns_socket_state_name(int state) { static char xbuf[16]; switch (state) { case ISNS_SOCK_LISTENING: return "listening"; case ISNS_SOCK_CONNECTING: return "connecting"; case ISNS_SOCK_IDLE: return "idle"; case ISNS_SOCK_FAILED: return "failed"; case ISNS_SOCK_DISCONNECTED: return "disconnected"; case ISNS_SOCK_DEAD: return "dead"; } snprintf(xbuf, sizeof(xbuf), "<%u>", state); return xbuf; } static void isns_print_socket(const isns_socket_t *sock) { isns_message_t *msg = NULL; char buffer[8192]; size_t pos = 0, size = sizeof(buffer); snprintf(buffer + pos, size - pos, "socket %p desc %d state %s", sock, sock->is_desc, isns_socket_state_name(sock->is_state)); pos = strlen(buffer); if (timerisset(&sock->is_deadline)) { snprintf(buffer + pos, size - pos, " deadline=%ldms", __timeout_millisec(NULL, &sock->is_deadline)); pos = strlen(buffer); } if ((msg = isns_message_queue_head(&sock->is_pending)) != NULL) { snprintf(buffer + pos, size - pos, " msg timeout=%ldms", __timeout_millisec(NULL, &msg->im_timeout)); pos = strlen(buffer); } isns_debug_socket("%s\n", buffer); } #else #define isns_print_socket(p) do { } while (0) #endif /* * Process incoming messages, and timeouts */ static int isns_net_validate(isns_socket_t *sock, isns_message_t *msg, const isns_message_t *check_msg) { isns_message_t *orig = NULL; int verdict = ISNS_MSG_DISCARD; if (sock->is_security && !msg->im_security) { /* Rude server, or malicious man in the * middle. */ isns_debug_message("Ignoring unauthenticated message\n"); goto out; } /* If this is a request, return it. */ if (!(msg->im_header.i_function & 0x8000)) { if (check_msg == NULL) { verdict = ISNS_MSG_RETURN; } else { /* Else: see if there's a server attached to this * socket. */ } goto out; } orig = isns_message_queue_find(&sock->is_pending, msg->im_xid, NULL, 0); if (orig == NULL) { isns_debug_message("Ignoring spurious response message (xid=%04x)\n", msg->im_xid); goto out; } isns_message_unlink(orig); if (orig->im_header.i_function != (msg->im_header.i_function & 0x7FFF)) { isns_debug_message("Response message doesn't match function\n"); goto out; } if (check_msg == orig) { verdict = ISNS_MSG_RETURN; } else { isns_debug_message("Received response for pending message 0x%x\n", msg->im_xid); if (orig->im_callback) orig->im_callback(orig, msg); verdict = ISNS_MSG_DONE; } out: isns_message_release(orig); return verdict; } static void isns_net_timeout(isns_socket_t *sock, isns_message_t *msg) { if (msg->im_callback) msg->im_callback(msg, NULL); isns_message_release(msg); } /* * Helper function to update timeout */ static inline void __set_timeout(struct timeval *end, unsigned long timeout) { gettimeofday(end, NULL); end->tv_sec += timeout; } static inline int __timeout_expired(const struct timeval *now, const struct timeval *expires) { /* FIXME: Should ignore sub-millisecond remainder */ return timercmp(now, expires, >=); } static long __timeout_millisec(const struct timeval *now, const struct timeval *expires) { struct timeval __now, delta = { 0, 0 }; if (now == NULL) { gettimeofday(&__now, NULL); now = &__now; } timersub(expires, now, &delta); return delta.tv_sec * 1000 + delta.tv_usec / 1000; } static inline void __update_timeout(struct timeval *end, const struct timeval *timeout) { if (!timerisset(end) || timercmp(timeout, end, <)) *end = *timeout; } /* * Get the next iSNS message */ isns_message_t * __isns_recv_message(const struct timeval *end_time, isns_message_t *watch_msg) { isns_socket_t *sock, **sock_list; isns_list_t *pos, *next; struct pollfd *pfd; unsigned int i, count, max_sockets; struct timeval now, this_end; int r; max_sockets = isns_config.ic_network.max_sockets; sock_list = alloca(max_sockets * sizeof(sock_list[0])); pfd = alloca(max_sockets * sizeof(pfd[0])); again: timerclear(&this_end); gettimeofday(&now, NULL); if (end_time) { if (__timeout_expired(&now, end_time)) return NULL; this_end = *end_time; } i = 0; isns_list_foreach(&all_sockets, pos, next) { isns_socket_t *sock = isns_list_item(isns_socket_t, is_list, pos); isns_message_t *msg = NULL; /* We need to be a little careful here; callbacks may * mark the socket for destruction. * Bumping is_users while we're busy with the socket * prevents mayhem. */ sock->is_users++; while ((msg = isns_message_dequeue(&sock->is_complete)) != NULL) { switch (isns_net_validate(sock, msg, watch_msg)) { case ISNS_MSG_RETURN: isns_assert(!sock->is_destroy); isns_socket_release(sock); return msg; default: isns_message_release(msg); isns_socket_release(sock); return NULL; } } isns_print_socket(sock); /* This handles reconnect, idle disconnect etc. */ while (timerisset(&sock->is_deadline)) { if (__timeout_expired(&now, &sock->is_deadline)) { timerclear(&sock->is_deadline); sock->is_timeout(sock); isns_print_socket(sock); continue; } __update_timeout(&this_end, &sock->is_deadline); break; } /* No more input and output means closed&dead */ if (sock->is_state == ISNS_SOCK_IDLE && !(sock->is_poll_mask & (POLLIN|POLLOUT))) { isns_debug_socket("connection closed by peer, killing socket\n"); isns_net_close(sock, ISNS_SOCK_FAILED); } /* Check whether pending messages have timed out. */ while ((msg = isns_message_queue_head(&sock->is_pending)) != NULL) { if (__timeout_expired(&now, &msg->im_timeout)) { isns_debug_socket("sock %p message %04x timed out\n", sock, msg->im_xid); isns_message_unlink(msg); if (msg == watch_msg) { isns_message_release(msg); isns_socket_release(sock); return NULL; } isns_net_timeout(sock, msg); continue; } if (!__timeout_expired(&now, &msg->im_resend_timeout)) { __update_timeout(&this_end, &msg->im_resend_timeout); /* In odd configurations, the call_timeout * may be lower than the resend_timeout */ __update_timeout(&this_end, &msg->im_timeout); break; } isns_debug_socket("sock %p message %04x - " "minor timeout, resending.\n", sock, msg->im_xid); /* If a TCP socket times out, something is * fishy. Force a reconnect, which will resend * all pending messages. */ if (sock->is_type == SOCK_STREAM) { isns_net_close(sock, ISNS_SOCK_DISCONNECTED); isns_net_set_timeout(sock, isns_net_stream_reconnect, 0); break; } /* UDP socket - retransmit this one message */ isns_message_queue_remove(&sock->is_pending, msg); isns_socket_queue_message(sock, msg); isns_message_release(msg); } /* * If the socket on which we're waiting right * now got disconnected, or had any other kind of * error, return right away to let the caller know. */ if (sock->is_state == ISNS_SOCK_FAILED) { if (sock->is_disconnect_fatal) goto kill_socket; if (sock->is_report_failure) { isns_socket_release(sock); return NULL; } sock->is_state = ISNS_SOCK_DISCONNECTED; isns_socket_release(sock); continue; } if (sock->is_state == ISNS_SOCK_DEAD) { kill_socket: isns_list_del(&sock->is_list); if (sock->is_report_failure) { isns_socket_release(sock); return NULL; } if (!sock->is_client) isns_socket_free(sock); isns_socket_release(sock); continue; } /* This will return 0 if the socket was marked for * destruction. */ if (!isns_socket_release(sock)) continue; /* should not happen */ if (i >= max_sockets) break; pfd[i].fd = sock->is_desc; pfd[i].events = sock->is_poll_mask; sock_list[i] = sock; i++; } count = i; if (timerisset(&this_end)) { long millisec; /* timeval arithmetic can yield sub-millisecond timeouts. * Round up to prevent looping. */ millisec = __timeout_millisec(&now, &this_end); if (millisec == 0) millisec += 1; debug_verbose2("poll(%p, %u, %d)\n", pfd, count, millisec); r = poll(pfd, count, millisec); } else { r = poll(pfd, count, -1); } if (r < 0) { if (errno != EINTR) isns_error("poll returned error: %m\n"); return NULL; } /* Any new incoming connections will be added to the * head of the list. */ for (i = 0; i < count; ++i) { sock = sock_list[i]; if (pfd[i].revents & POLLIN) sock->is_poll_in(sock); if (pfd[i].revents & POLLOUT) sock->is_poll_out(sock); if (pfd[i].revents & POLLHUP) sock->is_poll_hup(sock); } goto again; } isns_message_t * isns_recv_message(struct timeval *timeout) { isns_message_t *msg; struct timeval end; if (timeout == NULL) return __isns_recv_message(NULL, NULL); gettimeofday(&end, NULL); timeradd(&end, timeout, &end); msg = __isns_recv_message(&end, NULL); if (msg == NULL) return msg; isns_debug_socket("Next message xid=%04x\n", msg->im_xid); if (msg->im_security) { isns_debug_message("Received authenticated message from \"%s\"\n", isns_principal_name(msg->im_security)); } else if (isns_config.ic_security) { isns_debug_message("Received unauthenticated message\n"); } else { isns_debug_message("Received message\n"); } return msg; } int isns_socket_send(isns_socket_t *sock, isns_message_t *msg) { struct isns_hdr *hdr; size_t pdu_len; buf_t *bp; /* If the socket is disconnected, and the * reconnect timeout is not set, force a * reconnect right away. */ if (sock->is_state == ISNS_SOCK_DISCONNECTED && !timerisset(&sock->is_deadline)) { isns_net_set_timeout(sock, isns_net_stream_reconnect, 0); } if (!(bp = msg->im_payload)) return 0; pdu_len = buf_avail(bp); if (pdu_len < sizeof(*hdr)) return 0; /* Pad PDU to multiple of 4 bytes, if needed */ if (pdu_len & 3) { unsigned int pad = 4 - (pdu_len & 3); if (!buf_put(bp, "\0\0\0", pad)) return 0; pdu_len += pad; } if (!(bp = buf_dup(bp))) return 0; hdr = buf_head(bp); hdr->i_version = htons(msg->im_header.i_version); hdr->i_function = htons(msg->im_header.i_function); hdr->i_flags = htons(msg->im_header.i_flags); hdr->i_length = htons(pdu_len - sizeof(*hdr)); hdr->i_xid = htons(msg->im_header.i_xid); hdr->i_seq = htons(msg->im_header.i_seq); /* For now, we deal with unfragmented messages only. */ hdr->i_flags |= htons(ISNS_F_FIRST_PDU|ISNS_F_LAST_PDU); if (sock->is_security) { #ifdef WITH_SECURITY hdr->i_flags |= htons(ISNS_F_AUTHBLK_PRESENT); if (!isns_pdu_seal(sock->is_security, bp)) { isns_debug_message("Error adding auth block to outgoing PDU\n"); goto error; } #else isns_debug_message("%s: Authentication not supported\n", __FUNCTION__); goto error; #endif } bp->addr = msg->im_addr; bp->addrlen = msg->im_addrlen; buf_list_append(&sock->is_xmit_buf, bp); sock->is_poll_mask |= POLLOUT; /* Set the retransmit timeout */ __set_timeout(&msg->im_resend_timeout, sock->is_retrans_timeout); return 1; error: buf_free(bp); return 0; } /* * Queue a message to a socket */ int isns_socket_queue_message(isns_socket_t *sock, isns_message_t *msg) { if (!isns_socket_send(sock, msg)) return 0; /* Insert sorted by timeout. For now, this amounts to * appending at the end of the list, but that may change * if we implement exponential backoff for UDP */ isns_message_queue_insert_sorted(&sock->is_pending, ISNS_MQ_SORT_RESEND_TIMEOUT, msg); msg->im_socket = sock; return 1; } /* * Retransmit any queued messages */ int isns_socket_retransmit_queued(isns_socket_t *sock) { isns_message_t *msg; isns_list_t *pos; isns_debug_socket("%s(%p)\n", __FUNCTION__, sock); isns_message_queue_foreach(&sock->is_pending, pos, msg) { if (!isns_socket_send(sock, msg)) isns_warning("Unable to retransmit message\n"); } return 1; } /* * Submit a message to the socket, for asynchronous calls */ int isns_socket_submit(isns_socket_t *sock, isns_message_t *msg, long timeout) { if (timeout <= 0) timeout = isns_config.ic_network.call_timeout; __set_timeout(&msg->im_timeout, timeout); return isns_socket_queue_message(sock, msg); } /* * Transmit a message and wait for a response. */ isns_message_t * isns_socket_call(isns_socket_t *sock, isns_message_t *msg, long timeout) { isns_message_t *resp; debug_verbose("isns_socket_call(sock=%p, msg=%p, timeout=%ld)\n", sock, msg, timeout); if (timeout <= 0) timeout = isns_config.ic_network.call_timeout; __set_timeout(&msg->im_timeout, timeout); if (!isns_socket_queue_message(sock, msg)) return NULL; sock->is_report_failure = 1; resp = __isns_recv_message(NULL, msg); sock->is_report_failure = 0; if (isns_message_unlink(msg)) { /* We can get here if __isns_recv_message returned * due to a fatal socket error. */ isns_debug_socket("%s: msg not unlinked!\n", __FUNCTION__); isns_message_release(msg); } if (resp == NULL && sock->is_type == SOCK_STREAM) isns_net_close(sock, ISNS_SOCK_DISCONNECTED); return resp; } /* * Resolve a hostname */ struct addrinfo * isns_get_address_list(const char *addrspec, const char *port, int af_hint, int sock_type, int flags) { struct addrinfo hints, *found = NULL, *res = NULL; char *copy = NULL, *host = NULL, *s; int rv; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_ADDRCONFIG; if (addrspec && addrspec[0] == '/') { if (af_hint != AF_LOCAL && af_hint != AF_UNSPEC) { isns_debug_socket("Path as address, but af_hint=%d\n", af_hint); goto bad_address; } res = make_addrinfo_unix(addrspec, SOCK_STREAM); goto out; } if (addrspec) { copy = host = isns_strdup(addrspec); if (*host == '[') { hints.ai_flags |= AI_NUMERICHOST; if ((s = strchr(host, ']')) == NULL) goto bad_address; *s++ = '\0'; if (*s == ':') port = ++s; else if (*s) goto bad_address; } else if ((s = strchr(host, ':')) != NULL) { *s++ = '\0'; if (!*s) goto bad_address; port = s; } if (*host == '\0') host = NULL; } else if (port == NULL) { /* Just wildcard */ res = make_addrinfo_any(af_hint, sock_type); goto out; } hints.ai_family = af_hint; hints.ai_flags |= flags; hints.ai_socktype = sock_type; if (af_hint == AF_INET6) hints.ai_flags |= AI_V4MAPPED; rv = getaddrinfo(host, port, &hints, &found); if (rv) { isns_error("Cannot resolve address \"%s\": %s\n", addrspec, gai_strerror(rv)); goto out; } if (found == NULL) { isns_error("No useable addresses returned.\n"); goto out; } res = clone_addrinfo(found); out: if (found) freeaddrinfo(found); isns_free(copy); return res; bad_address: isns_error("Cannot parse address spec \"%s\"\n", addrspec); goto out; } int isns_get_address(struct sockaddr_storage *result, const char *addrspec, const char *port, int af_hint, int sock_type, int flags) { struct addrinfo *ai; int alen; if (!(ai = isns_get_address_list(addrspec, port, af_hint, sock_type, flags))) return -1; alen = ai->ai_addrlen; if (alen > sizeof(*result)) return -1; memcpy(result, ai->ai_addr, alen); release_addrinfo(ai); return alen; } /* * Get the canonical hostname */ char * isns_get_canon_name(const char *hostname) { struct addrinfo hints, *res = NULL; char *fqdn = NULL; int rv; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; rv = getaddrinfo(hostname, NULL, &hints, &res); if (rv) { isns_error("Cannot resolve hostname \"%s\": %s\n", hostname, gai_strerror(rv)); goto out; } if (res == NULL) { isns_error("No useable addresses returned.\n"); goto out; } fqdn = isns_strdup(res->ai_canonname); out: if (res) freeaddrinfo(res); return fqdn; } int isns_socket_get_local_addr(const isns_socket_t *sock, struct sockaddr_storage *addr) { socklen_t alen; if (sock->is_desc < 0) return 0; if (getsockname(sock->is_desc, (struct sockaddr *) addr, &alen) < 0) { isns_error("getsockname: %m\n"); return 0; } return 1; } int isns_socket_get_portal_info(const isns_socket_t *sock, isns_portal_info_t *portal) { struct sockaddr_storage addr; socklen_t alen; int fd, success = 0; memset(portal, 0, sizeof(*portal)); /* If the socket is currently closed (eg because the * server shut down the connection), we cannot get the * local address easily. Create a temporary UDP socket, * connect it, and query that socket. */ if ((fd = sock->is_desc) < 0) { const struct sockaddr *daddr; daddr = (struct sockaddr *) &sock->is_dst.addr; fd = socket(daddr->sa_family, SOCK_DGRAM, 0); if (fd < 0) goto out; if (connect(fd, daddr, sizeof(sock->is_dst.addr)) < 0) goto out; } alen = sizeof(addr); if (getsockname(fd, (struct sockaddr *) &addr, &alen) < 0) { isns_error("getsockname: %m\n"); goto out; } if (!isns_portal_from_sockaddr(portal, &addr)) goto out; if (sock->is_type == SOCK_STREAM) portal->proto = IPPROTO_TCP; else portal->proto = IPPROTO_UDP; debug_verbose("socket_get_portal: %s\n", isns_portal_string(portal)); success = 1; out: /* If we used a temp UDP socket, close it */ if (fd >= 0 && fd != sock->is_desc) close(fd); return success; } isns_socket_t * isns_socket_find_server(const isns_portal_info_t *portal) { struct sockaddr_storage bound_addr; int sock_type, addr_len; isns_list_t *pos, *next; addr_len = isns_portal_to_sockaddr(portal, &bound_addr); if ((sock_type = isns_socket_type_from_portal(portal)) < 0) return NULL; isns_list_foreach(&all_sockets, pos, next) { isns_socket_t *sock = isns_list_item(isns_socket_t, is_list, pos); if (!sock->is_client && sock->is_type == sock_type && sock->is_dst.addrlen == addr_len && !memcmp(&sock->is_dst.addr, &bound_addr, addr_len)) { sock->is_users++; return sock; } } return NULL; } int isns_addr_get_port(const struct sockaddr *addr) { const struct sockaddr_in *sin; const struct sockaddr_in6 *six; switch (addr->sa_family) { case AF_INET: sin = (const struct sockaddr_in *) addr; return ntohs(sin->sin_port); case AF_INET6: six = (const struct sockaddr_in6 *) addr; return ntohs(six->sin6_port); } return 0; } void isns_addr_set_port(struct sockaddr *addr, unsigned int port) { struct sockaddr_in *sin; struct sockaddr_in6 *six; switch (addr->sa_family) { case AF_INET: sin = (struct sockaddr_in *) addr; sin->sin_port = htons(port); break; case AF_INET6: six = (struct sockaddr_in6 *) addr; six->sin6_port = htons(port); break; } } open-iscsi-2.0.873/utils/open-isns/socket.h000066400000000000000000000040461175631155400204740ustar00rootroot00000000000000/* * iSNS network code * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_SOCKET_H #define ISNS_SOCKET_H #include "isns.h" #include "buffer.h" #include "message.h" struct isns_partial_msg { isns_message_t imp_base; uint32_t imp_flags; uint32_t imp_first_seq; uint32_t imp_last_seq; unsigned int imp_pdu_count; unsigned int imp_msg_size; buf_t * imp_chain; struct ucred imp_credbuf; }; #define imp_users imp_base.im_users #define imp_list imp_base.im_list #define imp_xid imp_base.im_xid #define imp_header imp_base.im_header #define imp_addr imp_base.im_addr #define imp_addrlen imp_base.im_addrlen #define imp_header imp_base.im_header #define imp_payload imp_base.im_payload #define imp_security imp_base.im_security #define imp_creds imp_base.im_creds enum { ISNS_SOCK_LISTENING, ISNS_SOCK_CONNECTING, ISNS_SOCK_IDLE, ISNS_SOCK_FAILED, ISNS_SOCK_DISCONNECTED, ISNS_SOCK_DEAD, }; /* Helper class */ struct __isns_socket_addr { struct sockaddr_storage addr; socklen_t addrlen; struct addrinfo * list; }; struct isns_socket { isns_list_t is_list; int is_desc; int is_type; unsigned int is_client : 1, is_autoclose : 1, is_disconnect_fatal : 1, is_report_failure : 1, is_destroy : 1; unsigned int is_users; int is_poll_mask; int is_state; isns_security_t * is_security; struct __isns_socket_addr is_src, is_dst; unsigned int is_retrans_timeout; /* If we're past this time, is_timeout() is called. */ struct timeval is_deadline; buf_t * is_recv_buf; buf_t * is_xmit_buf; size_t is_queue_size; isns_message_queue_t is_partial; isns_message_queue_t is_complete; isns_message_queue_t is_pending; void (*is_poll_in)(isns_socket_t *); void (*is_poll_out)(isns_socket_t *); void (*is_poll_hup)(isns_socket_t *); void (*is_poll_err)(isns_socket_t *); void (*is_timeout)(isns_socket_t *); void (*is_error)(isns_socket_t *, int); }; extern int isns_socket_submit(isns_socket_t *, isns_message_t *, long); #endif /* ISNS_SOCKET_H */ open-iscsi-2.0.873/utils/open-isns/source.h000066400000000000000000000014641175631155400205050ustar00rootroot00000000000000/* * iSNS source attribute handling * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_SOURCE_H #define ISNS_SOURCE_H #include "attrs.h" struct isns_source { unsigned int is_users; isns_attr_t * is_attr; unsigned int is_untrusted : 1; isns_object_t * is_node; unsigned int is_node_type; isns_object_t * is_entity; }; extern int isns_source_encode(buf_t *, const isns_source_t *); extern int isns_source_decode(buf_t *, isns_source_t **); extern int isns_source_set_node(isns_source_t *, isns_db_t *); extern void isns_source_set_entity(isns_source_t *, isns_object_t *); extern isns_source_t * isns_source_dummy(void); extern char * isns_build_source_pattern(const char *); extern int isns_source_pattern_match(const char *, const char *); #endif /* ISNS_SOURCE_H */ open-iscsi-2.0.873/utils/open-isns/storage-node.c000066400000000000000000000114041175631155400215620ustar00rootroot00000000000000/* * iSNS object model - storage node * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns.h" #include "objects.h" #include "util.h" isns_object_t * isns_create_storage_node(const char *name, uint32_t type, isns_object_t *parent) { isns_object_t *obj; if (parent && !ISNS_IS_ENTITY(parent)) { isns_warning("Invalid container type \"%s\" for storage node: " "should be \"%s\"\n", parent->ie_template->iot_name, isns_entity_template.iot_name); return NULL; } obj = isns_create_object(&isns_iscsi_node_template, NULL, parent); isns_object_set_string(obj, ISNS_TAG_ISCSI_NAME, name); isns_object_set_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, type); return obj; } isns_object_t * isns_create_storage_node2(const isns_source_t *source, uint32_t type, isns_object_t *parent) { isns_attr_t *name_attr; isns_object_t *obj; if (parent && !ISNS_IS_ENTITY(parent)) { isns_warning("Invalid container type \"%s\" for storage node: " "should be \"%s\"\n", parent->ie_template->iot_name, isns_entity_template.iot_name); return NULL; } if ((name_attr = isns_source_attr(source)) == NULL) { isns_warning("No source attribute\n"); return NULL; } if (name_attr->ia_tag_id == ISNS_TAG_ISCSI_NAME) { obj = isns_create_object(&isns_iscsi_node_template, NULL, parent); isns_attr_list_update_attr(&obj->ie_attrs, name_attr); isns_object_set_uint32(obj, ISNS_TAG_ISCSI_NODE_TYPE, type); } else { /* No iFCP yet, sorry */ isns_warning("%s: source tag type %u not supported\n", __FUNCTION__); return NULL; } return obj; } isns_object_t * isns_create_iscsi_initiator(const char *name, isns_object_t *parent) { return isns_create_storage_node(name, 1 << ISNS_ISCSI_NODE_TYPE_INITIATOR, parent); } isns_object_t * isns_create_iscsi_target(const char *name, isns_object_t *parent) { return isns_create_storage_node(name, 1 << ISNS_ISCSI_NODE_TYPE_TARGET, parent); } const char * isns_storage_node_name(const isns_object_t *node) { const isns_attr_t *attr; if (node->ie_attrs.ial_count == 0) return NULL; attr = node->ie_attrs.ial_data[0]; if (attr->ia_value.iv_type != &isns_attr_type_string) return NULL; switch (attr->ia_tag_id) { case ISNS_TAG_ISCSI_NAME: case ISNS_TAG_FC_PORT_NAME_WWPN: return attr->ia_value.iv_string; } return 0; } isns_attr_t * isns_storage_node_key_attr(const isns_object_t *node) { if (node->ie_attrs.ial_count == 0) return NULL; return node->ie_attrs.ial_data[0]; } static uint32_t iscsi_node_attrs[] = { ISNS_TAG_ISCSI_NAME, ISNS_TAG_ISCSI_NODE_TYPE, ISNS_TAG_ISCSI_ALIAS, ISNS_TAG_ISCSI_SCN_BITMAP, ISNS_TAG_ISCSI_NODE_INDEX, ISNS_TAG_WWNN_TOKEN, ISNS_TAG_ISCSI_AUTHMETHOD, /* RFC 4171 lists a "iSCSI node certificate" * as an option attribute of an iSCSI * storage node, but doesn't define it anywhere * in the spec. */ }; static uint32_t iscsi_node_key_attrs[] = { ISNS_TAG_ISCSI_NAME, }; isns_object_template_t isns_iscsi_node_template = { .iot_name = "iSCSI Storage Node", .iot_handle = ISNS_OBJECT_TYPE_NODE, .iot_attrs = iscsi_node_attrs, .iot_num_attrs = array_num_elements(iscsi_node_attrs), .iot_keys = iscsi_node_key_attrs, .iot_num_keys = array_num_elements(iscsi_node_key_attrs), .iot_index = ISNS_TAG_ISCSI_NODE_INDEX, .iot_next_index = ISNS_TAG_ISCSI_NODE_NEXT_INDEX, .iot_container = &isns_entity_template, }; static uint32_t fc_port_attrs[] = { ISNS_TAG_FC_PORT_NAME_WWPN, ISNS_TAG_PORT_ID, ISNS_TAG_FC_PORT_TYPE, ISNS_TAG_SYMBOLIC_PORT_NAME, ISNS_TAG_FABRIC_PORT_NAME, ISNS_TAG_HARD_ADDRESS, ISNS_TAG_PORT_IP_ADDRESS, ISNS_TAG_CLASS_OF_SERVICE, ISNS_TAG_FC4_TYPES, ISNS_TAG_FC4_DESCRIPTOR, ISNS_TAG_FC4_FEATURES, ISNS_TAG_IFCP_SCN_BITMAP, ISNS_TAG_PORT_ROLE, ISNS_TAG_PERMANENT_PORT_NAME, }; static uint32_t fc_port_key_attrs[] = { ISNS_TAG_FC_PORT_NAME_WWPN, }; isns_object_template_t isns_fc_port_template = { .iot_name = "iFCP Port", .iot_handle = ISNS_OBJECT_TYPE_FC_PORT, .iot_attrs = fc_port_attrs, .iot_num_attrs = array_num_elements(fc_port_attrs), .iot_keys = fc_port_key_attrs, .iot_num_keys = array_num_elements(fc_port_key_attrs), .iot_container = &isns_entity_template, }; static uint32_t fc_node_attrs[] = { ISNS_TAG_FC_NODE_NAME_WWNN, ISNS_TAG_SYMBOLIC_NODE_NAME, ISNS_TAG_NODE_IP_ADDRESS, ISNS_TAG_NODE_IPA, ISNS_TAG_PROXY_ISCSI_NAME, }; static uint32_t fc_node_key_attrs[] = { ISNS_TAG_FC_NODE_NAME_WWNN, }; isns_object_template_t isns_fc_node_template = { .iot_name = "iFCP Device Node", .iot_handle = ISNS_OBJECT_TYPE_FC_NODE, .iot_attrs = fc_node_attrs, .iot_num_attrs = array_num_elements(fc_node_attrs), .iot_keys = fc_node_key_attrs, .iot_num_keys = array_num_elements(fc_node_key_attrs), .iot_container = &isns_fc_port_template, }; open-iscsi-2.0.873/utils/open-isns/sysdep-unix.c000066400000000000000000000074211175631155400214670ustar00rootroot00000000000000/* * System dependent stuff * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include #include "isns.h" #include "util.h" int isns_get_nr_portals(void) { char buffer[8192], *end, *ptr; struct ifconf ifc; unsigned int nportals = 0; int fd = -1; if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { isns_error("%s: no socket - %m\n", __FUNCTION__); return 0; } ifc.ifc_buf = buffer; ifc.ifc_len = sizeof(buffer); if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) { isns_error("ioctl(SIOCGIFCONF): %m\n"); goto out; } ptr = buffer; end = buffer + ifc.ifc_len; while (ptr < end) { struct ifreq ifr; struct sockaddr_storage ifaddr; int ifflags; memcpy(&ifr, ptr, sizeof(ifr)); ptr += sizeof(ifr); /* Get the interface addr */ memcpy(&ifaddr, &ifr.ifr_addr, sizeof(ifr.ifr_addr)); if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) { isns_error("ioctl(%s, SIOCGIFFLAGS): %m\n", ifr.ifr_name); continue; } ifflags = ifr.ifr_flags; if ((ifflags & IFF_UP) == 0) continue; if ((ifflags & IFF_LOOPBACK) != 0) continue; if (ifaddr.ss_family == AF_INET6 || ifaddr.ss_family == AF_INET) nportals++; } out: if (fd >= 0) close(fd); return nportals; } int isns_enumerate_portals(isns_portal_info_t *result, unsigned int max) { char buffer[8192], *end, *ptr; struct ifconf ifc; unsigned int nportals = 0; int fd = -1; if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { isns_error("%s: no socket - %m\n", __FUNCTION__); return 0; } ifc.ifc_buf = buffer; ifc.ifc_len = sizeof(buffer); if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) { isns_error("ioctl(SIOCGIFCONF): %m\n"); goto out; } ptr = buffer; end = buffer + ifc.ifc_len; while (ptr < end) { struct ifreq ifr; struct sockaddr_storage ifaddr; isns_portal_info_t portal; int ifflags; memcpy(&ifr, ptr, sizeof(ifr)); ptr += sizeof(ifr); /* Get the interface addr */ memcpy(&ifaddr, &ifr.ifr_addr, sizeof(ifr.ifr_addr)); if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) { isns_error("ioctl(%s, SIOCGIFFLAGS): %m\n", ifr.ifr_name); continue; } ifflags = ifr.ifr_flags; if ((ifflags & IFF_UP) == 0) continue; if ((ifflags & IFF_LOOPBACK) != 0) continue; if (!isns_portal_from_sockaddr(&portal, &ifaddr)) continue; isns_debug_socket("Got interface %u: %s %s\n", nportals, ifr.ifr_name, isns_portal_string(&portal)); if (nportals < max) result[nportals++] = portal; } out: if (fd >= 0) close(fd); return nportals; } int isns_portal_from_sockaddr(isns_portal_info_t *portal, const struct sockaddr_storage *addr) { struct sockaddr_in6 *six; struct sockaddr_in *sin; memset(portal, 0, sizeof(*portal)); /* May have to convert AF_INET to AF_INET6 */ six = &portal->addr; switch (addr->ss_family) { case AF_INET6: memcpy(six, addr, sizeof(*six)); break; case AF_INET: sin = (struct sockaddr_in *) addr; six->sin6_family = AF_INET6; six->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr; six->sin6_port = sin->sin_port; break; default: return 0; } return 1; } int isns_portal_to_sockaddr(const isns_portal_info_t *portal, struct sockaddr_storage *addr) { const struct sockaddr_in6 *six = &portal->addr; struct sockaddr_in *sin; /* Check if this is really a v4 address is disguise. * If so, explicitly use an AF_INET socket - the * stack may not support IPv6. */ if (IN6_IS_ADDR_V4MAPPED(&six->sin6_addr) || IN6_IS_ADDR_V4COMPAT(&six->sin6_addr)) { sin = (struct sockaddr_in *) addr; memset(sin, 0, sizeof(*sin)); sin->sin_family = AF_INET; sin->sin_addr.s_addr = six->sin6_addr.s6_addr32[3]; sin->sin_port = six->sin6_port; return sizeof(*sin); } /* This is the genuine article */ memcpy(addr, six, sizeof(*six)); return sizeof(*six); } open-iscsi-2.0.873/utils/open-isns/tags.c000066400000000000000000000430001175631155400201260ustar00rootroot00000000000000/* * Define all iSNS tags with their types, etc. * * Copyright (C) 2007 Olaf Kirch */ #include #include #include #include "isns-proto.h" #include "vendor.h" #include "attrs.h" #include "security.h" #include "objects.h" #include "util.h" #define ISNS_MAX_BUILTIN_TAG 4096 static void print_bitfield(unsigned long, char **, char *, size_t); static int parse_bitfield( char **, const char *, uint32_t *); static const char *help_bitfield(char **); #define DECLARE_VALIDATOR(name) \ static int isns_##name##_validate(const isns_value_t *, const isns_policy_t *); #define DECLARE_ACCESSORS(name) \ static int isns_##name##_parse(isns_value_t *, const char *buf); \ static void isns_##name##_print(const isns_value_t *, char *buf, size_t size); \ static const char * isns_##name##_help(void) #define USE_VALIDATOR(name) \ .it_validate = isns_##name##_validate #define USE_ACCESSORS(name) \ .it_parse = isns_##name##_parse, \ .it_print = isns_##name##_print, \ .it_help = isns_##name##_help DECLARE_VALIDATOR(entity_protocol); DECLARE_ACCESSORS(entity_protocol); DECLARE_ACCESSORS(tcpudp_port); DECLARE_VALIDATOR(iscsi_node_type); DECLARE_ACCESSORS(iscsi_node_type); DECLARE_ACCESSORS(timestamp); DECLARE_ACCESSORS(portal_secbitmap); DECLARE_ACCESSORS(scn_bitmap); DECLARE_ACCESSORS(dd_features); DECLARE_ACCESSORS(policy_object_type); DECLARE_ACCESSORS(policy_function); static const char *isns_authmethod_help(void); #define TAG(ID, name, type, args...) \ [ISNS_TAG_##ID] = { \ .it_id = ISNS_TAG_##ID, \ .it_name = name, \ .it_type = &isns_attr_type_##type, \ args \ } static isns_tag_type_t isns_tags[ISNS_MAX_BUILTIN_TAG] = { TAG(DELIMITER, "Delimiter", nil), TAG(ENTITY_IDENTIFIER, "Entity identifier", string), TAG(ENTITY_PROTOCOL, "Entity protocol", uint32, USE_VALIDATOR(entity_protocol), USE_ACCESSORS(entity_protocol)), TAG(MGMT_IP_ADDRESS, "Mgmt IP address", ipaddr), TAG(TIMESTAMP, "Timestamp", uint64, USE_ACCESSORS(timestamp), .it_readonly = 1), TAG(PROTOCOL_VERSION_RANGE, "Protocol version range", range16), TAG(REGISTRATION_PERIOD, "Registration Period", uint32), TAG(ENTITY_INDEX, "Entity index", uint32, .it_readonly = 1), TAG(ENTITY_NEXT_INDEX, "Entity next index", uint32, .it_readonly = 1), TAG(PORTAL_IP_ADDRESS, "Portal IP address", ipaddr), TAG(PORTAL_TCP_UDP_PORT, "Portal TCP/UDP port", uint32, USE_ACCESSORS(tcpudp_port)), TAG(ESI_INTERVAL, "ESI interval", uint32), TAG(ESI_PORT, "ESI port", uint32, USE_ACCESSORS(tcpudp_port)), TAG(PORTAL_SYMBOLIC_NAME, "Portal name", string), TAG(PORTAL_INDEX, "Portal index", uint32), TAG(SCN_PORT, "SCN port", uint32, USE_ACCESSORS(tcpudp_port)), TAG(PORTAL_SECURITY_BITMAP, "Portal security bitmap", uint32, USE_ACCESSORS(portal_secbitmap)), TAG(PORTAL_NEXT_INDEX, "Portal next index", uint32, .it_readonly = 1), TAG(ISCSI_NAME, "iSCSI name", string), TAG(ISCSI_NODE_TYPE, "iSCSI node type", uint32, USE_VALIDATOR(iscsi_node_type), USE_ACCESSORS(iscsi_node_type)), TAG(ISCSI_ALIAS, "iSCSI alias", string), TAG(ISCSI_SCN_BITMAP, "iSCSI SCN bitmap", uint32, USE_ACCESSORS(scn_bitmap)), TAG(ISCSI_NODE_INDEX, "iSCSI node index", uint32, .it_readonly = 1), TAG(WWNN_TOKEN, "WWNN token", uint64), TAG(ISCSI_NODE_NEXT_INDEX, "iSCSI node next index",uint32, .it_readonly = 1), TAG(ISCSI_AUTHMETHOD, "iSCSI auth method", string, .it_help = isns_authmethod_help), TAG(PG_ISCSI_NAME, "Portal group name", string), TAG(PG_PORTAL_IP_ADDR, "Portal group address", ipaddr), TAG(PG_PORTAL_TCP_UDP_PORT, "Portal group port", uint32, USE_ACCESSORS(tcpudp_port)), TAG(PG_TAG, "Portal group tag", uint32), TAG(PG_INDEX, "Portal group index", uint32, .it_readonly = 1), TAG(PG_NEXT_INDEX, "Portal group next index",uint32, .it_readonly = 1), /* FC Port */ TAG(FC_PORT_NAME_WWPN, "FC port name WWPN", uint64), TAG(PORT_ID, "FC port ID", uint32), TAG(FC_PORT_TYPE, "FC port type", uint32), TAG(SYMBOLIC_PORT_NAME, "FC symbolic port name",string), TAG(FABRIC_PORT_NAME, "FC fabric port name", uint64), TAG(HARD_ADDRESS, "FC hard", uint32), TAG(PORT_IP_ADDRESS, "FC Port IP address", ipaddr), TAG(CLASS_OF_SERVICE, "FC service class", uint32), TAG(FC4_TYPES, "FC4 types", opaque), TAG(FC4_DESCRIPTOR, "FC4 descriptor", string), TAG(FC4_FEATURES, "FC4 features", opaque), TAG(IFCP_SCN_BITMAP, "iFCP SCN bitmap", uint32, USE_ACCESSORS(scn_bitmap)), TAG(PORT_ROLE, "FC port role", uint32), TAG(PERMANENT_PORT_NAME, "FC permanent port name",uint64), TAG(FC4_TYPE_CODE, "FC4 type code", uint32), /* FC Node */ TAG(FC_NODE_NAME_WWNN, "FC node name", uint64), TAG(SYMBOLIC_NODE_NAME, "FC symbolic node name",string), TAG(NODE_IP_ADDRESS, "FC node IP address", ipaddr), TAG(NODE_IPA, "FC node IPA", uint64), TAG(PROXY_ISCSI_NAME, "FC node proxy iSCSI name",string), /* Other FC tags to go here */ /* Discovery domain set */ TAG(DD_SET_ID, "DD set ID", uint32), TAG(DD_SET_SYMBOLIC_NAME, "DD set name", string), TAG(DD_SET_STATUS, "DD set status", uint32), TAG(DD_SET_NEXT_ID, "DD set next ID", uint32, .it_readonly = 1), /* Discovery domain */ TAG(DD_ID, "DD ID", uint32), TAG(DD_SYMBOLIC_NAME, "DD name", string), TAG(DD_MEMBER_ISCSI_INDEX, "DD member iSCSI index",uint32, .it_multiple = 1), TAG(DD_MEMBER_ISCSI_NAME, "DD member iSCSI name", string, .it_multiple = 1), TAG(DD_MEMBER_FC_PORT_NAME, "DD member FC WWPN", string, .it_multiple = 1), TAG(DD_MEMBER_PORTAL_INDEX, "DD member portal index",uint32, .it_multiple = 1), TAG(DD_MEMBER_PORTAL_IP_ADDR, "DD member portal addr",ipaddr, .it_multiple = 1), TAG(DD_MEMBER_PORTAL_TCP_UDP_PORT,"DD member portal port",uint32, USE_ACCESSORS(tcpudp_port), .it_multiple = 1), TAG(DD_FEATURES, "DD features", uint32, USE_ACCESSORS(dd_features)), TAG(DD_NEXT_ID, "DD next ID", uint32, .it_readonly = 1), }; /* * End of RFC defined tags */ #undef TAG /* * Open-iSNS vendor specific tags */ #define TAG(ID, name, type, args...) \ { \ .it_id = OPENISNS_TAG_##ID, \ .it_name = name, \ .it_type = &isns_attr_type_##type, \ args \ } static isns_tag_type_t isns_vendor_tags[] = { TAG(POLICY_SPI, "Security Policy Index", string), TAG(POLICY_KEY, "DSA security key", opaque), TAG(POLICY_ENTITY, "Policy allowed entity name", string), TAG(POLICY_OBJECT_TYPE, "Policy allowed object types", uint32, USE_ACCESSORS(policy_object_type)), TAG(POLICY_NODE_NAME, "Policy allowed node name", string, .it_multiple = 1), TAG(POLICY_NODE_TYPE, "Policy allowed node type", uint32, USE_VALIDATOR(iscsi_node_type), USE_ACCESSORS(iscsi_node_type)), TAG(POLICY_FUNCTIONS, "Policy allowed functions", uint32, USE_ACCESSORS(policy_function)), TAG(POLICY_VISIBLE_DD, "Visible Discovery Domain", string, .it_multiple = 1), TAG(POLICY_DEFAULT_DD, "Default Discovery Domain", string), { 0 } }; /* * End of vendor-specific tags */ static isns_tag_type_t isns_unknown_tag = { .it_id = 0xffff, .it_name = "unknown", .it_type = &isns_attr_type_opaque, }; /* * Map iSNS attribute tag to its data type */ const isns_tag_type_t * isns_tag_type_by_id(uint32_t id) { isns_tag_type_t *tag; if (id < ISNS_MAX_BUILTIN_TAG) { tag = &isns_tags[id]; if (tag->it_type == NULL) { *tag = isns_unknown_tag; tag->it_id = id; } return tag; } for (tag = isns_vendor_tags; tag->it_name; ++tag) { if (tag->it_id == id) return tag; } return &isns_unknown_tag; } /* * Specific validators/pretty printers */ int isns_entity_protocol_validate(const isns_value_t *value, const isns_policy_t *policy) { enum isns_entity_protocol protocol = value->iv_uint32; switch (protocol) { case ISNS_ENTITY_PROTOCOL_NONE: case ISNS_ENTITY_PROTOCOL_ISCSI: case ISNS_ENTITY_PROTOCOL_IFCP: return 1; } return 0; } int isns_entity_protocol_parse(isns_value_t *value, const char *string) { uint32_t prot; if (!strcasecmp(string, "none")) prot = ISNS_ENTITY_PROTOCOL_NONE; else if (!strcasecmp(string, "iscsi")) prot = ISNS_ENTITY_PROTOCOL_ISCSI; else if (!strcasecmp(string, "ifcp")) prot = ISNS_ENTITY_PROTOCOL_IFCP; else return 0; value->iv_uint32 = prot; return 1; } void isns_entity_protocol_print(const isns_value_t *value, char *buf, size_t size) { enum isns_entity_protocol protocol = value->iv_uint32; const char *prot_name; switch (protocol) { case ISNS_ENTITY_PROTOCOL_NONE: prot_name = "None"; break; case ISNS_ENTITY_PROTOCOL_ISCSI: prot_name = "iSCSI"; break; case ISNS_ENTITY_PROTOCOL_IFCP: prot_name = "iFCP"; break; default: prot_name = "Unknown"; } snprintf(buf, size, "%s (%u)", prot_name, protocol); } const char * isns_entity_protocol_help(void) { return "one of None, iSCSI, iFCP"; } /* * TCP/UDP port */ int isns_tcpudp_port_parse(isns_value_t *value, const char *string) { uint32_t num; const char *ep; num = strtoul(string, (char **) &ep, 0); if (ep && *ep) { if (!strcasecmp(ep, "/udp")) num |= ISNS_PORTAL_PORT_UDP_MASK; else if (!strcasecmp(ep, "/tcp")) /* nothing */; else { isns_error("Cannot parse port spec \"%s\"\n", string); return 0; } } value->iv_uint32 = num; return 1; } void isns_tcpudp_port_print(const isns_value_t *value, char *buf, size_t size) { uint32_t portspec = value->iv_uint32, num; if (portspec == 0) { snprintf(buf, size, "[default]"); } else { num = portspec & 0xffff; if (portspec & ISNS_PORTAL_PORT_UDP_MASK) { snprintf(buf, size, "%u/udp", num); } else { snprintf(buf, size, "%u/tcp", num); } } } const char * isns_tcpudp_port_help(void) { return "/tcp, /udp, or (defaults to TCP)"; } int isns_timestamp_parse(isns_value_t *value, const char *string) { isns_error("Timestamp parsing not implemented\n"); return 0; } void isns_timestamp_print(const isns_value_t *value, char *buf, size_t size) { time_t timestamp = value->iv_uint64; char *str, *s; str = ctime(×tamp); if ((s = strchr(str, '\n')) != NULL) *s = '\0'; snprintf(buf, size, "%s", str); } const char * isns_timestamp_help(void) { return NULL; } /* * Helper macros to implement the off-the-shelf bitfield * accessors. */ #define IMPLEMENT_BITFIELD_ACCESSORS(name) \ int isns_##name##_parse(isns_value_t *value, const char *string) \ { \ return parse_bitfield(name##_bit_names, string, \ &value->iv_uint32); \ } \ \ void \ isns_##name##_print(const isns_value_t *value, char *buf, size_t size) \ { \ print_bitfield(value->iv_uint32, name##_bit_names, \ buf, size); \ } \ \ const char * \ isns_##name##_help(void) \ { \ return help_bitfield(name##_bit_names); \ } static char * iscsi_node_type_bit_names[32] = { [ISNS_ISCSI_NODE_TYPE_TARGET] = "Target", [ISNS_ISCSI_NODE_TYPE_INITIATOR] = "Initiator", [ISNS_ISCSI_NODE_TYPE_CONTROL] = "Control", }; int isns_iscsi_node_type_validate(const isns_value_t *value, const isns_policy_t *policy) { uint32_t bits = value->iv_uint32, permitted; permitted = ISNS_ISCSI_INITIATOR_MASK | ISNS_ISCSI_TARGET_MASK | ISNS_ISCSI_CONTROL_MASK; if (bits & ~permitted) return 0; if (policy && !isns_policy_validate_node_type(policy, bits)) return 0; return 1; } IMPLEMENT_BITFIELD_ACCESSORS(iscsi_node_type); /* * Portal Security Bitmap */ static char * portal_secbitmap_bit_names[32] = { [ISNS_PORTAL_SEC_BITMAP_VALID] = "bitmap valid", [ISNS_PORTAL_SEC_IPSEC_ENABLED] = "ipsec enabled", [ISNS_PORTAL_SEC_MAIN_MODE_ENABLED] = "main mode enabled", [ISNS_PORTAL_SEC_AGGR_MODE_ENABLED] = "aggressive mode enabled", [ISNS_PORTAL_SEC_PFS_ENABLED] = "pfs enabled", [ISNS_PORTAL_SEC_TRANSPORT_MODE_PREFERRED] = "transport mode preferred", [ISNS_PORTAL_SEC_TUNNEL_MODE_PREFERRED] = "tunnel mode preferred", }; IMPLEMENT_BITFIELD_ACCESSORS(portal_secbitmap); /* * SCN bitmap */ static char * scn_bitmap_bit_names[32] = { [ISNS_SCN_DD_MEMBER_ADDED] = "DD/DDS member added", [ISNS_SCN_DD_MEMBER_REMOVED] = "DD/DDS member removed", [ISNS_SCN_OBJECT_UPDATED] = "object updated", [ISNS_SCN_OBJECT_ADDED] = "object added", [ISNS_SCN_OBJECT_REMOVED] = "object removed", [ISNS_SCN_MANAGEMENT_REGISTRATION] = "management registration", [ISNS_SCN_TARGET_AND_SELF_ONLY] = "target and self information only", [ISNS_SCN_INITIATOR_AND_SELF_ONLY] = "initiator and self information only", }; IMPLEMENT_BITFIELD_ACCESSORS(scn_bitmap); /* * DD features bitmap */ static char * dd_features_bit_names[32] = { [ISNS_DD_BOOT_LIST_ENABLED] = "Boot list enabled", }; IMPLEMENT_BITFIELD_ACCESSORS(dd_features); /* * Policy: list of allowed functions */ static char * policy_function_bit_names[32] = { [ISNS_DEVICE_ATTRIBUTE_REGISTER]= "DevAttrReg", [ISNS_DEVICE_ATTRIBUTE_QUERY] = "DevAttrQry", [ISNS_DEVICE_GET_NEXT] = "DevGetNext", [ISNS_DEVICE_DEREGISTER] = "DevDereg", [ISNS_SCN_REGISTER] = "SCNReg", [ISNS_SCN_DEREGISTER] = "SCNDereg", [ISNS_SCN_EVENT] = "SCNEvent", [ISNS_STATE_CHANGE_NOTIFICATION]= "SCN", [ISNS_DD_REGISTER] = "DDReg", [ISNS_DD_DEREGISTER] = "DDDereg", [ISNS_DDS_REGISTER] = "DDSReg", [ISNS_DDS_DEREGISTER] = "DDSDereg", [ISNS_ENTITY_STATUS_INQUIRY] = "ESI", [ISNS_HEARTBEAT] = "Heartbeat", }; IMPLEMENT_BITFIELD_ACCESSORS(policy_function); /* * Policy: list of allowed node types */ static char * policy_object_type_bit_names[32] = { [ISNS_OBJECT_TYPE_ENTITY] = "entity", [ISNS_OBJECT_TYPE_NODE] = "iscsi-node", [ISNS_OBJECT_TYPE_PORTAL] = "portal", [ISNS_OBJECT_TYPE_PG] = "portal-group", [ISNS_OBJECT_TYPE_DD] = "dd", [ISNS_OBJECT_TYPE_DDSET] = "ddset", [ISNS_OBJECT_TYPE_POLICY] = "policy", }; static int isns_policy_object_type_parse(isns_value_t *vp, const char *buf) { char *copy, *s, *next; int rv = 0; if (!strcasecmp(buf, "ALL")) { vp->iv_uint32 = ~0; return 1; } if (!strcasecmp(buf, "DEFAULT")) { vp->iv_uint32 = ISNS_DEFAULT_OBJECT_ACCESS; return 1; } vp->iv_uint32 = 0; copy = isns_strdup(buf); for (s = copy; s; s = next) { char *perm; int bit, mask = 0; while (1) { unsigned int n; n = strcspn(s, ",+;|"); if (n) { next = s + n; if (*next) *next++ = '\0'; break; } ++n; } mask = ISNS_PERMISSION_READ; if ((perm = strchr(s, ':')) != NULL) { *perm++ = '\0'; mask = 0; while (*perm) { switch (*perm++) { case 'R': case 'r': mask = ISNS_PERMISSION_READ; break; case 'W': case 'w': mask = ISNS_PERMISSION_READ; break; default: goto failed; } } } for (bit = 0; bit < 32; ++bit) { if (policy_object_type_bit_names[bit] && !strcasecmp(policy_object_type_bit_names[bit], s)) goto found; } goto failed; found: vp->iv_uint32 |= ISNS_ACCESS(bit, mask); } rv = 1; failed: isns_free(copy); return rv; } static void isns_policy_object_type_print(const isns_value_t *vp, char *buf, size_t size) { unsigned int i, pos = 0; uint32_t mask; const char *sepa = ""; mask = vp->iv_uint32; if (mask == 0) { snprintf(buf, size, ""); return; } for (i = 0; i < 32; ++i, mask >>= 2) { const char *name; if (!(mask & 3)) continue; name = policy_object_type_bit_names[i]; if (name) snprintf(buf + pos, size - pos, "%s%s:%s%s", sepa, name, (mask & ISNS_PERMISSION_READ)? "r" : "", (mask & ISNS_PERMISSION_WRITE)? "w" : ""); else snprintf(buf + pos, size - pos, "%sbit%u:%s%s",sepa, i, (mask & ISNS_PERMISSION_READ)? "r" : "", (mask & ISNS_PERMISSION_WRITE)? "w" : ""); sepa = ", "; pos = strlen(buf); } } static const char * isns_policy_object_type_help(void) { static char buffer[256]; unsigned int i, n; char *sepa = ""; strcpy(buffer, "bitfield (type:perm): perm=R, W, or RW; type="); n = strlen(buffer); for (i = 0; i < 32; ++i) { if (policy_object_type_bit_names[i]) { snprintf(buffer + n, sizeof(buffer) - n, "%s%s", sepa, policy_object_type_bit_names[i]); sepa = ", "; } } return buffer; } /* * Help message for AuthMethod */ const char * isns_authmethod_help(void) { return "comma separated list, including of KRB5, SPKM1, SPKM2, SRP, CHAP, none"; } /* * Helper functions to deal with bitfields */ static void print_bitfield(unsigned long value, char **bit_names, char *buf, size_t size) { unsigned int bit, mask; const char *sepa = ""; char *buf_end; if (value == 0) { snprintf(buf, size, ""); return; } buf_end = buf + size; for (bit = 0, mask = 1; mask; ++bit, mask <<= 1) { char namebuf[16], *name; if (!(value & mask)) continue; if ((name = bit_names[bit]) == NULL) { sprintf(namebuf, "bit%u", bit); name = namebuf; } snprintf(buf, buf_end - buf, "%s%s", sepa, name); buf += strlen(buf); sepa = ", "; } } static int parse_bitfield(char **bit_names, const char *string, uint32_t *result) { *result = 0; if (!strcasecmp(string, "ALL")) { unsigned int bit; for (bit = 0; bit < 32; ++bit) { if (bit_names[bit]) *result |= 1 << bit; } return 1; } if (!strcasecmp(string, "NONE")) return 1; while (*string) { unsigned int n, bit, match = 0; n = strcspn(string, ",+;|"); if (n == 0) goto next; for (bit = 0; bit < 32; ++bit) { if (!bit_names[bit]) continue; if (!strncasecmp(bit_names[bit], string, n)) { *result |= 1 << bit; match++; } } if (!match) return 0; next: string += n; string += strspn(string, ",+;|"); } return 1; } static const char * help_bitfield(char **bit_names) { static char buffer[1024]; char *pos, sepa = ':'; unsigned int bit; strcpy(buffer, "bitfield"); pos = strchr(buffer, '\0'); for (bit = 0; bit < 32; ++bit) { if (bit_names[bit] == NULL) continue; snprintf(pos, sizeof(buffer) - (pos - buffer), "%c %s", sepa, bit_names[bit]); pos += strlen(pos); sepa = ','; } return buffer; } open-iscsi-2.0.873/utils/open-isns/tests/000077500000000000000000000000001175631155400201715ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/.cvsignore000066400000000000000000000000201175631155400221610ustar00rootroot00000000000000*.swp pauw[1-9] open-iscsi-2.0.873/utils/open-isns/tests/Makefile000066400000000000000000000021631175631155400216330ustar00rootroot00000000000000# # Simple makefile to run regression tests, and to # document how to run them. # # Each test case is a perl script, testXX.pl. Run as # perl testXX.pl # Optionally followed by # -q quiet - just print a header line, and the overall result # -v verbose - display more detailed information, including the # commands being run # -f fast - skip tests that take more than 15 seconds # # The default is to be slightly verbose, and display a comment # about each stage of the test. # All test related data is kept in /tmp/isns-test, with a # subdirectory for each test. # For instance, test01 will create # /tmp/isns-test/test01/server0 # /tmp/isns-test/test01/client1 # /tmp/isns-test/test01/dump # # The server and client directories will contain configuration # data, logfiles, and (for the server) the Unix socket, the # PID file, and the database. # # The dump directory contains snapshots of the on-disk database # for each test stage (if the test stage involves a verification # of the database). tests: @for test in test*.pl; do \ perl $$test -q; \ done quick: @for test in test*.pl; do \ perl $$test -q --fast; \ done open-iscsi-2.0.873/utils/open-isns/tests/client.conf000066400000000000000000000002771175631155400223240ustar00rootroot00000000000000SourceName = @NOT_SET@ AuthName = @NOT_SET@ ServerAddress = @NOT_SET@ BindAddress = @NOT_SET@ Security = @NOT_SET@ AuthKeyFile = @NOT_SET@ ServerKeyFile = @NOT_SET@ ControlSocket = @NOT_SET@ open-iscsi-2.0.873/utils/open-isns/tests/data/000077500000000000000000000000001175631155400211025ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test01/000077500000000000000000000000001175631155400222225ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test01/01-enroll000066400000000000000000000014731175631155400236630ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test01/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test01/02-registration000066400000000000000000000036201175631155400250770ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test01/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 12:40:58 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test01/03-query000066400000000000000000000016221175631155400235330ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 12:41:41 2007 0007 uint32 : Entity index = 4 object[1] = 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 object[2] = 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 object[3] = 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test01/03-registration000066400000000000000000000020061175631155400250750ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test01/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "isns.client1" 0602v string : Policy allowed source name = "isns.client1" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "isns.client2" 0602v string : Policy allowed source name = "isns.client2" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... open-iscsi-2.0.873/utils/open-isns/tests/data/test01/99-unregistration000066400000000000000000000014731175631155400254660ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test01/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/000077500000000000000000000000001175631155400222235ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test02/01-enroll000066400000000000000000000014731175631155400236640ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/02-enroll000066400000000000000000000022611175631155400236610ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 5 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target open-iscsi-2.0.873/utils/open-isns/tests/data/test02/03-registration000066400000000000000000000065411175631155400251060ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 13 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:53 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:53 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/04-query000066400000000000000000000016221175631155400235350ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 5 object[1] = 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 object[2] = 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 object[3] = 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/05-query000066400000000000000000000016241175631155400235400ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 object[1] = 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 object[2] = 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 object[3] = 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/06-dd-registration000066400000000000000000000073711175631155400255000ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 14 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" 0813 uint32 : DD member iSCSI index = 10 0814 string : DD member iSCSI name = "isns.client2" open-iscsi-2.0.873/utils/open-isns/tests/data/test02/07-query000066400000000000000000000034461175631155400235460ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 5 object[1] = 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 object[2] = 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 object[3] = 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 object[4] = 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 object[5] = 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 object[6] = 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 object[7] = 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/08-query000066400000000000000000000034461175631155400235470ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 5 object[1] = 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 object[2] = 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 object[3] = 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 object[4] = 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 object[5] = 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 object[6] = 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 object[7] = 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/09-query000066400000000000000000000016241175631155400235440ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 object[1] = 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 object[2] = 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 object[3] = 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/10-dd-registration000066400000000000000000000100371175631155400254640ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:18:54 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" 0813 uint32 : DD member iSCSI index = 10 0814 string : DD member iSCSI name = "isns.client2" 0813 uint32 : DD member iSCSI index = 14 0814 string : DD member iSCSI name = "iqn.com.foobar:disk1" -------------- Object: index=14 type= state=limbo 0020 string : iSCSI name = "iqn.com.foobar:disk1" 0024 uint32 : iSCSI node index = 14 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/11-query000066400000000000000000000007421175631155400235350ustar00rootroot00000000000000object[0] = 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" 0813 uint32 : DD member iSCSI index = 10 0814 string : DD member iSCSI name = "isns.client2" 0813 uint32 : DD member iSCSI index = 14 0814 string : DD member iSCSI name = "iqn.com.foobar:disk1" open-iscsi-2.0.873/utils/open-isns/tests/data/test02/12-dd-deregistration000066400000000000000000000076621175631155400260110ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:20:33 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:20:33 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" 0813 uint32 : DD member iSCSI index = 14 0814 string : DD member iSCSI name = "iqn.com.foobar:disk1" -------------- Object: index=14 type= state=limbo 0020 string : iSCSI name = "iqn.com.foobar:disk1" 0024 uint32 : iSCSI node index = 14 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/13-dd-deregistration000066400000000000000000000074751175631155400260140ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" -------------- Object: index=14 type= state=limbo 0020 string : iSCSI name = "iqn.com.foobar:disk1" 0024 uint32 : iSCSI node index = 14 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/14-dd-registration000066400000000000000000000076521175631155400255010ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 6 0814 string : DD member iSCSI name = "isns.client1" 0813 uint32 : DD member iSCSI index = 10 0814 string : DD member iSCSI name = "isns.client2" -------------- Object: index=14 type= state=limbo 0020 string : iSCSI name = "iqn.com.foobar:disk1" 0024 uint32 : iSCSI node index = 14 open-iscsi-2.0.873/utils/open-isns/tests/data/test02/15-dd-deregistration000066400000000000000000000070221175631155400260020ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test02/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client2.isns-test.eu" 0607v string : Policy allowed node name = "isns.client2" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... 0608v uint32 : Policy allowed node type = Target -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 6 -------------- Object: index=7 type= state=mature parent=5 0010 ipaddr : Portal IP address = 127.1.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 7 -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.1.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 -------------- Object: index=9 type= state=mature 0001 string : Entity identifier = "client2.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:24:04 2007 0007 uint32 : Entity index = 9 -------------- Object: index=10 type= state=mature parent=9 0020 string : iSCSI name = "isns.client2" 0021 uint32 : iSCSI node type = Target 0024 uint32 : iSCSI node index = 10 -------------- Object: index=11 type= state=mature parent=9 0010 ipaddr : Portal IP address = 127.1.0.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=9 0030 string : Portal group name = "isns.client2" 0031 ipaddr : Portal group address = 127.1.0.2 0032 uint32 : Portal group port = 3260/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=14 type= state=limbo 0020 string : iSCSI name = "iqn.com.foobar:disk1" 0024 uint32 : iSCSI node index = 14 open-iscsi-2.0.873/utils/open-isns/tests/data/test03/000077500000000000000000000000001175631155400222245ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test03/01-enroll000066400000000000000000000014731175631155400236650ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test03/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test03/02-registration000066400000000000000000000036201175631155400251010ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test03/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:36:35 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test03/03-unregistration000066400000000000000000000036061175631155400254510ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test03/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:25:47 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=limbo 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test03/04-unregistration000066400000000000000000000014731175631155400254520ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test03/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test03/99-unregistration000066400000000000000000000011241175631155400254610ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test03/server0/database Last EID: 1 Last Index: 7 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... open-iscsi-2.0.873/utils/open-isns/tests/data/test04/000077500000000000000000000000001175631155400222255ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test04/01-enroll000066400000000000000000000014731175631155400236660ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test04/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test04/02-registration000066400000000000000000000036201175631155400251020ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test04/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:38:41 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test04/03-restart000066400000000000000000000036201175631155400240550ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test04/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:38:41 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test04/04-query000066400000000000000000000016221175631155400235370ustar00rootroot00000000000000object[0] = 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:38:42 2007 0007 uint32 : Entity index = 4 object[1] = 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 object[2] = 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 object[3] = 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test05/000077500000000000000000000000001175631155400222265ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test05/01-enroll000066400000000000000000000014731175631155400236670ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test05/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test05/02-registration000066400000000000000000000036161175631155400251100ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test05/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 20 0004 uint64 : Timestamp = Fri Sep 14 13:40:40 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test05/03-expired000066400000000000000000000014731175631155400240360ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test05/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/000077500000000000000000000000001175631155400222275ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test06/01-enroll000066400000000000000000000014731175631155400236700ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/02-registration000066400000000000000000000036201175631155400251040ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:51 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 5 -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/03-registration000066400000000000000000000036311175631155400251070ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 12 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=8 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:51 2007 0007 uint32 : Entity index = 8 -------------- Object: index=9 type= state=mature parent=8 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 9 -------------- Object: index=10 type= state=mature parent=8 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 10 -------------- Object: index=11 type= state=mature parent=8 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 11 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/04-registration000066400000000000000000000036401175631155400251100ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 16 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=12 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:51 2007 0007 uint32 : Entity index = 12 -------------- Object: index=13 type= state=mature parent=12 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=14 type= state=mature parent=12 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 14 -------------- Object: index=15 type= state=mature parent=12 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 15 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/05-dd-registration000066400000000000000000000043141175631155400254750ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 17 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=12 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:52 2007 0007 uint32 : Entity index = 12 -------------- Object: index=13 type= state=mature parent=12 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=14 type= state=mature parent=12 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 14 -------------- Object: index=15 type= state=mature parent=12 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 15 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" open-iscsi-2.0.873/utils/open-isns/tests/data/test06/06-registration000066400000000000000000000043141175631155400251110ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 20 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=17 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:52 2007 0007 uint32 : Entity index = 17 -------------- Object: index=13 type= state=mature parent=17 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=18 type= state=mature parent=17 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=19 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 19 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" open-iscsi-2.0.873/utils/open-isns/tests/data/test06/07-dd-registration000066400000000000000000000045561175631155400255070ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 20 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=17 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:52 2007 0007 uint32 : Entity index = 17 -------------- Object: index=13 type= state=mature parent=17 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=18 type= state=mature parent=17 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=19 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 19 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" 0816 uint32 : DD member portal index = 18 0817 ipaddr : DD member portal addr = 192.168.1.1 0818 uint32 : DD member portal port = 860/tcp open-iscsi-2.0.873/utils/open-isns/tests/data/test06/08-registration000066400000000000000000000056221175631155400251160ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 22 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=17 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:52 2007 0007 uint32 : Entity index = 17 -------------- Object: index=13 type= state=mature parent=17 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=18 type= state=limbo 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=19 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 19 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" 0816 uint32 : DD member portal index = 18 0817 ipaddr : DD member portal addr = 192.168.1.1 0818 uint32 : DD member portal port = 860/tcp -------------- Object: index=20 type= state=mature parent=17 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 20 -------------- Object: index=21 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 21 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/09-registration000066400000000000000000000056221175631155400251170ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 22 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=17 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:41:52 2007 0007 uint32 : Entity index = 17 -------------- Object: index=13 type= state=mature parent=17 0020 string : iSCSI name = "isns.client1" 0021 uint32 : iSCSI node type = Initiator 0024 uint32 : iSCSI node index = 13 -------------- Object: index=18 type= state=mature parent=17 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=19 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 19 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" 0816 uint32 : DD member portal index = 18 0817 ipaddr : DD member portal addr = 192.168.1.1 0818 uint32 : DD member portal port = 860/tcp -------------- Object: index=20 type= state=limbo 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 20 -------------- Object: index=21 type= state=mature parent=17 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 21 open-iscsi-2.0.873/utils/open-isns/tests/data/test06/10-unregistration000066400000000000000000000032041175631155400254440ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 22 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=13 type= state=limbo 0020 string : iSCSI name = "isns.client1" 0024 uint32 : iSCSI node index = 13 -------------- Object: index=18 type= state=limbo 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" 0816 uint32 : DD member portal index = 18 0817 ipaddr : DD member portal addr = 192.168.1.1 0818 uint32 : DD member portal port = 860/tcp open-iscsi-2.0.873/utils/open-isns/tests/data/test06/11-registration000066400000000000000000000045561175631155400251150ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test06/server0/database Last EID: 1 Last Index: 24 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b7 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=22 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 21 11:23:54 2007 0007 uint32 : Entity index = 22 -------------- Object: index=13 type= state=mature parent=22 0020 string : iSCSI name = "isns.client1" 0024 uint32 : iSCSI node index = 13 0021 uint32 : iSCSI node type = Initiator -------------- Object: index=18 type= state=mature parent=22 0010 ipaddr : Portal IP address = 192.168.1.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 18 -------------- Object: index=23 type= state=mature parent=22 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 192.168.1.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 23 -------------- Object: index=16 type= state=mature 0811 uint32 : DD ID = 1 0812 string : DD name = "isns.dd1" 081e uint32 : DD features = 0813 uint32 : DD member iSCSI index = 13 0814 string : DD member iSCSI name = "isns.client1" 0816 uint32 : DD member portal index = 18 0817 ipaddr : DD member portal addr = 192.168.1.1 0818 uint32 : DD member portal port = 860/tcp open-iscsi-2.0.873/utils/open-isns/tests/data/test07/000077500000000000000000000000001175631155400222305ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test07/01-enroll000066400000000000000000000015661175631155400236740ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test07/server0/database Last EID: 1 Last Index: 4 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 0004 uint64 : Timestamp = Fri Sep 14 13:42:57 2007 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test07/02-registration000066400000000000000000000040351175631155400251060ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test07/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 0004 uint64 : Timestamp = Fri Sep 14 13:42:57 2007 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=4 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:42:57 2007 0007 uint32 : Entity index = 4 -------------- Object: index=5 type= state=mature parent=4 0020 string : iSCSI name = "isns.client1" 0024 uint32 : iSCSI node index = 5 0021 uint32 : iSCSI node type = Initiator -------------- Object: index=6 type= state=mature parent=4 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 65535/tcp 0013 uint32 : ESI interval = 5 -------------- Object: index=7 type= state=mature parent=4 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 7 open-iscsi-2.0.873/utils/open-isns/tests/data/test07/03-expired000066400000000000000000000015661175631155400240430ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test07/server0/database Last EID: 1 Last Index: 8 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 0004 uint64 : Timestamp = Fri Sep 14 13:42:57 2007 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test07/04-registration000066400000000000000000000051071175631155400251110ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test07/server0/database Last EID: 1 Last Index: 14 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 0004 uint64 : Timestamp = Fri Sep 14 13:43:12 2007 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 -------------- Object: index=8 type= state=mature 0001 string : Entity identifier = "client1.isns-test.eu" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 14 13:43:12 2007 0007 uint32 : Entity index = 8 -------------- Object: index=9 type= state=mature parent=8 0020 string : iSCSI name = "isns.client1" 0024 uint32 : iSCSI node index = 9 0021 uint32 : iSCSI node type = Initiator -------------- Object: index=10 type= state=mature parent=8 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 860/tcp 0016 uint32 : Portal index = 10 0014 uint32 : ESI port = 65535/tcp 0013 uint32 : ESI interval = 5 -------------- Object: index=11 type= state=mature parent=8 0010 ipaddr : Portal IP address = 127.0.0.1 0011 uint32 : Portal TCP/UDP port = 1/tcp 0016 uint32 : Portal index = 11 -------------- Object: index=12 type= state=mature parent=8 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 860/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 12 -------------- Object: index=13 type= state=mature parent=8 0030 string : Portal group name = "isns.client1" 0031 ipaddr : Portal group address = 127.0.0.1 0032 uint32 : Portal group port = 1/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 13 open-iscsi-2.0.873/utils/open-isns/tests/data/test07/05-expired000066400000000000000000000015671175631155400240460ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test07/server0/database Last EID: 1 Last Index: 14 -------------- Object: index=1 type= state=mature PRIVATE 0001 string : Entity identifier = "CONTROL" 0007 uint32 : Entity index = 1 0004 uint64 : Timestamp = Fri Sep 14 13:43:12 2007 -------------- Object: index=2 type= state=mature parent=1 PRIVATE 0601v string : Security Policy Index = "client1.isns-test.eu" 0607v string : Policy allowed node name = "isns.client1" 0603v opaque : DSA security key = <30 82 01 b6 30 82 01 2b 06 07 2a 86 48 ce 38 04 01 30 82 01... -------------- Object: index=3 type= state=mature parent=1 PRIVATE 0020 string : iSCSI name = "isns.control" 0021 uint32 : iSCSI node type = 0024 uint32 : iSCSI node index = 3 open-iscsi-2.0.873/utils/open-isns/tests/data/test08/000077500000000000000000000000001175631155400222315ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test08/01-pauw1000066400000000000000000000117401175631155400234320ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test08/server0/database Last EID: 1 Last Index: 15 -------------- Object: index=1 type= state=mature 0001 string : Entity identifier = "cyan.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 15:15:41 2007 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0024 uint32 : iSCSI node index = 2 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (10 GB)" 002a string : iSCSI auth method = "None" -------------- Object: index=3 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0024 uint32 : iSCSI node index = 3 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ntfs)" 002a string : iSCSI auth method = "None" -------------- Object: index=4 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0024 uint32 : iSCSI node index = 4 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ext3)" 002a string : iSCSI auth method = "CHAP" -------------- Object: index=5 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0024 uint32 : iSCSI node index = 5 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (1 GB)" 002a string : iSCSI auth method = "None" -------------- Object: index=6 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0024 uint32 : iSCSI node index = 6 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (40 GB)" 002a string : iSCSI auth method = "CHAP" -------------- Object: index=7 type= state=mature parent=1 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "test" 002a string : iSCSI auth method = "None" -------------- Object: index=8 type= state=mature parent=1 0010 ipaddr : Portal IP address = 10.0.0.1 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0016 uint32 : Portal index = 8 -------------- Object: index=9 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 9 0033 uint32 : Portal group tag = 1 -------------- Object: index=10 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 10 0033 uint32 : Portal group tag = 1 -------------- Object: index=11 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 11 0033 uint32 : Portal group tag = 1 -------------- Object: index=12 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 12 0033 uint32 : Portal group tag = 1 -------------- Object: index=13 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 13 0033 uint32 : Portal group tag = 1 -------------- Object: index=14 type= state=mature parent=1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0031 ipaddr : Portal group address = 10.0.0.1 0032 uint32 : Portal group port = 3260/tcp 0034 uint32 : Portal group index = 14 0033 uint32 : Portal group tag = 1 open-iscsi-2.0.873/utils/open-isns/tests/data/test09/000077500000000000000000000000001175631155400222325ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test09/01-pauw2000066400000000000000000000026021175631155400234310ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test09/server0/database Last EID: 1 Last Index: 9 -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 15:18:04 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 56288/tcp 0013 uint32 : ESI interval = 300 -------------- Object: index=7 type= state=mature parent=5 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "iqn.2005-03.org.open-iscsi:blue" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 33849/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test10/000077500000000000000000000000001175631155400222225ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test10/01-pauw3000066400000000000000000000026011175631155400234210ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test10/server0/database Last EID: 1 Last Index: 9 -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 16:34:30 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 56288/tcp 0013 uint32 : ESI interval = 10 -------------- Object: index=7 type= state=mature parent=5 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "iqn.2005-03.org.open-iscsi:blue" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 33849/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test10/02-expired000066400000000000000000000026011175631155400240230ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test10/server0/database Last EID: 1 Last Index: 9 -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 16:34:30 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 56288/tcp 0013 uint32 : ESI interval = 10 -------------- Object: index=7 type= state=mature parent=5 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "iqn.2005-03.org.open-iscsi:blue" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 33849/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test10/03-pauw3000066400000000000000000000026011175631155400234230ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test10/server0/database Last EID: 1 Last Index: 9 -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 16:34:51 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 56288/tcp 0013 uint32 : ESI interval = 10 -------------- Object: index=7 type= state=mature parent=5 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "iqn.2005-03.org.open-iscsi:blue" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 33849/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test10/04-expired000066400000000000000000000026011175631155400240250ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test10/server0/database Last EID: 1 Last Index: 9 -------------- Object: index=5 type= state=mature 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Mon Sep 17 16:34:51 2007 0007 uint32 : Entity index = 5 -------------- Object: index=6 type= state=mature parent=5 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0016 uint32 : Portal index = 6 0014 uint32 : ESI port = 56288/tcp 0013 uint32 : ESI interval = 10 -------------- Object: index=7 type= state=mature parent=5 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0024 uint32 : iSCSI node index = 7 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" -------------- Object: index=8 type= state=mature parent=5 0030 string : Portal group name = "iqn.2005-03.org.open-iscsi:blue" 0031 ipaddr : Portal group address = 192.168.1.2 0032 uint32 : Portal group port = 33849/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 8 open-iscsi-2.0.873/utils/open-isns/tests/data/test11/000077500000000000000000000000001175631155400222235ustar00rootroot00000000000000open-iscsi-2.0.873/utils/open-isns/tests/data/test11/01-pauw4000066400000000000000000000026451175631155400234330ustar00rootroot00000000000000Dumping database contents Backend: /tmp/isns-test/test11/server0/database Last EID: 1 Last Index: 5 -------------- Object: index=1 type= state=mature 0001 string : Entity identifier = "troopa.nki.nl" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 7200 0004 uint64 : Timestamp = Fri Sep 21 09:37:10 2007 0007 uint32 : Entity index = 1 -------------- Object: index=2 type= state=mature parent=1 0010 ipaddr : Portal IP address = 192.168.1.40 0011 uint32 : Portal TCP/UDP port = 3229/tcp 0017 uint32 : SCN port = 3230/tcp 0014 uint32 : ESI port = 3230/tcp 0013 uint32 : ESI interval = 300 0016 uint32 : Portal index = 2 -------------- Object: index=3 type= state=mature parent=1 0030 string : Portal group name = "iqn.1991-05.com.microsoft:orange" 0031 ipaddr : Portal group address = 192.168.1.40 0032 uint32 : Portal group port = 3229/tcp 0033 uint32 : Portal group tag = 1 0034 uint32 : Portal group index = 3 -------------- Object: index=4 type= state=mature parent=1 0020 string : iSCSI name = "iqn.1991-05.com.microsoft:orange" 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "" 0024 uint32 : iSCSI node index = 4 open-iscsi-2.0.873/utils/open-isns/tests/genkey000066400000000000000000000102241175631155400213750ustar00rootroot00000000000000#!/bin/bash # # This is a very simple script to generate a DSA # key pair for authenticated iSNS. # # Copyright (C) 2007 Olaf Kirch # # This script is supposed to be run on the iSNS server. # For the first time, run as # isnsgenkey -s 1024 # This will generate a DSA params file, and a DSA private # and public key for the server. # # For each client, generate a key using # isnsgenkey # where is the fully qualified domain name. # This script will convert the FQDN to a valid iSNS # source name (isns.com.foobar.host) myname=`basename $0` etcdir=/etc/isns keystore=$etcdir/keystore dsa_parms=$etcdir/dsa.params dsa_bits=1024 opt_force=0 opt_server=0 function usage { cat <<-EOF >&2 $* Usage: $myname -s [-f] bits $myname clientname EOF exit 1 } function make_isns_name { OFS="$IFS" IFS=. set -- $* __result=$1; shift for part; do __result=$part.$__result done echo "isns.$__result" IFS="$OFS" } set -- `getopt b:fk:s $*` while [ $# -gt 0 ]; do opt=$1; shift case $opt in --) break;; -b) dsa_bits=$1; shift;; -f) opt_force=1;; -k) dsa_priv=$1; shift;; -s) opt_server=1;; *) usage "Unknown option $opt";; esac done if [ `id -un` != "root" -a $opt_force -eq 0 ]; then echo "$myname: should be run by super user only" >&2 exit 1 fi # All newly generated files should have restricted # access by default. umask 077 tmpdir=`mktemp -d /tmp/isnsgenkey.XXXXXX` trap "rm -rf $tmpdir" 0 1 2 15 if [ $opt_server -ne 0 ]; then [ $# -eq 1 ] || usage "Expected DSA key length" dsa_bits=$1 install -m 755 -d $etcdir if [ -z $dsa_priv ]; then dsa_priv=$etcdir/auth_key fi dsa_pub=$dsa_priv.pub dsa_copy= else [ $# -eq 1 ] || usage "Expected client name" client=`make_isns_name $1` mkdir -p $tmpdir$etcdir # build_client_conf $client > $tmpdir$etcdir/client.conf if [ -z $dsa_priv ]; then dsa_priv=$tmpdir$etcdir/auth_key fi dsa_pub=$dsa_priv.pub dsa_copy=$keystore/$client fi if [ -f $dsa_priv -a $opt_force -eq 0 ]; then cat <<-EOF ------------------------------------------------------------------ | There is already a DSA key installed in $dsa_priv. In order to | generate a new key, please specify the -f [force] option. ------------------------------------------------------------------ EOF exit 1 fi if [ ! -r $dsa_parms ]; then if [ $opt_server -eq 0 ]; then echo "Please run $myname in server-initialization mode first" >&2 exit 1 fi cat <<-EOF ------------------------------------------------------------------ | I will now try to generate a set of DSA parameters. This can be | a slow process, so please be patient. ------------------------------------------------------------------ EOF mkdir -p `dirname $dsa_parms` openssl dsaparam $dsa_bits -out $dsa_parms || exit 1 # DSA parameters are public chmod 644 $dsa_parms fi cat <&2 exit 1 fi if ! openssl dgst -dss1 -verify $dsa_pub -signature $tmpdir/test-sig /etc/hosts; then echo "DSA verification failed - aborting!" >&2 exit 1 fi od -tx1 $tmpdir/test-sig if [ $opt_server -eq 0 ]; then echo "Installing DSA public key as $dsa_copy" install -d -m 755 $keystore install -m 644 $dsa_pub $dsa_copy install -m 644 $etcdir/auth_key.pub $tmpdir$etcdir/server.pub tarball=auth-$client.tar.gz tar -C $tmpdir -czf $tarball .$etcdir cat <<-EOF ------------------------------------------------------------------ | Successfully packaged $tarball | Please copy this file to client $client and install ------------------------------------------------------------------ EOF fi open-iscsi-2.0.873/utils/open-isns/tests/harness.pl000066400000000000000000000437441175631155400222050ustar00rootroot00000000000000#!/usr/bin/perl use Getopt::Long; $__isns_verbose = 1; $__isns_security = 1; $__isns_bin = "../"; $__isns_seq = 0; $__isns_test_base = '/tmp/isns-test'; $__isns_test_dir = '/tmp/isns-test/test'; $__isns_stage = 1; $__isns_test_data = ''; $__isns_test_dump = ''; $__isns_passed = 0; $__isns_failed = 0; $__isns_warned = 0; @__isns_servers = (); %__isns_ignore_tag = ( "0004" => 1, # Timestamp "0603v" => 1, # DSA public key ); sub isns_fail { print "*** FAILURE ***\n"; $__isns_failed++; my $line; foreach $line (@_) { print "*** $line ***\n"; } } sub isns_pass { print "*** SUCCESS ***\n" if ($__isns_verbose > 1); $__isns_passed++; } sub isns_warn { printf "*** WARNING: %s ***\n", join(' ', @_); $__isns_warned++; } sub isns_die { printf "*** TERMINAL FAILURE: %s ***\n", join(' ', @_); $__isns_failed++; &isns_finish; die "Test aborted\n"; } sub isns_finish { my $pid; foreach $pid (@__isns_servers) { kill 15, $pid or &isns_warn("Cannot kill server process (pid=$pid): $!\n"); } &isns_report; } sub isns_report { print "*** Test $__isns_test_name complete."; print " PASSED: $__isns_passed" if ($__isns_passed); print " FAILED: $__isns_failed" if ($__isns_failed); print " WARNINGS: $__isns_warned" if ($__isns_warned); print " ***\n"; } sub isns_info { print @_ if ($__isns_verbose > 1); } sub isns_notice { print @_ if ($__isns_verbose > 0); } sub isns_stage { local($name, @msg) = @_; if ($name =~ m/^[0-9]/o) { $__isns_stage_name = $name; } else { $__isns_stage_name = sprintf "%02d-%s", $__isns_stage++, $name; } &isns_notice("*** $__isns_stage_name: ", @msg, " ***\n"); } sub build_config { local($src_file, $dst_file, *__subst) = @_; my $key; my $okey; my $value; my $sepa; my %subst; &isns_info("*** Building $src_file -> $dst_file\n"); # Translate all keys to lower case. foreach $key (keys(%__subst)) { $value = $__subst{$key}; $key =~ tr/A-Z/a-z/; $subst{$key} = $value; } # foreach $key (keys(%subst)) { # printf " %s -> %s\n", $key, $subst{$key}; # } open IN, "<$src_file" or die "$src_file: $!\n"; open OUT, ">$dst_file" or die "$dst_file: $!\n"; while () { $line = $_; if (m:(\S+)(\s*=\s*)(.*):o) { ($okey, $sepa, $value) = ($1, $2, $3); $key = $okey; $key =~ tr/A-Z/a-z/; if ($subst{$key}) { $line = "$okey$sepa$subst{$key}\n"; } } # Ignore unconfigured lines. next if ($line =~ m/\@[A-Z_]*\@/o); print OUT $line; } close OUT; close IN; } sub get_config_value { local($cfg_file, $item_name) = @_; my $result; my $name; my $value; $item_name =~ tr/A-Z/a-z/; open IN, "<$cfg_file" or die "$cfg_file: $!\n"; while () { chop; ($name, $value) = split(/\s+=\s+/, $_); $name =~ tr/A-Z/a-z/; if ($name eq $item_name) { $result = $value; last; } } close IN; return $result; } sub create_key { local($keyfile) = @_; if ($__isns_security) { &isns_info("*** Creating key at $keyfile\n"); system "./genkey -fsk $keyfile 2048 >${keyfile}.log 2>&1"; } return $keyfile; } sub create_server { local(*override) = @_; my %local_config; my $my_dir; my $handle; my $config; $handle = sprintf "server%d", $__isns_seq++; $my_dir = "$__isns_test_dir/${handle}"; mkdir $my_dir, 0700 or die "Cannot create $my_dir: $!\n"; $server_addr = "127.0.0.1:7770" unless ($server_addr); $config = "$my_dir/config"; $local_config{"SourceName"} = "isns.$handle"; $local_config{"Database"} = "$my_dir/database"; $local_config{"BindAddress"} = "$server_addr"; $local_config{"PIDFile"} = "$my_dir/pid"; $local_config{"ControlSocket"} = "$my_dir/control"; $local_config{"Security"} = $__isns_security; $local_config{"AuthKeyFile"} = &create_key("$my_dir/auth_key"); foreach $key (keys(%override)) { $local_config{$key} = $override{$key}; } &build_config('server.conf', $config, \%local_config); return $config; } sub create_client { local($server_config, $client_address) = @_; my %local_config; my $server_key; my $control_socket; my $server_addr; my $my_dir; my $handle; my $config; $handle = sprintf "client%d", $__isns_seq++; $my_dir = "$__isns_test_dir/${handle}"; mkdir $my_dir, 0700 or die "Cannot create $my_dir: $!\n"; $control_socket = &get_config_value($server_config, "ControlSocket"); $server_addr = &get_config_value($server_config, "BindAddress"); $server_addr = "127.0.0.1" unless ($server_addr); $config = "$my_dir/config"; $local_config{"SourceName"} = "isns.$handle"; $local_config{"AuthName"} = "$handle.isns-test.eu"; $local_config{"ServerAddress"} = $server_addr; $local_config{"ControlSocket"} = $control_socket; $local_config{"BindAddress"} = $client_address if ($client_address); $local_config{"server_config"} = $server_config; $local_config{"Security"} = $__isns_security; $local_config{"AuthKeyFile"} = &create_key("$my_dir/auth_key"); $local_config{"ServerKeyFile"} = &get_config_value($server_config, "AuthKeyFile") . ".pub"; &build_config('client.conf', $config, \%local_config); $__isns_data{$config,"server_config"} = $server_config; $__isns_data{$config} = %local_config; return $config; } sub get_logfile { local($config) = @_; my $dir; $dir = $config; $dir =~ s|/+[^/]+$||o; return "$dir/logfile"; } sub run_command { local(@cmd) = @_; my $status; my $cmd; $cmd = join(' ', @cmd); &isns_info("$cmd\n"); system "$cmd"; $status = $?; if ($status) { &isns_warn("Command failed, exit status $status"); print "*** Command was: $cmd ***\n"; return undef; } return 1; } sub isns_start_server { local($server_config) = @_; my $logfile; my $pidfile; my $pid; die "restart_server: missing server config argument!\n" unless(-f $server_config); $logfile = &get_logfile($server_config); $pidfile = &get_config_value($server_config, "PIDFile"); &isns_info("*** Starting server (logging to $logfile)\n"); $pid = fork(); if ($pid) { my $retry; if ($pidfile) { for ($retry = 0; $retry < 5; $retry++) { last if (-f $pidfile); sleep 1; } $pid = `cat $pidfile` if ($pidfile); chop($pid); } &isns_info("*** Started server (pid=$pid) ***\n"); push(@__isns_servers, $pid); return $pid; } &isns_info("${__isns_bin}isnsd -c $server_config -f -d all\n"); exec "${__isns_bin}isnsd -c $server_config -f -d all >$logfile 2>&1 &" or die "Unable to run isnsd: $!\n"; } sub isns_stop_server { local($pid) = @_; my @list; my $p; kill 15, $pid or &isns_warn("Cannot kill server process (pid=$pid): $!\n"); foreach $p (@__isns_servers) { append(@list, $p) unless ($p == $pid); } @__isns_servers = @list; } sub isns_restart_server { local($pid, $server_config); if ($_[0] =~ m:^\d+$:o) { $pid = shift(@_); } else { if ($#__isns_servers < 0) { &isns_warn("isns_restart_server: no server running\n"); return 0; } $pid = $__isns_servers[0]; } $server_config = shift(@_); &isns_stop_server($pid); return &isns_start_server($server_config); } sub isns_verify_db { local($stage, $server_config); my $dump_file; my $data_file; if ($_[0] =~ m/^\d/o) { $stage = shift(@_); } else { $stage = $__isns_stage_name; } $server_config = shift(@_); die "Test case forgot to call test_prep" unless($__isns_test_data); $dump_file = "$__isns_test_dump/$stage"; unless (&run_command("${__isns_bin}/isnsd -c $server_config --dump-db > $dump_file")) { &isns_fail; return 0; } # See if the reference data file exists. If it # doesn't, this means we're priming the test case. # Just copy the dump file. $data_file = "$__isns_test_data/$stage"; unless (-f $data_file) { print "*** Saving database dump for stage $stage ***\n"; mkdir $__isns_test_data, 0755; system "cp $dump_file $data_file"; return 1; } &isns_info("*** Verifying database dump for stage $stage ***\n"); if (&verify_dump($stage, $data_file, $dump_file)) { &isns_pass; } else { if ($__isns_verbose > 1) { system("diff -u -ITimestamp -I'DSA security key' $data_file $dump_file"); } &isns_fail; } return 1; } sub verify_db { &isns_verify_db(@_); } sub verify_response { local($stage, $client_config) = @_; my $dump_file; my $data_file; die "Test case forgot to call test_prep" unless($__isns_test_data); $dump_file = &get_logfile($client_config); # See if the reference data file exists. If it # doesn't, this means we're priming the test case. # Just copy the dump file. $data_file = "$__isns_test_data/$stage"; unless (-f $data_file) { print "*** Saving data for stage $stage ***\n"; mkdir $__isns_test_data, 0755; system "cp $dump_file $data_file"; return 1; } &isns_info("*** Verifying data for stage $stage ***\n"); if (&verify_query($stage, $data_file, $dump_file)) { &isns_pass; } else { &isns_fail("Query response returns unexpected data"); system "cp $dump_file $__isns_test_dump/$stage"; print "*** Saved dump as $__isns_test_dump/$stage\n"; print "*** Reference data in $data_file\n"; if ($__isns_verbose > 1) { system("diff -u -ITimestamp -I'DSA security key' $data_file $dump_file"); } } return 1; } sub verify_dump { local($stage, $data_file, $dump_file) = @_; my $line; my @dump; my @data; my @obj1; my @obj2; @dump = &load_dump($dump_file); @data = &load_dump($data_file); &skip_header(\@dump); &skip_header(\@data); while (1) { $line++; @obj1 = &get_next_object(\@dump); @obj2 = &get_next_object(\@data); last unless(@obj1 || @obj2); unless (@obj1 && @obj2) { print STDERR "*** $stage: Excess data at end of dump\n"; return 0; } unless (&compare_objects(\@obj1, \@obj2)) { print STDERR "*** Object mismatch (object $line):\n"; print STDERR "Expected:\n "; print STDERR join("\n ", @obj2), "\n"; print STDERR "Got:\n "; print STDERR join("\n ", @obj1), "\n"; return 0; } } if (@data) { print STDERR "*** $stage: Unexpected end of dump at line $line\n"; return 0; } return 1; } sub skip_header { local(*list) = @_; local($_); while ($_ = shift(@list)) { last if (/^-/o); } } sub get_next_object { local(*list) = @_; local($_, $header, @result); my @tags; while ($_ = shift(@list)) { next if (/^-/o); if (/^\s+([0-9a-fv]+)\s+/o) { next if ($__isns_ignore_tag{$1}); push(@tags, $_); } else { if (@result) { unshift(@list, $_); last; } push(@result, $_); } #print "### $_\n"; } if (@tags) { push(@result, sort(@tags)); } return @result; } sub compare_objects { local(*a, *b) = @_; local($i); return 0 unless ($#a == $#b); for ($i = 0; $i <= $#a; $i++) { return 0 unless ($a[$i] eq $b[$i]); } return 1; } sub verify_query { local($stage, $data_file, $dump_file) = @_; my $line; my @dump; my @data; @dump = &load_dump($dump_file); @data = &load_dump($data_file); while (@dump) { $line++; unless (@data) { print STDERR "*** $stage: Excess data in dump at line $line\n"; return 0; } $a = shift(@dump); $b = shift(@data); if ($a =~ /^\S/o) { next if ($a eq $b); print STDERR "*** $stage: Mismatch at line $line ***\n"; print STDERR "*** Found: $a\n"; print STDERR "*** Expected: $b\n"; return 0; } ($nix, $a_tag, $a_value) = split(/\s+/, $a, 3); ($nix, $b_tag, $b_value) = split(/\s+/, $b, 3); if ($a_tag ne $b_tag) { print STDERR "*** $stage: Tag mismatch at line $line\n"; print STDERR "*** Found: $a\n"; print STDERR "*** Expected: $b\n"; return 0; } next if ($__isns_ignore_tag{$a_tag}); if ($a_value ne $b_value) { print STDERR "*** $stage: Value mismatch at line $line (tag $a_tag)\n"; print STDERR "*** Found: $a\n"; print STDERR "*** Expected: $b\n"; return 0; } } if (@data) { print STDERR "*** $stage: Unexpected end of dump at line $line\n"; return 0; } return 1; } sub load_dump { local($filename) = @_; my @result; open IN, $filename or die "Unable to open $filename: $!\n"; while () { chop; push(@result, $_); } close IN; return @result; } sub run_client { local($config, @args) = @_; my $logfile; my $cmd; $logfile = &get_logfile($config); $cmd = "${__isns_bin}/isnsadm -c $client_config " . join(' ', @args); if (&run_command("$cmd >$logfile")) { return $logfile; } return undef; } sub __isns_enroll_client { local($client_config, @extra_args) = @_; my $source_name; my $auth_name; my $auth_key; my @args; $source_name = &get_config_value($client_config, "SourceName"); $auth_name = &get_config_value($client_config, "AuthName"); $auth_key = &get_config_value($client_config, "AuthKeyFile"); push(@args, "--local --enroll $auth_name node-name=$source_name"); push(@args, " key=${auth_key}.pub") if ($auth_key); push(@args, @extra_args) if (@extra_args); &run_client($client_config, @args); } sub isns_enroll_client { local($client, @args) = @_; my $server; $server = $__isns_data{$client,"server_config"}; &isns_stage("enroll", "Enrolling client"); &__isns_enroll_client($client, @args); &verify_db($__isns_stage_name, $server); } sub enroll_client { print "*** Enrolling client ***\n"; &__isns_enroll_client(@_); } sub __isns_register_client { local($client_config, @extra_args) = @_; my @args; push(@args, "--register"); push(@args, @extra_args) if (@extra_args); &run_client($client_config, @args); } sub isns_register_client { local($client, @args) = @_; my $server; $server = $__isns_data{$client,"server_config"}; &isns_stage("registration", "Registering client " . join(' ', @args)); &__isns_register_client($client, @args); &verify_db($__isns_stage_name, $server); } sub register_client { print "*** Registering client ***\n"; &__isns_register_client(@_); } sub __isns_query_objects { local($client_config, @extra_args) = @_; my @args; push(@args, "--query"); push(@args, @extra_args) if (@extra_args); return &run_client($client_config, @args); } sub isns_query_objects { local($client, @args) = @_; &isns_stage("query", "Querying " . join(' ', @args)); &__isns_query_objects($client, @args); &verify_response($__isns_stage_name, $client); } sub query_objects { print "*** Querying objects ***\n"; __isns_query_objects(@_); } sub isns_query_eid { local($client_config, @extra_args) = @_; my $logfile; my @args; local($eid); push(@args, "--query-eid"); push(@args, @extra_args) if (@extra_args); &isns_info("*** Querying for EID ***\n"); $logfile = &run_client($client_config, @args); if ($logfile) { $eid = `cat $logfile`; unless ($eid) { &isns_fail("Server reports empty EID"); } chop($eid); } return $eid; } sub __isns_unregister_client { local($client_config, @extra_args) = @_; my @args; push(@args, "--deregister"); push(@args, @extra_args) if (@extra_args); &run_client($client_config, @args); } sub isns_unregister_client { my $stage = 0; my $client; my $server; my $eid; if ($_[0] =~ m/^\d/o) { &isns_stage(shift(@_), "Unregister client"); } else { &isns_stage("unregistration", "Unregister client"); } $client = shift(@_); unless (@_) { $eid = &isns_query_eid($client); push(@_, "eid=$eid"); } &__isns_unregister_client($client, @_); $server = $__isns_data{$client,"server_config"}; &verify_db($__isns_stage_name, $server); } sub unregister_client { &isns_info("*** Unregistering client ***\n"); &__isns_unregister_client(@_); } sub __isns_register_domain { local($client_config, @extra_args) = @_; my @args; push(@args, "--local --dd-register"); push(@args, @extra_args) if (@extra_args); &run_client($client_config, @args); } sub isns_register_domain { local($client, @args) = @_; my $server; &isns_stage("dd-registration", "Registering DD " . join(' ', @args)); &__isns_register_domain($client, @args); $server = $__isns_data{$client,"server_config"}; &isns_verify_db($server); } sub register_domain { &isns_info("*** Registering DD ***\n"); &__isns_register_domain(@_); } sub __isns_deregister_domain { local($client_config, @extra_args) = @_; my @args; push(@args, "--local --dd-deregister"); push(@args, @extra_args) if (@extra_args); &run_client($client_config, @args); } sub isns_deregister_domain { local($client, @args) = @_; my $server; &isns_stage("dd-deregistration", "Deregistering DD (members)" . join(' ', @args)); &__isns_deregister_domain($client, @args); $server = $__isns_data{$client,"server_config"}; &isns_verify_db($server); } sub isns_external_test { local($client, @args) = @_; my $logfile; my $stage; my $cmd; $logfile = &get_logfile($client); $cmd = shift(@args); $stage = $cmd; $stage =~ s:.*/::o; $cmd = "${__isns_bin}/$cmd -c $client " . join(' ', @args); &isns_stage($stage, "Running external $cmd " . join(' ', @args)); unless (&run_command("$cmd >$logfile")) { return undef; } $server = $__isns_data{$client,"server_config"}; &isns_verify_db($server); } sub __isns_prep_test { local($name, $duration, @ARGV) = @_; GetOptions('verbose+' => \$__isns_verbose, "quiet" => \$__isns_quiet, "fast" => \$__isns_quick, "insecure" => \$__isns_insecure); $__isns_verbose = 0 if ($__isns_quiet); $__isns_security = 0 if ($__isns_insecure); if ($__isns_quick && $duration > 15) { print "*** Skipping $name (duration ~ $duration seconds) ***\n"; exit(0); } print "*** Starting $name ***\n"; printf "*** This test case will take about %u sec ***\n", $duration if ($duration); $__isns_test_name = $name; $__isns_test_dir = "$__isns_test_base/$name"; $__isns_test_dump = "$__isns_test_dir/dump"; $__isns_test_data = "data/$name"; # Be careful when removing test dir system "rm -rf $__isns_test_dir" if ($__isns_test_dir =~ m:/tmp/:o); mkdir $__isns_test_base, 0700; mkdir $__isns_test_dir, 0700; mkdir $__isns_test_dump, 0700; } sub test_prep { local($name, @args) = @_; __isns_prep_test($name, 0, @args); } sub isns_prep_slow_test { __isns_prep_test(@_); } # Sleep for a few seconds, giving the user some dots to keep # him occupied. sub isns_idle { local($time) = @_; if ($__isns_verbose == 0) { sleep $time; return; } $| = 1; print "Snooze"; while ($time--) { print "."; sleep 1; } print "\n"; $| = 0; } sub main { my $server_config; my $client_config; &test_prep; $server_config = &create_server; $client_config = &create_client($server_config); } #&main; 1; open-iscsi-2.0.873/utils/open-isns/tests/pauw1.c000066400000000000000000000151251175631155400213760ustar00rootroot00000000000000/* * Test case, captured from a Wasabi Storage Builder * registering itself. */ #include #include #include #include #include int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int c; while ((c = getopt(argc, argv, "c:d:")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); isns_assign_string(&isns_config.ic_source_name, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); attrs = ®->is_operating_attrs; #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) STR(ENTITY_IDENTIFIER, "cyan.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); U32(REGISTRATION_PERIOD, 31536000); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0", "Test (10 GB)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1", "160 GB disk (ntfs)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2", "160 GB disk (ext3)", "CHAP"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3", "Test (1 GB)", "None"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4", "Test (40 GB)", "CHAP"); TARGET("iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5", "test", "None"); isns_portal_parse(&portal_info, "10.0.0.1:3260/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); /* Mumbo jumbo encoding of portal groups */ U32(PG_TAG, 1); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4"); STR(PG_ISCSI_NAME, "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5"); /* Strictly speaking, a PGT not followed by any data is invalid. * * 5.6.5.1. * When a Portal is registered, the Portal attributes MAY * immediately be followed by a PGT attribute. The PGT attribute * SHALL be followed by the set of PG iSCSI Names representing * nodes that will be associated to the Portal using the indicated * PGT value. */ NIL(PG_TAG); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object(s)\n"); isns_simple_print(reg, isns_print_stdout); return 0; } /* Creating file DB backend (/var/lib/isns) DB: loading all objects from /var/lib/isns Next ESI message in 3600 seconds Incoming PDU xid=0001 seq=0 len=1208 func=DevAttrReg client first last Next message xid=0001 Received message ---DevAttrReg--- Source: 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" Message attributes: Operating attributes: 0001 string : Entity identifier = "cyan.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0006 uint32 : Registration Period = 31536000 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (10 GB)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ntfs)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "160 GB disk (ext3)" 002a string : iSCSI auth method = "CHAP" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (1 GB)" 002a string : iSCSI auth method = "None" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "Test (40 GB)" 002a string : iSCSI auth method = "CHAP" 0020 string : iSCSI name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0021 uint32 : iSCSI node type = Target 0022 string : iSCSI alias = "test" 002a string : iSCSI auth method = "None" 0010 ipaddr : Portal IP address = 10.0.0.1 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0033 uint32 : Portal group tag = 1 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-1" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-2" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-3" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-4" 0030 string : Portal group name = "iqn.2000-05.com.wasabisystems.storagebuilder:cyan-5" 0033 nil : Portal group tag = :: policy insecure function DevAttrReg (0001) permitted :: policy insecure source iqn.2000-05.com.wasabisystems.storagebuilder:cyan-0 permitted :: policy insecure operation DevAttrReg on Network Entity object permitted DB: Storing object 00000001 -> /var/lib/isns/00000001 DB: added object 1 (Network Entity) state 1 Segmentation fault */ open-iscsi-2.0.873/utils/open-isns/tests/pauw2.c000066400000000000000000000151211175631155400213730ustar00rootroot00000000000000/* * Test case, captured from iscsi-target * registering itself. */ #include #include #include #include #include #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int c; while ((c = getopt(argc, argv, "c:d:")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2007-03.com.example:stgt.disk" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 3260/tcp 0017 uint32 : SCN port = 42138/tcp 0020 string : iSCSI name = "iqn.2007-03.com.example:stgt.disk" 0021 uint32 : iSCSI node type = Target */ isns_assign_string(&isns_config.ic_source_name, "iqn.2007-03.com.example:stgt.disk"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = 1; /* Message attributes */ attrs = ®->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = ®->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:3260/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(SCN_PORT, 42138); STR(ISCSI_NAME, "iqn.2007-03.com.example:stgt.disk"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object #1\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0014 uint32 : ESI port = 56288/tcp 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" [...] response status 0x0003 (Invalid registration) This would fail because we got confused about EID in the replace case. */ isns_assign_string(&isns_config.ic_source_name, "iqn.2005-03.org.open-iscsi:blue"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = 1; /* Message attributes */ attrs = ®->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = ®->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:33849/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(ESI_PORT, 56288); STR(ISCSI_NAME, "iqn.2005-03.org.open-iscsi:blue"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, "blue.pauw.homeunix.net"); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object #2\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); return 0; } /* Creating file DB backend (/var/lib/isns) DB: loading all objects from /var/lib/isns Next ESI message in 3600 seconds Incoming PDU xid=0001 seq=0 len=232 func=DevAttrReg client first last Next message xid=0001 Received message :: policy insecure function DevAttrReg (0001) permitted :: policy insecure source iqn.2005-03.org.open-iscsi:blue permitted :: policy insecure operation DevAttrReg on object 00000001 (Network Entity) permitted Replacing Network Entity (id 1) DB: removed object 2 (Portal) DB: removed object 4 (iSCSI Portal Group) DB: removed object 3 (iSCSI Storage Node) DB: removed object 1 (Network Entity) DB: destroying object 2 (Portal) DB: Purging object 2 (/var/lib/isns/00000002) DB: destroying object 1 (Network Entity) DB: Purging object 1 (/var/lib/isns/00000001) DB: destroying object 3 (iSCSI Storage Node) DB: Purging object 3 (/var/lib/isns/00000003) DB: destroying object 4 (iSCSI Portal Group) DB: Purging object 4 (/var/lib/isns/00000004) :: policy insecure entity ID blue.pauw.homeunix.net permitted :: policy insecure operation DevAttrReg on Network Entity object permitted DB: Storing object 5 -> /var/lib/isns/00000005 DB: added object 5 (Network Entity) state 1 DB: Storing object 5 -> /var/lib/isns/00000005 isns_esi_callback(0x9dee788, 0x10) Deleting SCN registration for iqn.2007-03.com.example:stgt.disk isns_esi_callback(0x9deeae0, 0x10) isns_esi_callback(0x9deea30, 0x10) isns_esi_callback(0x9deec80, 0x10) SCN multicast isns_scn_callback(0x9deec80, 0x10) isns_esi_callback(0x9def4b0, 0xc) Enable ESI monitoring for entity 5 */ open-iscsi-2.0.873/utils/open-isns/tests/pauw3.c000066400000000000000000000072201175631155400213750ustar00rootroot00000000000000/* * This tests another problem reported by Albert, where a * re-registration shortly before ESI expiry would fail * to resurrect the registration properly. * * Usage: * pauw3 [options] timeout * * Where timeout is the delay until we try to re-register */ #include #include #include #include #include #include #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int opt_replace = 1; int c, n, timeout; while ((c = getopt(argc, argv, "c:d:n")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'n': opt_replace = 0; break; default: isns_fatal("Unknown option\n"); } } if (optind != argc - 1) isns_fatal("Need timeout argument\n"); timeout = parse_timeout(argv[optind]); isns_read_config(opt_configfile); /* ---DevAttrReg[REPLACE]--- Source: 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" Message attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" Operating attributes: 0001 string : Entity identifier = "blue.pauw.homeunix.net" 0002 uint32 : Entity protocol = iSCSI (2) 0010 ipaddr : Portal IP address = 192.168.1.2 0011 uint32 : Portal TCP/UDP port = 33849/tcp 0014 uint32 : ESI port = 56288/tcp 0020 string : iSCSI name = "iqn.2005-03.org.open-iscsi:blue" 0021 uint32 : iSCSI node type = Initiator 0022 string : iSCSI alias = "blue.pauw.homeunix.net" [...] response status 0x0003 (Invalid registration) This would fail because we got confused about EID in the replace case. */ isns_assign_string(&isns_config.ic_source_name, "iqn.2005-03.org.open-iscsi:blue"); for (n = 0; n < 2; ++n) { clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = opt_replace; /* Message attributes */ attrs = ®->is_message_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); /* Operating attributes */ attrs = ®->is_operating_attrs; STR(ENTITY_IDENTIFIER, "blue.pauw.homeunix.net"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.2:33849/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(ESI_PORT, 56288); STR(ISCSI_NAME, "iqn.2005-03.org.open-iscsi:blue"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, "blue.pauw.homeunix.net"); isns_simple_print(reg, isns_print_stdout); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("Unable to register object: %s\n", isns_strerror(status)); printf("Successfully registered object\n"); // isns_simple_print(reg, isns_print_stdout); isns_simple_free(reg); isns_client_destroy(clnt); if (n == 0) { printf("Sleeping for %d seconds\n", timeout); sleep(timeout); } } return 0; } open-iscsi-2.0.873/utils/open-isns/tests/pauw4.c000066400000000000000000000067001175631155400214000ustar00rootroot00000000000000/* * Test MS initiator registration. * The oddity about this is that the PG object precedes the * initiator object in the message. */ #include #include #include #include #include #include #define ADD(type, tag, value) \ isns_attr_list_append_##type(attrs, ISNS_TAG_##tag, value) #define STR(tag, value) ADD(string, tag, value) #define U32(tag, value) ADD(uint32, tag, value) #define NIL(tag) isns_attr_list_append_nil(attrs, ISNS_TAG_##tag) #define TARGET(name, alias, auth) \ STR(ISCSI_NAME, name); \ U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); \ STR(ISCSI_ALIAS, alias); \ STR(ISCSI_AUTHMETHOD, auth) int main(int argc, char **argv) { const char *opt_configfile = ISNS_DEFAULT_ISNSADM_CONFIG; isns_client_t *clnt; isns_attr_list_t *attrs; isns_simple_t *reg; isns_portal_info_t portal_info; uint32_t status; int opt_replace = 1; int c; while ((c = getopt(argc, argv, "c:d:n")) != -1) { switch (c) { case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'n': opt_replace = 0; break; default: isns_fatal("Unknown option\n"); } } isns_read_config(opt_configfile); isns_assign_string(&isns_config.ic_source_name, "iqn.1991-05.com.microsoft:orange"); clnt = isns_create_default_client(NULL); reg = isns_simple_create(ISNS_SCN_DEREGISTER, clnt->ic_source, NULL); /* Message attributes */ attrs = ®->is_message_attrs; STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_error("SCNDereg failed: %s\n", isns_strerror(status)); isns_simple_free(reg); reg = isns_simple_create(ISNS_DEVICE_DEREGISTER, clnt->ic_source, NULL); attrs = ®->is_operating_attrs; STR(ENTITY_IDENTIFIER, "troopa.nki.nl"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.40:3229/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("DevDereg failed: %s\n", isns_strerror(status)); isns_simple_free(reg); reg = isns_simple_create(ISNS_DEVICE_ATTRIBUTE_REGISTER, clnt->ic_source, NULL); reg->is_replace = opt_replace; attrs = ®->is_operating_attrs; STR(ENTITY_IDENTIFIER, "troopa.nki.nl"); U32(ENTITY_PROTOCOL, 2); isns_portal_parse(&portal_info, "192.168.1.40:3229/tcp", NULL); isns_portal_to_attr_list(&portal_info, ISNS_TAG_PORTAL_IP_ADDRESS, ISNS_TAG_PORTAL_TCP_UDP_PORT, attrs); U32(SCN_PORT, 3230); U32(ESI_PORT, 3230); U32(PG_TAG, 1); STR(PG_ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); STR(ISCSI_NAME, "iqn.1991-05.com.microsoft:orange"); U32(ISCSI_NODE_TYPE, ISNS_ISCSI_INITIATOR_MASK); STR(ISCSI_ALIAS, ""); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("DevAttrReg failed: %s\n", isns_strerror(status)); isns_simple_free(reg); reg = isns_simple_create(ISNS_DEVICE_GET_NEXT, clnt->ic_source, NULL); attrs = ®->is_message_attrs; NIL(ISCSI_NAME); attrs = ®->is_operating_attrs; U32(ISCSI_NODE_TYPE, ISNS_ISCSI_TARGET_MASK); NIL(ISCSI_NODE_TYPE); status = isns_client_call(clnt, ®); if (status != ISNS_SUCCESS) isns_fatal("DevGetNext failed: %s\n", isns_strerror(status)); isns_simple_free(reg); return 0; } open-iscsi-2.0.873/utils/open-isns/tests/server.conf000066400000000000000000000004231175631155400223450ustar00rootroot00000000000000BindAddress = @SERVER_ADDRESS@ SourceName = @SOURCE_NAME@ Database = @DB_PATH@ RegistrationPeriod = 2h ESIMinInterval = 1m ESIMinInterval = 5m Security = @NOT_SET@ AuthKeyFile = @AUTH_KEY@ ClientKeyStore = DB: PIDFile = @MYDIR@/pid ControlSocket = @MYDIR@/control open-iscsi-2.0.873/utils/open-isns/tests/test01.pl000066400000000000000000000011671175631155400216530ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # single client. push(@INC, "."); require "harness.pl"; &test_prep("test01", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); # 1: Enroll the test client &isns_enroll_client($client); # 2: Register an initiator with default portal &isns_register_client($client, "initiator portal"); # 3: Run a simple query &isns_query_objects($client, "eid"); # 99: Unregister client &isns_unregister_client("99-unregistration", $client); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test02.pl000066400000000000000000000033771175631155400216610ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # two clients, and simple DD functionality. push(@INC, "."); require "harness.pl"; &test_prep("test02", @ARGV); $server = &create_server; $client1 = &create_client($server, "127.1.0.1"); $client2 = &create_client($server, "127.1.0.2"); &isns_start_server($server); # 1: Enroll the client1 &isns_enroll_client($client1); # 2: Enroll the client1 &isns_enroll_client($client2, "node-type=target"); &isns_stage("registration", "Registering both clients"); &__isns_register_client($client1, "initiator portal"); &__isns_register_client($client2, "target portal"); &isns_verify_db($server); # Now each of the two clients should just see # itself &isns_query_objects($client1, "eid"); &isns_query_objects($client2, "eid"); # Register a DD linking the two nodes &isns_register_domain($client1, "member-name=isns.client1", "member-name=isns.client2"); # Now the clients should see each other &isns_query_objects($client1, "eid"); &isns_query_objects($client2, "eid"); # Initiator querying for target: &isns_query_objects($client1, "iscsi-node-type=Target"); # Add another member to this DD, and re-add client2 (making # sure the server doesn't generate dupes) &isns_register_domain($client1, "dd-id=1", "member-name=isns.client2", "member-name=iqn.com.foobar:disk1"); # Query the list of DDs we're a member of &isns_query_objects($client1, "dd-id"); # Remove some entries from the DD &isns_deregister_domain($client1, "1", "member-iscsi-idx=10"); &isns_deregister_domain($client1, "1", "member-name=iqn.com.foobar:disk1"); &isns_register_domain($client1, "dd-id=1", "member-name=isns.client2"); &isns_deregister_domain($client1, "1"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test03.pl000066400000000000000000000012651175631155400216540ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and unregistration. push(@INC, "."); require "harness.pl"; &test_prep("test03", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); &isns_enroll_client($client); &isns_register_client($client, "initiator portal"); # Unregistering the portal should leave the iscsi node and # portal group active, and move the portal to state limbo. &isns_unregister_client($client, "portal=127.0.0.1:860"); # As the iscsi node goes away, so should the whole entity &isns_unregister_client($client, "iscsi-name=isns.client1"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test04.pl000066400000000000000000000012441175631155400216520ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case verifies that the database remains intact # across server restarts. push(@INC, "."); require "harness.pl"; &test_prep("test04", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); &isns_enroll_client($client); &isns_register_client($client, "initiator portal"); # Restart the server, and make sure it still displays # the database properly &isns_stage("restart", "Restarting server process"); &isns_restart_server($server); &isns_verify_db($server); # Run a simple query &isns_query_objects($client, "iscsi-name"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test05.pl000066400000000000000000000010401175631155400216450ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case verifies entity expiry push(@INC, "."); require "harness.pl"; &isns_prep_slow_test("test05", 30, @ARGV); $server = &create_server({ "RegistrationPeriod" => "20s" }); $client = &create_client($server); &isns_start_server($server); &isns_enroll_client($client); &isns_register_client($client, "initiator portal"); &isns_stage("expired", "Waiting for registration period to expire (25s)"); &isns_idle(25); &isns_verify_db($server); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test06.pl000066400000000000000000000033041175631155400216530ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates DevAttrReg replace mode. push(@INC, "."); require "harness.pl"; &test_prep("test06", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); # 1: Enroll the client &isns_enroll_client($client); # 2: Register a simple initiator with one portal &isns_register_client($client, "initiator portal"); $eid = &isns_query_eid($client); unless ($eid) { &isns_die("Cannot obtain entity ID"); } # Now replace the portal with different values &isns_register_client($client, "--replace entity=$eid initiator portal=192.168.1.1:iscsi"); &isns_register_client($client, "--replace entity=$eid initiator portal=192.168.1.2:iscsi"); &isns_register_domain($client, "member-name=isns.client1"); # Replace our registration once more. Now the object index of the # initiator should not change, since it's a domain member now. &isns_register_client($client, "--replace entity=$eid initiator portal=192.168.1.1:iscsi"); # Make the portal a domain member too. Now even the portal index should stay # the same. Note that we do not replace the whole entity now, but just the # portal &isns_register_domain($client, "dd-id=1 member-addr=192.168.1.1 member-port=860"); &isns_register_client($client, "--replace --key portal=192.168.1.1:iscsi portal=192.168.1.2:iscsi"); &isns_register_client($client, "--replace --key portal=192.168.1.2:iscsi portal=192.168.1.1:iscsi"); # Now unregister the whole client, and re-register. # Portal and client index should remain the same &isns_unregister_client($client, "eid=$eid"); &isns_register_client($client, "initiator portal=192.168.1.1:iscsi"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test07.pl000066400000000000000000000020611175631155400216530ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates that the server discards portals # that do not respond to ESI messages push(@INC, "."); require "harness.pl"; &isns_prep_slow_test("test07", 30, @ARGV); $server = &create_server({ "ESIMinInterval" => "5s" }); $client = &create_client($server); &isns_start_server($server); # 1: Enroll the client &isns_enroll_client($client); # 2: Register a simple initiator with one portal &isns_register_client($client, "initiator portal,esi-port=65535,esi-interval=5"); &isns_stage("expired", "Waiting for ESI to expire (~15 sec)"); &isns_idle(15); &isns_verify_db($server); # 3: Register a simple initiator with two portals, one with ESI and one without. # When the ESI monitored portal expires, this should still take down # the whole network entity. &isns_register_client($client, "initiator portal,esi-port=65535,esi-interval=5 portal=127.0.0.1:1"); &isns_stage("expired", "Waiting for ESI to expire (~15 sec)"); &isns_idle(15); &isns_verify_db($server); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test08.pl000066400000000000000000000006731175631155400216630ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # single client. push(@INC, "."); require "harness.pl"; # For now, this one will run w/o security only push(@ARGV, '-i'); &test_prep("test08", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); &isns_external_test($client, "tests/pauw1"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test09.pl000066400000000000000000000006731175631155400216640ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # single client. push(@INC, "."); require "harness.pl"; # For now, this one will run w/o security only push(@ARGV, '-i'); &test_prep("test09", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); &isns_external_test($client, "tests/pauw2"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test10.pl000066400000000000000000000013601175631155400216460ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # single client. push(@INC, "."); require "harness.pl"; # For now, this one will run w/o security only push(@ARGV, '-i'); &isns_prep_slow_test("test10", 20, @ARGV); $server = &create_server({ "ESIMinInterval" => "10s" }); $client = &create_client($server); &isns_start_server($server); &isns_external_test($client, "tests/pauw3", "16"); &isns_stage("expired", "Waiting for ESI to come around"); &isns_idle(5); &isns_verify_db($server); &isns_external_test($client, "tests/pauw3", "-n", "16"); &isns_stage("expired", "Waiting for ESI to come around"); &isns_idle(5); &isns_verify_db($server); &isns_finish; open-iscsi-2.0.873/utils/open-isns/tests/test11.pl000066400000000000000000000006731175631155400216550ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (C) 2007 Olaf Kirch # # This test case validates registration and simple query of # single client. push(@INC, "."); require "harness.pl"; # For now, this one will run w/o security only push(@ARGV, '-i'); &test_prep("test11", @ARGV); $server = &create_server; $client = &create_client($server); &isns_start_server($server); &isns_external_test($client, "tests/pauw4"); &isns_finish; open-iscsi-2.0.873/utils/open-isns/timer.c000066400000000000000000000044561175631155400203240ustar00rootroot00000000000000/* * Timers (one-short and periodic) * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "util.h" typedef struct isns_timer isns_timer_t; struct isns_timer { isns_list_t it_list; time_t it_when; unsigned int it_period; isns_timer_callback_t * it_func; void * it_data; }; static ISNS_LIST_DECLARE(timers); static void __isns_arm_timer(isns_timer_t *tm) { isns_list_t *pos, *next; time_t when = tm->it_when; isns_list_foreach(&timers, pos, next) { isns_timer_t *cur = isns_list_item(isns_timer_t, it_list, pos); if (when < cur->it_when) break; } isns_item_insert_before(pos, &tm->it_list); } static isns_timer_t * __isns_create_timer(time_t when, unsigned int period, isns_timer_callback_t *fn, void *data) { isns_timer_t *tm; tm = isns_calloc(1, sizeof(*tm)); tm->it_when = when; tm->it_period = period; tm->it_func = fn; tm->it_data = data; return tm; } void isns_add_timer(unsigned int period, isns_timer_callback_t *fn, void *data) { isns_timer_t *tm; isns_assert(period); tm = __isns_create_timer(time(NULL) + period, period, fn, data); __isns_arm_timer(tm); } void isns_add_oneshot_timer(unsigned int expires, isns_timer_callback_t *fn, void *data) { isns_timer_t *tm; tm = __isns_create_timer(time(NULL) + expires, 0, fn, data); __isns_arm_timer(tm); } void isns_cancel_timer(isns_timer_callback_t *fn, void *data) { isns_list_t *pos, *next; isns_list_foreach(&timers, pos, next) { isns_timer_t *tm = isns_list_item(isns_timer_t, it_list, pos); if (tm->it_func == fn && (data == NULL || tm->it_data == data)) { isns_list_del(pos); isns_free(tm); } } } time_t isns_run_timers(void) { while (!isns_list_empty(&timers)) { isns_timer_t *tm = isns_list_item(isns_timer_t, it_list, timers.next); isns_timer_callback_t *func; time_t expire; void *data; expire = tm->it_when; if (time(NULL) < expire) return expire; isns_list_del(&tm->it_list); func = tm->it_func; data = tm->it_data; expire = 0; /* If it's a periodic timer, rearm it now. This allows * the timer callback to cancel the timer. */ if (tm->it_period) { tm->it_when = time(NULL) + tm->it_period; __isns_arm_timer(tm); } else { isns_free(tm); } func(data); } return 0; } open-iscsi-2.0.873/utils/open-isns/types.h000066400000000000000000000030601175631155400203430ustar00rootroot00000000000000/* * Open-iSNS types * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_TYPES_H #define ISNS_TYPES_H typedef struct isns_simple isns_simple_t; typedef struct isns_source isns_source_t; typedef struct isns_object isns_object_t; typedef struct isns_relation isns_relation_t; typedef struct isns_attr isns_attr_t; typedef struct isns_attr_list isns_attr_list_t; typedef struct isns_message isns_message_t; typedef struct isns_socket isns_socket_t; typedef struct isns_db isns_db_t; typedef struct isns_tag_type isns_tag_type_t; typedef const struct isns_object_template isns_object_template_t; typedef struct isns_authdata isns_authdata_t; typedef struct isns_security isns_security_t; typedef struct isns_principal isns_principal_t; typedef struct isns_policy isns_policy_t; typedef struct isns_keystore isns_keystore_t; typedef struct isns_scope isns_scope_t; typedef struct isns_portal_info isns_portal_info_t; typedef struct isns_server isns_server_t; typedef struct isns_db_event isns_db_event_t; typedef struct isns_bitvector isns_bitvector_t; typedef struct isns_object_list { unsigned int iol_count; isns_object_t ** iol_data; } isns_object_list_t; #define ISNS_OBJECT_LIST_INIT { .iol_count = 0, .iol_data = NULL } /* * An attribute list */ struct isns_attr_list { unsigned int ial_count; isns_attr_t ** ial_data; }; #define ISNS_ATTR_LIST_INIT { .ial_count = 0, .ial_data = NULL } /* * Function types. */ typedef void isns_print_fn_t(const char *, ...); typedef void isns_timer_callback_t(void *); #endif /* ISNS_TYPES_H */ open-iscsi-2.0.873/utils/open-isns/util.c000066400000000000000000000077661175631155400201700ustar00rootroot00000000000000/* * util.c * * Misc utility functions * * Copyright (C) 2006, 2007 Olaf Kirch */ #include #include #include #include #include #include "util.h" unsigned long parse_size(const char *arg) { unsigned long mult = 1, ret; char *s; ret = strtol(arg, &s, 0); switch (*s++) { case 'g': case 'G': mult = 1024 * 1024 * 1024; break; case 'm': case 'M': mult = 1024 * 1024; break; case 'k': case 'K': mult = 1024; break; case '\0': return ret; default: bad: err(1, "parse_size: unknown unit in \"%s\"\n", arg); } if (*s != '\0') goto bad; return mult * ret; } char * print_size(unsigned long size) { static char unit[] = "-kMG"; static char buffer[64]; unsigned int power = 0; while (size && !(size % 1024) && power < sizeof(unit)) { size /= 1024; power++; } if (!power) { snprintf(buffer, sizeof(buffer), "%lu", size); } else { snprintf(buffer, sizeof(buffer), "%lu%c", size, unit[power]); } return buffer; } unsigned int parse_count(const char *arg) { unsigned long ret; char *s; ret = strtoul(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"\n", arg); return ret; } int parse_int(const char *arg) { long ret; char *s; ret = strtol(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"\n", arg); return ret; } long long parse_longlong(const char *arg) { long long ret; char *s; ret = strtoll(arg, &s, 0); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"\n", arg); return ret; } double parse_double(const char *arg) { double ret; char *s; ret = strtod(arg, &s); if (*s != '\0') err(1, "parse_count: unexpected character in \"%s\"\n", arg); return ret; } unsigned int parse_timeout(const char *arg) { unsigned int v, ret = 0; char *s; do { v = strtoul(arg, &s, 10); switch (*s) { case '\0': ret += v; break; case 'd': v *= 24; case 'h': v *= 60; case 'm': v *= 60; case 's': ret += v; ++s; break; default: errx(1, "parse_timeout: unexpected character in \"%s\"\n", arg); } arg = s; } while (*arg); return ret; } void isns_string_array_append(struct string_array *array, const char *val) { if (!(array->count % 32)) { array->list = isns_realloc(array->list, (array->count + 32) * sizeof(val)); } array->list[array->count++] = val? isns_strdup(val) : NULL; } void isns_string_array_destroy(struct string_array *array) { unsigned int i; for (i = 0; i < array->count; ++i) isns_free(array->list[i]); isns_free(array->list); memset(array, 0, sizeof(*array)); } void isns_assign_string(char **var, const char *val) { char *s = NULL; if (val && !(s = isns_strdup(val))) errx(1, "out of memory"); if (*var) isns_free(*var); *var = s; } /* * Recursively create a directory */ int isns_mkdir_recursive(const char *pathname) { const char *orig_pathname = pathname; char *squirrel[64]; char *copy = NULL, *s; int ns = 0; if (!pathname || !strcmp(pathname, ".")) return 0; while (1) { if (mkdir(pathname, 0755) >= 0) { if (ns == 0) break; *squirrel[--ns] = '/'; continue; } if (errno == EEXIST) goto good; if (errno != ENOENT) goto bad; if (copy == NULL) { copy = isns_strdup(pathname); pathname = copy; } s = strrchr(copy, '/'); while (s > copy && s[-1] == '/') --s; *s = '\0'; isns_assert(ns < 64); squirrel[ns++] = s; if (s == copy) goto bad; } good: if (copy) isns_free(copy); errno = 0; return 0; bad: if (copy) isns_free(copy); perror(orig_pathname); return -1; } /* * This one differs from POSIX dirname; it does not * modify its argument */ const char * isns_dirname(const char *pathname) { static char buffer[4096]; char *s; strcpy(buffer, pathname); if ((s = strrchr(buffer, '/')) != NULL) { *s = '\0'; return buffer; } return "."; } open-iscsi-2.0.873/utils/open-isns/util.h000066400000000000000000000162401175631155400201600ustar00rootroot00000000000000/* * Utility functions * * Copyright (C) 2006, 2007 Olaf Kirch */ #ifndef UTIL_H #define UTIL_H #include #include #include #include #include #include // for strdup #include "types.h" #define array_num_elements(a) (sizeof(a) / sizeof((a)[0])) const char * isns_dirname(const char *); int isns_mkdir_recursive(const char *); extern const char *parser_separators; char * parser_get_next_line(FILE *); char * parser_get_next_word(char **); char * parser_get_rest_of_line(char **); int parser_split_line(char *, unsigned int, char **); unsigned long parse_size(const char *); unsigned int parse_count(const char *); int parse_int(const char *); long long parse_longlong(const char *); double parse_double(const char *); unsigned int parse_timeout(const char *); char * print_size(unsigned long); /* * Very simple and stupid string array. */ struct string_array { unsigned int count; char ** list; }; void isns_string_array_append(struct string_array *, const char *); void isns_string_array_destroy(struct string_array *); void isns_assign_string(char **, const char *); void isns_write_pidfile(const char *); void isns_update_pidfile(const char *); void isns_remove_pidfile(const char *); extern void isns_log_background(void); extern void isns_assert_failed(const char *, const char *, unsigned int); extern void isns_fatal(const char *, ...); extern void isns_warning(const char *, ...); extern void isns_error(const char *, ...); extern void isns_notice(const char *, ...); extern void isns_debug_general(const char *, ...); extern void isns_debug_socket(const char *, ...); extern void isns_debug_protocol(const char *, ...); extern void isns_debug_message(const char *, ...); extern void isns_debug_state(const char *, ...); extern void isns_debug_auth(const char *, ...); extern void isns_debug_scn(const char *, ...); extern void isns_debug_esi(const char *, ...); extern void isns_enable_debugging(const char *); extern int isns_debug_enabled(int); enum { DBG_GENERAL = 0, DBG_SOCKET, DBG_PROTOCOL, DBG_MESSAGE, DBG_STATE, DBG_AUTH, DBG_SCN, DBG_ESI, }; /* * There's no htonll yet */ #ifndef htonll # include # include # if __BYTE_ORDER == __BIG_ENDIAN # define htonll(x) (x) # define ntohll(x) (x) # elif __BYTE_ORDER == __LITTLE_ENDIAN # define htonll(x) __bswap_64(x) # define ntohll(x) __bswap_64(x) # endif #endif /* * One of the those eternal staples of C coding: */ #ifndef MIN # define MIN(a, b) ((a) < (b)? (a) : (b)) # define MAX(a, b) ((a) > (b)? (a) : (b)) #endif #define DECLARE_BITMAP(name, NBITS) \ uint32_t name[(NBITS+31) >> 5] = { 0 } #define __BIT_INDEX(nr) (nr >> 5) #define __BIT_MASK(nr) (1 << (nr & 31)) static inline void set_bit(uint32_t *map, unsigned int nr) { map[__BIT_INDEX(nr)] |= __BIT_MASK(nr); } static inline void clear_bit(uint32_t *map, unsigned int nr) { map[__BIT_INDEX(nr)] &= ~__BIT_MASK(nr); } static inline int test_bit(const uint32_t *map, unsigned int nr) { return !!(map[__BIT_INDEX(nr)] & __BIT_MASK(nr)); } /* * Dynamically sized bit vector */ extern isns_bitvector_t *isns_bitvector_alloc(void); extern void isns_bitvector_init(isns_bitvector_t *); extern void isns_bitvector_destroy(isns_bitvector_t *); extern void isns_bitvector_free(isns_bitvector_t *); extern int isns_bitvector_test_bit(const isns_bitvector_t *, unsigned int); extern int isns_bitvector_set_bit(isns_bitvector_t *, unsigned int); extern int isns_bitvector_clear_bit(isns_bitvector_t *, unsigned int); extern int isns_bitvector_is_empty(const isns_bitvector_t *); extern int isns_bitvector_intersect(const isns_bitvector_t *a, const isns_bitvector_t *b, isns_bitvector_t *result); extern void isns_bitvector_print(const isns_bitvector_t *, isns_print_fn_t *); extern void isns_bitvector_foreach(const isns_bitvector_t *bv, int (*cb)(uint32_t, void *), void *user_data); /* * List manipulation primites */ typedef struct isns_list isns_list_t; struct isns_list { isns_list_t * next; isns_list_t * prev; }; #define ISNS_LIST_DECLARE(list) \ isns_list_t list = { &list, &list } static inline void isns_list_init(isns_list_t *head) { head->next = head->prev = head; } static inline void __isns_list_insert(isns_list_t *prev, isns_list_t *item, isns_list_t *next) { item->next = next; item->prev = prev; next->prev = item; prev->next = item; } static inline void isns_list_append(isns_list_t *head, isns_list_t *item) { __isns_list_insert(head->prev, item, head); } static inline void isns_list_insert(isns_list_t *head, isns_list_t *item) { __isns_list_insert(head, item, head->next); } static inline void isns_item_insert_before(isns_list_t *where, isns_list_t *item) { __isns_list_insert(where->prev, item, where); } static inline void isns_item_insert_after(isns_list_t *where, isns_list_t *item) { __isns_list_insert(where, item, where->next); } static inline void isns_list_del(isns_list_t *item) { isns_list_t *prev = item->prev; isns_list_t *next = item->next; prev->next = next; next->prev = prev; item->next = item->prev = item; } static inline int isns_list_empty(const isns_list_t *head) { return head == head->next; } static inline void isns_list_move(isns_list_t *dst, isns_list_t *src) { isns_list_t *prev, *next; isns_list_t *head, *tail; if (isns_list_empty(src)) return; prev = dst->prev; next = dst; head = src->next; tail = src->prev; next->prev = tail; prev->next = head; head->prev = prev; tail->next = next; src->next = src->prev = src; } #define isns_list_item(type, member, ptr) \ container_of(type, member, ptr) #define isns_list_foreach(list, __pos, __next) \ for (__pos = (list)->next; \ (__pos != list) && (__next = __pos->next, 1); \ __pos = __next) #if 0 /* This is defined in stddef */ #define offsetof(type, member) ((unsigned long) &(((type *) 0)->member)) #endif #define container_of(type, member, ptr) \ ((type *) (((unsigned char *) ptr) - offsetof(type, member))) /* * Use isns_assert instead of libc's assert, so that the * message can be captured and sent to syslog. */ #define isns_assert(condition) do { \ if (!(condition)) \ isns_assert_failed(#condition, \ __FILE__, __LINE__); \ } while (0) #ifndef MDEBUG # define isns_malloc(size) malloc(size) # define isns_calloc(n, size) calloc(n, size) # define isns_realloc(p, size) realloc(p, size) # define isns_strdup(s) strdup(s) # define isns_free(p) free(p) #else # define isns_malloc(size) isns_malloc_fn(size, __FILE__, __LINE__) # define isns_calloc(n, size) isns_calloc_fn(n, size, __FILE__, __LINE__) # define isns_realloc(p, size) isns_realloc_fn(p, size, __FILE__, __LINE__) # define isns_strdup(s) isns_strdup_fn(s, __FILE__, __LINE__) # define isns_free(p) isns_free_fn(p, __FILE__, __LINE__) extern void * (*isns_malloc_fn)(size_t, const char *, unsigned int); extern void * (*isns_calloc_fn)(unsigned int, size_t, const char *, unsigned int); extern void * (*isns_realloc_fn)(void *, size_t, const char *, unsigned int); extern char * (*isns_strdup_fn)(const char *, const char *, unsigned int); extern void (*isns_free_fn)(void *, const char *, unsigned int); #endif #endif /* UTIL_H */ open-iscsi-2.0.873/utils/open-isns/vendor.c000066400000000000000000000017141175631155400204730ustar00rootroot00000000000000/* * iSNS vendor specific objects * * Copyright (C) 2007 Olaf Kirch */ #include #include #include "isns.h" #include "objects.h" #include "attrs.h" #include "vendor.h" #include "util.h" static uint32_t policy_attrs[] = { OPENISNS_TAG_POLICY_SPI, OPENISNS_TAG_POLICY_KEY, OPENISNS_TAG_POLICY_ENTITY, OPENISNS_TAG_POLICY_OBJECT_TYPE, OPENISNS_TAG_POLICY_NODE_NAME, OPENISNS_TAG_POLICY_NODE_TYPE, OPENISNS_TAG_POLICY_FUNCTIONS, OPENISNS_TAG_POLICY_VISIBLE_DD, OPENISNS_TAG_POLICY_DEFAULT_DD, }; static uint32_t policy_key_attrs[] = { OPENISNS_TAG_POLICY_SPI, }; isns_object_template_t isns_policy_template = { .iot_name = "Policy", .iot_handle = ISNS_OBJECT_TYPE_POLICY, .iot_attrs = policy_attrs, .iot_num_attrs = array_num_elements(policy_attrs), .iot_keys = policy_key_attrs, .iot_num_keys = array_num_elements(policy_key_attrs), .iot_container = &isns_entity_template, .iot_vendor_specific = 1, }; open-iscsi-2.0.873/utils/open-isns/vendor.h000066400000000000000000000025711175631155400205020ustar00rootroot00000000000000/* * iSNS "vendor-specific" protocol definitions * * Copyright (C) 2007 Olaf Kirch */ #ifndef ISNS_VENDOR_H #define ISNS_VENDOR_H #include "isns-proto.h" /* * We're poor, we don't own a OUI. Let's fake one. */ #define OPENISNS_VENDOR_OUI 0xFFFF00 #define OPENISNS_VENDOR_PREFIX (OPENISNS_VENDOR_OUI << 8) #define OPENISNS_IS_PRIVATE_ATTR(tag) (((tag) >> 16) == 0xFFFF) enum openisns_vendor_tag { /* Security Policy Identifier */ OPENISNS_TAG_POLICY_SPI = OPENISNS_VENDOR_PREFIX + ISNS_VENDOR_SPECIFIC_OTHER_BASE, __OPENISNS_TAG_POLICY_RESERVED, /* DSA signature key (public) */ OPENISNS_TAG_POLICY_KEY, /* Entity name to use */ OPENISNS_TAG_POLICY_ENTITY, /* Functions the client is permitted to invoke */ OPENISNS_TAG_POLICY_FUNCTIONS, /* Object types the client is permitted to see. */ OPENISNS_TAG_POLICY_OBJECT_TYPE, /* iSCSI node name the client is permitted to register. * This attribute may occur multiple times. * If absent, it defaults to POLICY_SOURCE_NAME */ OPENISNS_TAG_POLICY_NODE_NAME, /* Node type bitmap the client is permitted to register */ OPENISNS_TAG_POLICY_NODE_TYPE, /* Default discovery domain the client will be * placed in. * Not used yet. */ OPENISNS_TAG_POLICY_DEFAULT_DD, OPENISNS_TAG_POLICY_VISIBLE_DD, }; extern const struct isns_object_template isns_policy_template; #endif /* ISNS_VENDOR_H */ open-iscsi-2.0.873/utils/sysdeps/000077500000000000000000000000001175631155400166065ustar00rootroot00000000000000open-iscsi-2.0.873/utils/sysdeps/Makefile000066400000000000000000000004101175631155400202410ustar00rootroot00000000000000# This Makefile will work only with GNU make. CFLAGS += $(OPTFLAGS) $(WARNFLAGS) -O2 -fno-inline -Wall -Wstrict-prototypes -g SYSDEPS_OBJS=sysdeps.o all: $(SYSDEPS_OBJS) clean: rm -f *.o .depend depend: gcc $(CFLAGS) -M `ls *.c` > .depend -include .depend open-iscsi-2.0.873/utils/sysdeps/sysdeps.c000066400000000000000000000031201175631155400204400ustar00rootroot00000000000000/* * Copyright (C) 2003 Greg Kroah-Hartman * Copyright (C) 2005-2006 Kay Sievers * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #ifdef __GLIBC__ size_t strlcpy(char *dst, const char *src, size_t size) { size_t bytes = 0; char *q = dst; const char *p = src; char ch; while ((ch = *p++)) { if (bytes+1 < size) *q++ = ch; bytes++; } /* If size == 0 there is no space for a final null... */ if (size) *q = '\0'; return bytes; } size_t strlcat(char *dst, const char *src, size_t size) { size_t bytes = 0; char *q = dst; const char *p = src; char ch; while (bytes < size && *q) { q++; bytes++; } if (bytes == size) return (bytes + strlen(src)); while ((ch = *p++)) { if (bytes+1 < size) *q++ = ch; bytes++; } *q = '\0'; return bytes; } #endif /* __GLIBC__ */