*BSD News Article 24938


Return to BSD News archive

Newsgroups: comp.os.386bsd.apps
Path: sserve!newshost.anu.edu.au!munnari.oz.au!bunyip.cc.uq.oz.au!harbinger.cc.monash.edu.au!yeshua.marcam.com!usc!elroy.jpl.nasa.gov!swrinde!menudo.uh.edu!nuchat!limbic.ssdl.com!gil
From: gil@limbic.ssdl.com (Gil Kloepfer Jr.)
Subject: [FreeBSD] expect-send dialer for slattach
Message-ID: <1993Dec13.032545.5656@nuchat.sccsi.com>
Sender: usenet@nuchat.sccsi.com (Netnews Administrator)
Nntp-Posting-Host: limbic.ssdl.com
Organization: Southwest Systems Development Labs, Sugar Land, TX
Date: Mon, 13 Dec 1993 03:25:45 GMT
Lines: 1272

I'm not sure if this is an appropriate place to post this, whether
the program has been done before by someone else, or even if will work
for the general public.  I found it to be useful, so I'm posting it
here with the thought it may be for someone else.  It's short.

Basically, it's a utility program to do expect-send style dialing
in conjunction with the new slattach in FreeBSD.  I use it to establish
and maintain my SLIP connection.  There's some examples of how I use
it in the shar.

Enjoy!

-- Cut Here -- -- Cut Here -- -- Cut Here -- -- Cut Here -- -- Cut Here --
# This is a shell archive.  Save it in a file, remove anything before
# this line, and then unpack it by entering "sh file".  Note, it may
# create directories; files and directories will be owned by you and
# have default permissions.
#
# This archive contains:
#
#	README
#	COPYING
#	Makefile
#	expsend.c
#	expsend.1
#	example
#	example/slip.expsend
#	example/slip.slconfig
#	example/slip.slexit
#	example/slipdial.sh
#
echo x - README
sed 's/^X//' >README << 'END-of-README'
XThis is expsend - a simple program to handle expect-send sequences when
Xtalking to a modem.
X
XThere are better programs which do this I hear, but I wanted something
Xquick and dirty to use with the FreeBSD "slattach" command which allows
Xdialing and redialing SLIP lines.  This program enabled me to bring my
XSLIP connection back up when the line dropped, and to initiate the
Xcall.
X
XI include an example of how I use this with the FreeBSD slattach program.
XYou can use it however it suits you as long as it complies with the
XGNU General Public License as stated in the program source.
X
XIf you make improvements to this, please send a context diff along
Xto me!  If you have recommendations for something better, send it
Xalong too.  Flames to /dev/null, praise to gil@limbic.ssdl.com.  :)
X
XGil Kloepfer, Jr.
Xgil@limbic.ssdl.com
X12/11/1993
END-of-README
echo x - COPYING
sed 's/^X//' >COPYING << 'END-of-COPYING'
X		    GNU GENERAL PUBLIC LICENSE
X		       Version 2, June 1991
X
X Copyright (C) 1989, 1991 Free Software Foundation, Inc.
X                          675 Mass Ave, Cambridge, MA 02139, USA
X Everyone is permitted to copy and distribute verbatim copies
X of this license document, but changing it is not allowed.
X
X			    Preamble
X
X  The licenses for most software are designed to take away your
Xfreedom to share and change it.  By contrast, the GNU General Public
XLicense is intended to guarantee your freedom to share and change free
Xsoftware--to make sure the software is free for all its users.  This
XGeneral Public License applies to most of the Free Software
XFoundation's software and to any other program whose authors commit to
Xusing it.  (Some other Free Software Foundation software is covered by
Xthe GNU Library General Public License instead.)  You can apply it to
Xyour programs, too.
X
X  When we speak of free software, we are referring to freedom, not
Xprice.  Our General Public Licenses are designed to make sure that you
Xhave the freedom to distribute copies of free software (and charge for
Xthis service if you wish), that you receive source code or can get it
Xif you want it, that you can change the software or use pieces of it
Xin new free programs; and that you know you can do these things.
X
X  To protect your rights, we need to make restrictions that forbid
Xanyone to deny you these rights or to ask you to surrender the rights.
XThese restrictions translate to certain responsibilities for you if you
Xdistribute copies of the software, or if you modify it.
X
X  For example, if you distribute copies of such a program, whether
Xgratis or for a fee, you must give the recipients all the rights that
Xyou have.  You must make sure that they, too, receive or can get the
Xsource code.  And you must show them these terms so they know their
Xrights.
X
X  We protect your rights with two steps: (1) copyright the software, and
X(2) offer you this license which gives you legal permission to copy,
Xdistribute and/or modify the software.
X
X  Also, for each author's protection and ours, we want to make certain
Xthat everyone understands that there is no warranty for this free
Xsoftware.  If the software is modified by someone else and passed on, we
Xwant its recipients to know that what they have is not the original, so
Xthat any problems introduced by others will not reflect on the original
Xauthors' reputations.
X
X  Finally, any free program is threatened constantly by software
Xpatents.  We wish to avoid the danger that redistributors of a free
Xprogram will individually obtain patent licenses, in effect making the
Xprogram proprietary.  To prevent this, we have made it clear that any
Xpatent must be licensed for everyone's free use or not licensed at all.
X
X  The precise terms and conditions for copying, distribution and
Xmodification follow.
X
X		    GNU GENERAL PUBLIC LICENSE
X   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
X
X  0. This License applies to any program or other work which contains
Xa notice placed by the copyright holder saying it may be distributed
Xunder the terms of this General Public License.  The "Program", below,
Xrefers to any such program or work, and a "work based on the Program"
Xmeans either the Program or any derivative work under copyright law:
Xthat is to say, a work containing the Program or a portion of it,
Xeither verbatim or with modifications and/or translated into another
Xlanguage.  (Hereinafter, translation is included without limitation in
Xthe term "modification".)  Each licensee is addressed as "you".
X
XActivities other than copying, distribution and modification are not
Xcovered by this License; they are outside its scope.  The act of
Xrunning the Program is not restricted, and the output from the Program
Xis covered only if its contents constitute a work based on the
XProgram (independent of having been made by running the Program).
XWhether that is true depends on what the Program does.
X
X  1. You may copy and distribute verbatim copies of the Program's
Xsource code as you receive it, in any medium, provided that you
Xconspicuously and appropriately publish on each copy an appropriate
Xcopyright notice and disclaimer of warranty; keep intact all the
Xnotices that refer to this License and to the absence of any warranty;
Xand give any other recipients of the Program a copy of this License
Xalong with the Program.
X
XYou may charge a fee for the physical act of transferring a copy, and
Xyou may at your option offer warranty protection in exchange for a fee.
X
X  2. You may modify your copy or copies of the Program or any portion
Xof it, thus forming a work based on the Program, and copy and
Xdistribute such modifications or work under the terms of Section 1
Xabove, provided that you also meet all of these conditions:
X
X    a) You must cause the modified files to carry prominent notices
X    stating that you changed the files and the date of any change.
X
X    b) You must cause any work that you distribute or publish, that in
X    whole or in part contains or is derived from the Program or any
X    part thereof, to be licensed as a whole at no charge to all third
X    parties under the terms of this License.
X
X    c) If the modified program normally reads commands interactively
X    when run, you must cause it, when started running for such
X    interactive use in the most ordinary way, to print or display an
X    announcement including an appropriate copyright notice and a
X    notice that there is no warranty (or else, saying that you provide
X    a warranty) and that users may redistribute the program under
X    these conditions, and telling the user how to view a copy of this
X    License.  (Exception: if the Program itself is interactive but
X    does not normally print such an announcement, your work based on
X    the Program is not required to print an announcement.)
X
XThese requirements apply to the modified work as a whole.  If
Xidentifiable sections of that work are not derived from the Program,
Xand can be reasonably considered independent and separate works in
Xthemselves, then this License, and its terms, do not apply to those
Xsections when you distribute them as separate works.  But when you
Xdistribute the same sections as part of a whole which is a work based
Xon the Program, the distribution of the whole must be on the terms of
Xthis License, whose permissions for other licensees extend to the
Xentire whole, and thus to each and every part regardless of who wrote it.
X
XThus, it is not the intent of this section to claim rights or contest
Xyour rights to work written entirely by you; rather, the intent is to
Xexercise the right to control the distribution of derivative or
Xcollective works based on the Program.
X
XIn addition, mere aggregation of another work not based on the Program
Xwith the Program (or with a work based on the Program) on a volume of
Xa storage or distribution medium does not bring the other work under
Xthe scope of this License.
X
X  3. You may copy and distribute the Program (or a work based on it,
Xunder Section 2) in object code or executable form under the terms of
XSections 1 and 2 above provided that you also do one of the following:
X
X    a) Accompany it with the complete corresponding machine-readable
X    source code, which must be distributed under the terms of Sections
X    1 and 2 above on a medium customarily used for software interchange; or,
X
X    b) Accompany it with a written offer, valid for at least three
X    years, to give any third party, for a charge no more than your
X    cost of physically performing source distribution, a complete
X    machine-readable copy of the corresponding source code, to be
X    distributed under the terms of Sections 1 and 2 above on a medium
X    customarily used for software interchange; or,
X
X    c) Accompany it with the information you received as to the offer
X    to distribute corresponding source code.  (This alternative is
X    allowed only for noncommercial distribution and only if you
X    received the program in object code or executable form with such
X    an offer, in accord with Subsection b above.)
X
XThe source code for a work means the preferred form of the work for
Xmaking modifications to it.  For an executable work, complete source
Xcode means all the source code for all modules it contains, plus any
Xassociated interface definition files, plus the scripts used to
Xcontrol compilation and installation of the executable.  However, as a
Xspecial exception, the source code distributed need not include
Xanything that is normally distributed (in either source or binary
Xform) with the major components (compiler, kernel, and so on) of the
Xoperating system on which the executable runs, unless that component
Xitself accompanies the executable.
X
XIf distribution of executable or object code is made by offering
Xaccess to copy from a designated place, then offering equivalent
Xaccess to copy the source code from the same place counts as
Xdistribution of the source code, even though third parties are not
Xcompelled to copy the source along with the object code.
X
X  4. You may not copy, modify, sublicense, or distribute the Program
Xexcept as expressly provided under this License.  Any attempt
Xotherwise to copy, modify, sublicense or distribute the Program is
Xvoid, and will automatically terminate your rights under this License.
XHowever, parties who have received copies, or rights, from you under
Xthis License will not have their licenses terminated so long as such
Xparties remain in full compliance.
X
X  5. You are not required to accept this License, since you have not
Xsigned it.  However, nothing else grants you permission to modify or
Xdistribute the Program or its derivative works.  These actions are
Xprohibited by law if you do not accept this License.  Therefore, by
Xmodifying or distributing the Program (or any work based on the
XProgram), you indicate your acceptance of this License to do so, and
Xall its terms and conditions for copying, distributing or modifying
Xthe Program or works based on it.
X
X  6. Each time you redistribute the Program (or any work based on the
XProgram), the recipient automatically receives a license from the
Xoriginal licensor to copy, distribute or modify the Program subject to
Xthese terms and conditions.  You may not impose any further
Xrestrictions on the recipients' exercise of the rights granted herein.
XYou are not responsible for enforcing compliance by third parties to
Xthis License.
X
X  7. If, as a consequence of a court judgment or allegation of patent
Xinfringement or for any other reason (not limited to patent issues),
Xconditions are imposed on you (whether by court order, agreement or
Xotherwise) that contradict the conditions of this License, they do not
Xexcuse you from the conditions of this License.  If you cannot
Xdistribute so as to satisfy simultaneously your obligations under this
XLicense and any other pertinent obligations, then as a consequence you
Xmay not distribute the Program at all.  For example, if a patent
Xlicense would not permit royalty-free redistribution of the Program by
Xall those who receive copies directly or indirectly through you, then
Xthe only way you could satisfy both it and this License would be to
Xrefrain entirely from distribution of the Program.
X
XIf any portion of this section is held invalid or unenforceable under
Xany particular circumstance, the balance of the section is intended to
Xapply and the section as a whole is intended to apply in other
Xcircumstances.
X
XIt is not the purpose of this section to induce you to infringe any
Xpatents or other property right claims or to contest validity of any
Xsuch claims; this section has the sole purpose of protecting the
Xintegrity of the free software distribution system, which is
Ximplemented by public license practices.  Many people have made
Xgenerous contributions to the wide range of software distributed
Xthrough that system in reliance on consistent application of that
Xsystem; it is up to the author/donor to decide if he or she is willing
Xto distribute software through any other system and a licensee cannot
Ximpose that choice.
X
XThis section is intended to make thoroughly clear what is believed to
Xbe a consequence of the rest of this License.
X
X  8. If the distribution and/or use of the Program is restricted in
Xcertain countries either by patents or by copyrighted interfaces, the
Xoriginal copyright holder who places the Program under this License
Xmay add an explicit geographical distribution limitation excluding
Xthose countries, so that distribution is permitted only in or among
Xcountries not thus excluded.  In such case, this License incorporates
Xthe limitation as if written in the body of this License.
X
X  9. The Free Software Foundation may publish revised and/or new versions
Xof the General Public License from time to time.  Such new versions will
Xbe similar in spirit to the present version, but may differ in detail to
Xaddress new problems or concerns.
X
XEach version is given a distinguishing version number.  If the Program
Xspecifies a version number of this License which applies to it and "any
Xlater version", you have the option of following the terms and conditions
Xeither of that version or of any later version published by the Free
XSoftware Foundation.  If the Program does not specify a version number of
Xthis License, you may choose any version ever published by the Free Software
XFoundation.
X
X  10. If you wish to incorporate parts of the Program into other free
Xprograms whose distribution conditions are different, write to the author
Xto ask for permission.  For software which is copyrighted by the Free
XSoftware Foundation, write to the Free Software Foundation; we sometimes
Xmake exceptions for this.  Our decision will be guided by the two goals
Xof preserving the free status of all derivatives of our free software and
Xof promoting the sharing and reuse of software generally.
X
X			    NO WARRANTY
X
X  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
XFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
XOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
XPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
XOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
XMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
XTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
XPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
XREPAIR OR CORRECTION.
X
X  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
XWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
XREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
XINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
XOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
XTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
XYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
XPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
XPOSSIBILITY OF SUCH DAMAGES.
X
X		     END OF TERMS AND CONDITIONS
X
X	    How to Apply These Terms to Your New Programs
X
X  If you develop a new program, and you want it to be of the greatest
Xpossible use to the public, the best way to achieve this is to make it
Xfree software which everyone can redistribute and change under these terms.
X
X  To do so, attach the following notices to the program.  It is safest
Xto attach them to the start of each source file to most effectively
Xconvey the exclusion of warranty; and each file should have at least
Xthe "copyright" line and a pointer to where the full notice is found.
X
X    <one line to give the program's name and a brief idea of what it does.>
X    Copyright (C) 19yy  <name of author>
X
X    This program is free software; you can redistribute it and/or modify
X    it under the terms of the GNU General Public License as published by
X    the Free Software Foundation; either version 2 of the License, or
X    (at your option) any later version.
X
X    This program is distributed in the hope that it will be useful,
X    but WITHOUT ANY WARRANTY; without even the implied warranty of
X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
X    GNU General Public License for more details.
X
X    You should have received a copy of the GNU General Public License
X    along with this program; if not, write to the Free Software
X    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
XAlso add information on how to contact you by electronic and paper mail.
X
XIf the program is interactive, make it output a short notice like this
Xwhen it starts in an interactive mode:
X
X    Gnomovision version 69, Copyright (C) 19yy name of author
X    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
X    This is free software, and you are welcome to redistribute it
X    under certain conditions; type `show c' for details.
X
XThe hypothetical commands `show w' and `show c' should show the appropriate
Xparts of the General Public License.  Of course, the commands you use may
Xbe called something other than `show w' and `show c'; they could even be
Xmouse-clicks or menu items--whatever suits your program.
X
XYou should also get your employer (if you work as a programmer) or your
Xschool, if any, to sign a "copyright disclaimer" for the program, if
Xnecessary.  Here is a sample; alter the names:
X
X  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
X  `Gnomovision' (which makes passes at compilers) written by James Hacker.
X
X  <signature of Ty Coon>, 1 April 1989
X  Ty Coon, President of Vice
X
XThis General Public License does not permit incorporating your program into
Xproprietary programs.  If your program is a subroutine library, you may
Xconsider it more useful to permit linking proprietary applications with the
Xlibrary.  If this is what you want to do, use the GNU Library General
XPublic License instead of this License.
END-of-COPYING
echo x - Makefile
sed 's/^X//' >Makefile << 'END-of-Makefile'
X#
X# Very simple Makefile for expsend.c
X#
X
XCC=cc
XCFLAGS=-O
XLDFLAGS=-s
X
XBINDIR=/usr/local/bin
XMANDIR=/usr/local/man/man1
X
X# Set -DOPEN_BLOCKS for the IBM RT or whenever you use a TTY where the
X# open will block waiting for a carrier
XDEFS=
X#DEFS=-DOPEN_BLOCKS
X
Xexpsend:	expsend.c
X		$(CC) $(DEFS) $(CFLAGS) -o expsend expsend.c $(LDFLAGS)
X
X
Xshar:
X		shar README COPYING Makefile expsend.c expsend.1 example example/* > expsend.shar
X
Xclean:
X		rm -f core core.* *.o
X
Xspotless:	clean
X		rm -f expsend
X
Xinstall:	expsend
X		cp expsend $(BINDIR)
X		cp expsend.1 $(MANDIR)
X		chmod 755 $(BINDIR)/expsend
X		chmod 644 $(MANDIR)/expsend.1
X		chown bin $(BINDIR)/expsend $(MANDIR)/expsend.1
X		chgrp bin $(BINDIR)/expsend $(MANDIR)/expsend.1
END-of-Makefile
echo x - expsend.c
sed 's/^X//' >expsend.c << 'END-of-expsend.c'
X/*  expsend.c -- a simple, standalone expect-send program for automating
X                  the logon sequence to another system
X    Copyright (C) 1993 Gilbert C. Kloepfer, Jr.   All Rights Reserved
X
X    This program is free software; you can redistribute it and/or modify
X    it under the terms of the GNU General Public License as published by
X    the Free Software Foundation; either version 2 of the License, or
X    (at your option) any later version.
X
X    This program is distributed in the hope that it will be useful,
X    but WITHOUT ANY WARRANTY; without even the implied warranty of
X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
X    GNU General Public License for more details.
X
X    You should have received a copy of the GNU General Public License
X    along with this program; see the file COPYING.  If not, write to
X    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
X
X    You may contact the author by:
X       E-mail:  gil@limbic.ssdl.com
X      US-mail:  Gilbert C. Kloepfer, Jr.
X                2427 Manorwood Dr.
X                Sugar Land, TX  77478
X                USA
X       
X*************************************************************************/
X
X/*
X * Expsend provides a means to automate the login and connect procedure
X * to a remote system.  
X *
X * Special characters are escaped with backslash (\) and the following
X * are special sequences recognized by the program:
X *
X *		\r	- carriage return (ASCII 13)
X *		\n	- carraige-return/linefeed (ASCII 13/10)
X *		\\	- backslash
X *		\d	- delay (about 2 seconds)
X *		\p	- delay (something a second or less)
X *		\b	- space
X *		\X	- nothing (for "expect nothing")
X *		\c	- don't send carriage return at end of string
X *		\F	- Remainder of string contains one or more fail strings
X *
X *
X * The input data consists of expect-strings followed by send-strings.  The
X * send-string is sent on successful completion of expect-string.  A special
X * escape code \F may be included as part of any expect-string to provide
X * one or more fail-strings.
X *
X * The input data is scanned character-by-character until a match is
X * discovered with the expect-string or fail-string.  If a fail-string is
X * matched, processing ceases and the program exits according to the
X * failure mode processing.  If the expect-string is matched, the send-string
X * is then sent with all special escapes translated followed by a carriage
X * return (unless \c is present).
X *
X * Upon successful completion of the expect-send dialogue, the program will
X * exit with a status of 0.
X */
X
X#ifndef lint
Xstatic char cheapversion[] = "@(#) expsend.c 1.0 12/11/1993\n";
Xstatic char copyright[] = 
X"@(#) Copyright (C) 1993 Gilbert C. Kloepfer, Jr.   All Rights Reserved\n";
X#endif /* lint */
X
X#include <unistd.h>
X#include <stdio.h>
X#include <stdlib.h>
X#include <string.h>
X#include <syslog.h>
X#include <sys/termios.h>
X#include <sys/ioctl.h>
X#include <signal.h>
X#include <fcntl.h>
X
X/*
X * The following #defines should not need to be modified, but can be
X * for those who understand the inner workings of the code
X *
X * IOSIZE         = The number of characters sucked-in per read(2) call.
X *                  I don't know if it works with any bigger number  XXX
X * PATHSIZE       = The maximum size a pathname can be
X * NUM_EXPECTS    = The maximum number of "expect" (expect + n * fail)
X *                  sequences the program will allow
X * DEFAULT_TMOUT  = The default timeout period for a completely failed or
X *                  hung dial sequence (seconds)
X */
X
X#define	IOSIZE		1
X#define	PATHSIZE	128
X#define	NUM_EXPECTS	10
X#define	DEFAULT_TMOUT	90
X
X/*
X * Decide whether to use nonblocking open or not (IBM RT or when
X * needed)
X */
X#ifdef OPEN_BLOCKS
X# define TTY_OPEN_MODE (O_RDWR | O_NONBLOCK)
X#else
X# define TTY_OPEN_MODE (O_RDWR)
X#endif  /* OPEN_BLOCKS */
X
Xextern char *optarg;
Xextern int optind;
X
Xchar *progname;			/* Points to name of program */
Xchar esfile[PATHSIZE];		/* File to get expect-send info from */
Xchar usetty[PATHSIZE];		/* tty to do I/O on (if not stdin/out) */
Xtime_t failtime;		/* Seconds to wait to exit after failure */
Xint gagchars;			/* # irrelivant characters before gagging */
Xint use_syslog;			/* Use BSD syslog for recording messages */
Xint debug_on;			/* write debug messages to stderr */
Xint do_sendhup;			/* Send hangup on failure */
Xu_int expect_tmout;		/* Timeout for expect sequence to happen */
X
XFILE *esfp;			/* Expect-send file I/O pointer */
Xint ttyfd;			/* tty to do I/O with */
Xint tt_setup_done = 0;		/* Set to 1 if tty setup has been done */
Xstruct termios tiottysv;	/* Saved tty params (before changed) */
Xstruct termios tiostty;		/* Current tty params */
X
Xmain(argc, argv)
Xint argc;
Xchar *argv[];
X{
X	int		arg;
X	char		inputb[128];
X	int		es_expect(), es_send();
X	void		expect_timer();
X	int		statusind = 0;
X
X
X	/*
X	 * Get program name for error messages
X	 */
X
X	if ((progname=rindex(argv[0], '/')) != NULL)
X		progname++;
X	else
X		progname = argv[0];
X
X	/*
X	 * Initial flag/arg settings
X	 */
X
X	esfile[0] = '\0';
X	(void)strcpy(usetty, ttyname(0));
X	failtime = 0;
X	gagchars = 0;
X	use_syslog = 0;
X	debug_on = 0;
X	do_sendhup = 0;
X	expect_tmout = DEFAULT_TMOUT;
X
X	/*
X	 * Parse args
X	 */
X
X	while ((arg=getopt(argc, argv, "dt:F:G:T:SH")) != EOF) {
X		switch(arg) {
X		case 'd':  /* enable debugging */
X			debug_on = 1;
X			break;
X
X		case 't':  /* tty to do I/O with */
X			(void)strcpy(usetty, optarg);
X			break;
X
X		case 'G':  /* How many characters before gagging */
X			gagchars = atoi(optarg);
X			break;
X
X		case 'H':  /* Send hangup (stty 0) on failure */
X			do_sendhup = 1;
X			break;
X
X		case 'F':  /* Time to wait after failure */
X			failtime = (time_t)atol(optarg);
X			break;
X
X		case 'S':  /* Use syslog to log errors/notices */
X			use_syslog = 1;
X			break;
X
X		case 'T':  /* Modify expect timeout */
X			expect_tmout = (u_int)atoi(optarg);
X			break;
X
X		case '?':
X			usage();
X			exit(1);
X		}
X	}
X
X	if (optind >= argc) {
X		usage();
X		exit(1);
X	}
X	(void)strcpy(esfile, argv[optind++]);
X
X	/*
X	 * Open any files and validate args
X	 */
X
X	if (failtime < 0)
X		failtime = 0;
X
X	if (gagchars < 0)
X		gagchars = 0;
X 
X	if (use_syslog)
X		openlog(progname, 0, LOG_USER);
X
X	esfp = fopen(esfile, "r");
X	if (esfp == NULL) {
X		log_perror(esfile);
X		fail(2);
X	}
X
X	if (usetty[0] == '\0') {
X		log_msg("tty has not been specified or is not a tty");
X		fail(2);
X	}
X
X	ttyfd = open(usetty, TTY_OPEN_MODE);
X	if (ttyfd < 0) {
X		log_perror(usetty);
X		fail(2);
X	}
X
X#ifdef OPEN_BLOCKS
X	if (fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NONBLOCK) < 0) {
X		log_perror(usetty);
X		fail(2);
X	}
X#endif  /* OPEN_BLOCKS */
X
X	if (debug_on)
X		(void)fprintf(stderr,
X		  "%s: esfile=%s   tty=%s   failtime=%ld  gag=%d\n",
X			progname, esfile, usetty, failtime, gagchars);
X
X	/*
X	 * Establish terminal parameters which will be needed for
X	 * doing character-by-character I/O 
X	 */
X
X	if (ioctl(ttyfd, TIOCGETA, &tiottysv) < 0) {
X		log_perror("TIOCGETA");
X		fail(2);
X	}
X	bcopy(&tiottysv, &tiostty, sizeof(struct termios));
X
X	tiostty.c_iflag |= (IGNBRK | ISTRIP);
X	tiostty.c_iflag &= ~(IXON | IXOFF | IXANY);
X	tiostty.c_oflag = 0;
X	tiostty.c_cflag |= (CS8 | CLOCAL);
X	tiostty.c_lflag = NOFLSH;
X	tiostty.c_cc[VMIN] = 1;
X	tiostty.c_cc[VTIME] = 1;
X
X	if (ioctl(ttyfd, TIOCSETAF, &tiostty) < 0) {
X		log_perror("TIOCSETAF");
X		fail(2);
X	}
X
X	tt_setup_done = 1;
X
X	/*
X	 * Main loop - Perform expect-send tasks until all strings
X	 * are exhausted, then break from the loop so that the
X	 * remote line characteristics can be returned to normal
X	 */
X
X	while (1) {
X		if (fgets(inputb, 128, esfp) == NULL)
X			break;
X
X		if (expect_tmout != 0) {
X			(void)signal(SIGALRM, expect_timer);
X			alarm(expect_tmout);
X		}
X
X		if (es_expect(inputb) < 0)
X			fail(2);
X
X		if (expect_tmout != 0) {
X			(void)signal(SIGALRM, SIG_IGN);
X			alarm(0);
X		}
X
X		if (fgets(inputb, 128, esfp) == NULL)
X			break;
X
X		if (es_send(inputb) < 0)
X			fail(2);
X	}
X
X	/*
X	 * Set line characteristics back to normal and success
X	 * indication
X	 */
X
X	(void)ioctl(ttyfd, TIOCSETAW, &tiottysv);
X	close(ttyfd);
X	fclose(esfp);
X
X	if (use_syslog)
X		syslog(LOG_INFO, "caller script succeeded on %s", usetty);
X
X	exit(0);
X}
X
X
Xusage()
X{
X	(void)fprintf(stderr,"\
Xusage: %s [-dSH] [-T expect-tmout] [-F failwait] [-G gagchars]\n\
X          [-t ttyname] script\n",
X		progname);
X}
X
X
Xlog_perror(msg)
Xchar *msg;
X{
X	if (use_syslog)
X		syslog(LOG_ERR, "%s: %m", msg);
X	else
X		perror(msg);
X}
X
X
Xlog_msg(msg)
Xchar *msg;
X{
X	if (use_syslog)
X		syslog(LOG_NOTICE, msg);
X	else
X		(void)fprintf(stderr, "%s: %s\n", progname, msg);
X}
X
X
Xfail(estatus)
Xint estatus;
X{
X	if (tt_setup_done) {
X		if (do_sendhup) {
X			tiostty.c_ispeed = B0;
X			tiostty.c_ospeed = B0;
X			(void)ioctl(ttyfd, TIOCSETAF, &tiostty);
X			sleep(1);
X		}
X
X		(void)ioctl(ttyfd, TIOCSETAW, &tiottysv);
X	}
X
X	if (failtime > 0)
X		sleep(failtime);
X
X	if (use_syslog)
X		syslog(LOG_INFO, "caller script failed on %s", usetty);
X
X	exit(estatus);
X}
X
X
Xint es_expect(chats)
Xchar *chats;
X{
X	char		iobuffer[IOSIZE], transbuf[255], *isp, *osp;
X	int		iobufcnt, timeoutcnt, totalchr, n_seq, c_seq, bcc;
X	char		*seqs[NUM_EXPECTS], *matchp[NUM_EXPECTS],
X			*compp;
X	if (debug_on)
X		(void)fprintf(stderr, "Expect: [%s]\n", chats);
X
X	n_seq = 0;
X
X	/*
X	 * Convert the escape codes in the chat string
X	 */
X
X	isp = chats;
X	osp = transbuf;
X
X	*osp = '\0';
X	while (*isp) {
X		if (*isp == '\n') {
X			isp++;
X			continue;
X		}
X		if (*isp == '\\') {
X			isp++;
X			if (*isp == '\0')  continue;
X			switch (*isp) {
X			case 'r':  /* Carriage return */
X				*osp++ = '\015';
X				break;
X
X			case 'n':  /* Newline */
X				*osp++ = '\015';
X				*osp++ = '\012';
X				break;
X
X			case '\\':  /* Backslash */
X				*osp++ = '\\';
X				break;
X
X			case 'b':  /* Blank */
X				*osp++ = ' ';
X				break;
X
X			case 'X':  /* Nothing */
X				break;
X
X			case 'F':  /* End string, more (fail) sequences */
X				*osp = '\0';
X				seqs[n_seq] = strdup(transbuf);
X				matchp[n_seq] = seqs[n_seq];
X				if (++n_seq >= NUM_EXPECTS) {
X					log_msg("too many multiple expects");
X					fail(2);
X				}
X				osp = transbuf;
X				break;
X
X			default:  /* Ignore unknown/inappropriate ones */
X				break;
X			}
X		} else
X			*osp++ = *isp;
X
X		*osp = '\0';
X		++isp;
X	}
X
X	/* Finish the buffer being built */
X
X	seqs[n_seq] = strdup(transbuf);
X	matchp[n_seq] = seqs[n_seq];
X	if (++n_seq >= NUM_EXPECTS) {
X		log_msg("too many multiple expects");
X		fail(2);
X	}
X
X	/*
X	 * Get input characters from the remote side and match against
X	 * the match string
X	 */
X
X	timeoutcnt = 0;
X	totalchr = 0;
X
X	while (1) {
X		for (c_seq=0; c_seq < n_seq; c_seq++)
X			if (*matchp[c_seq] == '\0')
X				goto gotit;
X
X		iobufcnt = read(ttyfd, iobuffer, IOSIZE);
X		if (iobufcnt < 0) {
X			log_msg("expect input - read failure");
X			return(-1);
X		}
X
X		if (iobufcnt == 0) {
X			if (debug_on)
X				(void)fprintf(stderr, "<timeout>\n");
X			timeoutcnt++;
X			if (timeoutcnt > 30) {
X				log_msg("expect input - POSIX input timeout");
X				return(-1);
X			} else
X				continue;
X		}
X
X		totalchr += iobufcnt;
X		if (gagchars != 0 && totalchr > gagchars) {
X			log_msg("accept - too many misc characters accepted");
X			return(-1);
X		}
X
X		for (c_seq=0; c_seq < n_seq; c_seq++) {
X			compp = iobuffer;
X			bcc = iobufcnt;
X			while (bcc) {
X				if (debug_on && c_seq == 0)
X					(void)write(2, compp, 1);
X				if (*matchp[c_seq] == *compp) {
X					matchp[c_seq]++;
X					if (*matchp[c_seq] == '\0')
X						goto gotit;
X				} else {
X					matchp[c_seq] = seqs[c_seq];
X					if (*matchp[c_seq] == *compp) {
X						matchp[c_seq]++;
X						if (*matchp[c_seq] == '\0')
X							goto gotit;
X					}
X				}
X				--bcc;
X				++compp;
X			}
X		}
X	}
X
X	/*NOTREACHED*/
X
Xgotit:
X	while (--n_seq >= 0)
X		free(seqs[n_seq]);
X
X	if (c_seq != 0) {
X		log_msg("got expect fail - aborting");
X		return(-1);
X	} else {
X		if (debug_on)
X			(void)fprintf(stderr, "\ngot match\n");
X		return(0);
X	}
X
X	/*NOTREACHED*/
X}
X
X
Xint es_send(chats)
Xchar *chats;
X{
X	register char		*chatp;
X	char			buf[5];
X	int			nosendcr;
X
X	if (debug_on)
X		fprintf(stderr, "Send: [%s]\n", chats);
X
X	chatp = chats;
X	nosendcr = 0;
X
X	while (*chatp) {
X		if (*chatp == '\n') {
X			chatp++;
X			continue;
X		}
X		if (*chatp == '\\') {
X			chatp++;
X			if (*chatp == '\0')  continue;
X			switch (*chatp) {
X			case 'r':  /* Carriage return */
X				buf[0] = '\015';
X				if (write(ttyfd, buf, 1) != 1)  goto badwr;
X				break;
X
X			case 'n':  /* Newline */
X				buf[0] = '\015';
X				buf[1] = '\012';
X				if (write(ttyfd, buf, 2) != 2)  goto badwr;
X				break;
X
X			case '\\':  /* Backslash */
X				buf[0] = '\\';
X				if (write(ttyfd, buf, 1) != 1)  goto badwr;
X				break;
X
X			case 'd':   /* Delay */
X				sleep(2);
X				break;
X
X			case 'p':   /* Pause */
X				sleep(1);
X				break;
X
X			case 'b':  /* Blank */
X				buf[0] = ' ';
X				if (write(ttyfd, buf, 1) != 1)  goto badwr;
X				break;
X
X			case 'c':  /* Don't send return after string */
X				nosendcr = 1;
X				break;
X
X			default:  /* Ignore unknown/inappropriate ones */
X				break;
X			}
X		} else {
X			if (write(ttyfd, chatp, 1) != 1)  goto badwr;
X		}
X		chatp++;
X	}
X
X	if (!nosendcr) {
X		buf[0] = '\015';
X		if (write(ttyfd, buf, 1) != 1)  goto badwr;
X	}
X
X	return(0);
X
Xbadwr:
X	log_msg("send - write failed");
X	return(1);
X}
X
X
Xvoid expect_timer()
X{
X	log_msg("input - expect timer expired - sequence failed");
X
X	fail(2);
X}
END-of-expsend.c
echo x - expsend.1
sed 's/^X//' >expsend.1 << 'END-of-expsend.1'
X.\"    Copyright (C) 1993 Gilbert C. Kloepfer, Jr.   All Rights Reserved
X.\"
X.\"    This manual page is part of the expsend utility program.
X.\"
X.\"    This program is free software; you can redistribute it and/or modify
X.\"    it under the terms of the GNU General Public License as published by
X.\"    the Free Software Foundation; either version 2 of the License, or
X.\"    (at your option) any later version.
X.\"
X.\"    This program is distributed in the hope that it will be useful,
X.\"    but WITHOUT ANY WARRANTY; without even the implied warranty of
X.\"    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
X.\"    GNU General Public License for more details.
X.\"
X.\"    You should have received a copy of the GNU General Public License
X.\"    along with this program; see the file COPYING.  If not, write to
X.\"    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
X.\"
X.\"    You may contact the author by:
X.\"       E-mail:  gil@limbic.ssdl.com
X.\"      US-mail:  Gilbert C. Kloepfer, Jr.
X.\"                2427 Manorwood Dr.
X.\"                Sugar Land, TX  77478
X.\"                USA
X.TH expsend 1L "December 11, 1993" "Rev 1.0" "Local Communication Utilities"
X.SH NAME
X\fBexpsend\fR - a simple, standalone expect-send program
Xfor automating the logon sequence to another system
X.SH SYNOPSIS
X\fBexpsend\fR [\fB-dSH\fR] [\fB-T\fR expect-tmout] [\fB-F\fR failwait]
X[\fB-G\fR gagchars] [\fB-t\fR ttyname] script-file
X.SH DESCRIPTION
X\fBExpsend\fR is a standalone program used to implement
Xa simple expect-send sequence useful for automating the
Xdial-up and connection to another system via a modem
Xor similar communications medium.  The language implemented
Xis similar in function to that used in UUCP (qv.).  The
Xterminal parameters are set so that using \fBexpsend\fR
Xwith a modem is natural.
X.PP
XUnlike UUCP, or its offshoots, \fBexpsend\fR reads its
Xsequence of expect-send events from a \fBscript\fR file,
Xwith the expect and send strings separated by a newline
Xrather than whitespace.
X.SH OPTIONS
X.IP -d
XDisplay detailed actions of the program on standard error
X(\fBd\fRebug mode).
X.IP -S
XUse \fBsyslog(3)\fR calls to log failure or progress of
Xthe program, rather than displaying these messages on
X\fBstderr\fR.
X.IP -H
XInitiate hangup (\fBstty 0\fR) if script sequence fails.
X.IP "-T #"
XBy default, if the expect sequence does not complete
Xin 90 seconds, the entire script will fail by default.
XThis option sets this the timeout to something other
Xthan 90 seconds, or 0 to disable this function.
X.IP "-F #"
XWait a number of seconds if the script fails.
XIt is sometimes desirable to wait some short amount
Xof time if \fBexpsend\fR will be used in conjunction
Xwith a program which initiates a continuous redial
Xuntil the sequence succeeds.  This would prevent the
Xredial sequence from happening too rapidly.
X.IP "-G #"
XWhen using \fBexpsend\fR over a possibly noisy
Xcommunications medium, it is possible that there
Xis too much chatter to make the connection worthwhile.
XThis option specifies the number of characters that
Xare not part of the expect sequence to read before
Xassuming that the sequence should fail completely.
X.IP "-t tty"
XSpecify the tty device to perform the action on.
XBy default, the device attached to \fBstdin\fR is
Xused.
X.SH "SCRIPT FILE"
XThe \fBscript file\fR contains a series of lines in
Xthe order expect - send - expect - send [...] that
Xform a means of expecting a series of questions and
Xanswering those questions automatically.  Unlike
XUUCP, however, each of these directives are on
Xan individual line, separated by a newline.
X.PP
XA backslash character (\e) is treated specially
Xin the script file in that it escapes one or
Xmore special characters or options.  These
Xescape-functions are:
X.IP \er
XIndicates a carriage-return (ASCII 13)
X.IP \en
XIndicates a newline sequence (ASCII 13 and ASCII 10)
X.IP \e\e
XIndicates a backslash character
X.IP \ed
XPause approximately 2 seconds before continuing (send-only)
X.IP \ep
XPause approximately 1 second or less before continuing (send-only)
X.IP \eb
XIndicates a blank space.  This isn't necessarily needed
Xas the language uses a newline as a delimiter for the expect
Xand send strings, but it sometimes helps to indicate the
Xspace this way.
X.IP \eX
XNothing (null string).  This is useful in expect sequences
Xto say "expect nothing."  (expect-only)
X.IP \ec
XDo not send a carriage return at the end of this send
Xsequence (send-only)
X.IP \eF
XRemainder of expect sequence contains one or more "failure"
Xstrings.  When the string(s) indiciated after the \\F are
Xreceived, the expect sequence immediately fails and
X\fBexpsend\fR will terminate the entire expect-send
Xscript.  This functionality can be used to terminate
Xthe program faster when a busy signal or no carrier is
Xdetected by an intelligent modem.  (expect-only)
X.SH EXAMPLE
XWe would like to wait until the word \fBtesting\fR
Xis entered, to which we will reply \fBone two three\fR.
XIf, while waiting for \fBtesting\fR, we receive the
Xword \fBfoobar\fR, we will immediately terminate the
Xsession with a FAILED status.
X.PP
XIf the first sequence succeeds, we will then wait for
Xthe word \fBleave\fR to be entered, to which we will
Xreply \fBme alone\fR.  This string will fail if either
X\fBstay\fR or \fBthere\fR are entered.
X.PP
XThe script to effect this scenario would be:
X.nf
X.RS
X 
X testing\eFfoobar
X one two three
X leave\eFstay\eFthere
X me alone
X 
X.RE
X.fi
X.SH BUGS
XThe I/O system is not flexible and is really set-up
Xonly to talk to modems.
X.PP
XPOSIX-style termios are used, but this program was
Xwritten to assume the anomolies present in FreeBSD
Xtermios.
X.PP
XSome of the escaped characters are not needed.
X.PP
XIt is assumed that the terminal being connected to
Xhas its speed and all vital parameters set to sane
Xand correct values before \fBexpsend\fR is run.
X.SH AUTHOR
X.nf
XGil Kloepfer, Jr.
Xgil@limbic.ssdl.com
X.fi
X.SH ACKNOWLEDGEMENTS
XThanks to Lenny Tropiano (lenny@icus.com) for his recommendations
Xfor making this work on the IBM RT and for doing some testing of it.
XSpecial thanks to all those responsible for making BSD available
Xon the 80x86 platform, without which this software would not be
Xnecessary.
END-of-expsend.1
echo c - example
mkdir example > /dev/null 2>&1
echo x - example/slip.expsend
sed 's/^X//' >example/slip.expsend << 'END-of-example/slip.expsend'
X\X
X\pATZ
XOK
X\pATQ0V1M1&N17
XOK
X\pATDT5551212
XCONNECT\FBUSY\FNO\bCARRIER\FNO\bDIALTONE
X\p\r
Xogin:
X\pmylogin
Xword:
X\pmypassword
X\X
X\d
END-of-example/slip.expsend
echo x - example/slip.slconfig
sed 's/^X//' >example/slip.slconfig << 'END-of-example/slip.slconfig'
XPATH="/bin:/usr/bin:/usr/sbin:/sbin"
X# If the 2 args are not equal, the unit numbers are changing, else
X# this is the first config
X
Xif [ "$1" != "$2" ] ; then
X	route delete -net default hismach
X	ifconfig sl$1 down
X	ifconfig sl$1 delete
Xfi
X
X#
X# Config the new SLIP unit
X
Xifconfig sl$2 inet mymach hismach netmask 255.255.255.0 up
Xroute add -net default hismach 1
END-of-example/slip.slconfig
echo x - example/slip.slexit
sed 's/^X//' >example/slip.slexit << 'END-of-example/slip.slexit'
Xstty 0 <$1
END-of-example/slip.slexit
echo x - example/slipdial.sh
sed 's/^X//' >example/slipdial.sh << 'END-of-example/slipdial.sh'
XTTY="/dev/cua02"
X
Xstty -clocal <$TTY
Xslattach -h -s 38400 -u '/root/slip.slconfig' \
X	-e '/root/slip.slexit' \
X	-z -r "/usr/local/bin/expsend -SH -G 2048 -F 10 -t $TTY /root/slip.expsend" \
X	$TTY
END-of-example/slipdial.sh
exit
-- Cut Here -- -- Cut Here -- -- Cut Here -- -- Cut Here -- -- Cut Here --
-- 
Gil Kloepfer, Jr.              Home: gil@limbic.ssdl.com / ...!moxie!limbic!gil