[net.sources] rb/sb: Unix to micro file xfer

caf@omen.UUCP (Chuck Forsberg WA7KGX) (07/02/85)

By popular request from a number of sites unreachable by mail,
I am posting the newest versions of Unix rb and sb programs.
Rb and sb support YMODEM protocol file transfers to and from
micros running YAM or compatible programs.  Sb also supports
Pro-YAM's -g option which increases throughput over error
free connections.

VMS versions of these programs are also available.

#	This is a shell archive.
#	Remove everything above and including the cut line.
#	Then run the rest of the file through sh.
-----cut here-----cut here-----cut here-----cut here-----
#!/bin/sh
# shar:	Shell Archiver
#	Run the following text with /bin/sh to create:
#	rb.1
#	rb.c
#	rbsb.c
#	sb.1
#	sb.c
# This archive created: Tue Jul  2 02:22:53 1985
cat << \SHAR_EOF > rb.1
'\" Revision Level 
'\" Last Delta     07-01-85
.TH RB 1 OMEN
.SH NAME
rb \- receive files in batch mode
.SH SYNOPSIS
.B rb
[
.B \-bquv
]
.PP
.B rb
[
.B \-bcquv
]
.B file
.PP
.B [-][v]rbCOMMAND
.SH DESCRIPTION
.B Rb
receives 0 or more files as sent by yam
in batch mode.
Iff
.B file
is speficied,
a single file is received in MODEM7 single file mode.

Normally, the file contents are converted to
.SM Unix
conventions by stripping carriage returns and all characters
beginning with Control Z (CP/M end of file).
If the raw pathname ends in
".A",
".ARC",
".CCC",
".CL",
".CMD",
".COM",
".CRL",
".DAT",
".DIR",
".EXE",
".O",
".OBJ",
".OVL",
".PAG",
".REL",
".SAV",
".SUB",
".SWP",
".SYS",
".TAR",
".UTL",
".a",
".o",
".tar",
or if the first sector contains
data that suggest a binary file
(parity bits or characters in the range 000 to 006 before the first ^Z),
or if the file mode is transmitted and the 0100000 bit is set,
that file will be received in binary mode anyway.

Otherwise,
if the raw pathname ends in .MSG, or .TXT, any existing file will
be appended to rather than replaced.

Slashes in the pathname are changed to underscore.
Any trailing period in the pathname is eliminated.
Normally, each file name is converted to lower case
unless it contains one or more lower case letters.

Rb works with either standard 128 byte sectors or
1024 byte sectors
(yam k option).
The user should determine experimentally
the conditions under which use of 1k blocks
actually improves throughput without causing
problems.

If extended file information is received,
the file length controls the number of bytes written to
the output dataset,
and the modify time and file mode
(iff non zero)
are set accordingly.

If rb is invoked with stdout and stderr to different datasets,
Verbose is set to 2, causing frame by frame progress reports
to stderr.
This may be disabled with the
.B q
option.

.PP
The meanings of the available options are:
.PP
.PD 0
.TP
.B b
transfer all files in binary
(tell it like it is)
mode.
This option disables any append mode special processing.
.TP
.B c
Request cyclic redundancy check rather than
the MODEM7 checksum.
.TP
.B q
Quiet suppresses verbosity.
.TP
.B v
.IR Verbose
causes a list of file
names to be appended to
/tmp/rblog .
More v's generate more output.
.TP
.B u
Retain upper case letters in file names unconditionally.
.PD
.SH EXAMPLES
(
.SM Unix
command)
.RS
$rb
rb: ready C
.br
.RE
(yam command)
.RS
^E
>>>a0: sbt *.h *.c
.br
.RE
.SH SEE ALSO
sb(omen), sq(omen), usq(omen), undos(omen), Professional-YAM manual
.SH NOTES
If rb is invoked as
.B rbCOMMAND
(with an optional leading \- as generated by login(1))
rb will pipe each received file to ``COMMAND filename''
with the file contents as standard input.
A typical usage for this form is rbrmail which calls rmail
to post mail.
On some
.SM Unix
systems, the login directory must contain
COMMAND as login sets SHELL=rsh which disallows absolute
pathnames.
If invoked with a leading ``v'' rb will report progress to LOGFILE.
The following entry works for
.SM Unix
3.0.

rbrmail::5:1::/bin:/usr/ucb/rbrmail
.PP
The following (in a shell script)
may be used to fetch file(s) from a remote computer connected to /dev/tty7
once sb has been started on the remote.


rb -v >/dev/tty7 </dev/tty7
.SH BUGS
Path names are restricted to 127 characters.
In MODEM7 single file mode, the pathname is still processed
as described above.
.SH VMS
The VMS version does not set binary mode according to the incoming
file type.
Non binary file processing consists of stripping all characters beginning
with CPMEOF (^Z).

The VMS version does not set the file time.

VMS occaisonally loses incoming characters, resulting in retries
and degradation of throughput.

There may be unknown interactions between the VMS C standard i/o
package and RMS.

The VMS version does not allow the
.B rbCOMMAND
invocation.
SHAR_EOF
cat << \SHAR_EOF > rb.c
#define VERSION "2.15 03-04-85"

/*% cc -DUSG -DNFGVMIN -O -K % -o rb
 *
 * rb.c By Chuck Forsberg
 *
 * A program for Unix which can receive
 *  files from computers running YAM or MODEM.
 *  If no filename is given, YAM batch mode is assumed.
 *
 * Iff the program is invoked by rbCOMMAND, output is piped to 
 * "COMMAND filename"
 *
 *  Supports the CRC option or regular checksum.
 *  Received pathnames containing no lowercase letters will be changed to lower
 *  case unless -u option is given.
 *
 *  Unless the -b (binary) option is given, \r is discarded and
 *  ^Z (which is also discarded) acts as end of file.
 *
 *  Any slashes in the pathname are changed to underscore.
 *  If the raw pathname ends in .MSG or .TXT, any existing file will
 *  be appended to rather than replaced. Trailing periods are eliminated.
 *
 *  If the raw pathname ends in any of the extensions in Extensions,
 *   or .?Q* (squeezed file), or if the first sector contains binary-like
 *   data (parity bits or characters in the range 0 to 6 before ^Z is seen),
 *   or if the transmitted file mode has the 0100000 but set,
 *   that file will be received in binary mode anyway.
 *
 *
 * A log of activities is appended to LOGFILE with the -v option
 * If stdout and stderr refer to different devices, progress is displayed to
 * stderr.
 *
 * rb is derived from yam2.c and sb.c
 * rb uses Unix System III buffered input to reduce CPU time.
 *  USG UNIX (3.0) ioctl conventions courtesy  Jeff Martin
 * 	cc -O -DV7  rb.c -o rb		Unix V7, BSD 2.8 - 4.2
 *	cc -O -DUSG rb.c -o rb		USG (3.0) Unix
 *	cc -o rb.c			Regulus
 *		(Don't try this on Unix, you'll clobber the source!)
 *  Unix is a trademark of Western Electric Company
 *
 *  Regulus conventions 1-10-83 CAF
 *
 *  Some systems (Venix, Coherent, Regulus) do not support tty raw mode
 *  read(2) the same way as Unix. ONEREAD must be defined to force one
 *  character reads for these systems. Added 7-01-84 CAF
 *
 *  Alarm signal handling changed to work with 4.2 BSD 7-15-84 CAF 
 *
 *  NFGVMIN Added 1-13-85 CAF for PC-AT Xenix systems where c_cc[VMIN]
 *  doesn't seem to work (even though it compiles without error!).
 */
#define LOGFILE "/tmp/rblog"

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <ctype.h>
FILE *popen();

#define OK 0
#define FALSE 0
#define TRUE 1
#define ERROR (-1)

#define HOWMANY 133
#include "rbsb.c"	/* most of the system dependent stuff here */

char *substr();
FILE *fout;

char *Extensions[] = {
".A",
".ARC",
".CCC",
".CL",
".CMD",
".COM",
".CRL",
".DAT",
".DIR",
".EXE",
".O",
".OBJ",
".OVL",
".PAG",
".REL",
".SAV",
".SUB",
".SWP",
".SYS",
".TAR",
".UTL",
".a",
".o",
".tar",
""
};

/* Ward Christensen / CP/M parameters - Don't change these! */
#define ENQ 005
#define CAN ('X'&037)
#define XOFF ('s'&037)
#define XON ('q'&037)
#define SOH 1
#define STX 2
#define EOT 4
#define ACK 6
#define NAK 025
#define CPMEOF 032
#define WANTCRC 0103	/* send C not NAK to get crc not checksum */
#define TIMEOUT (-2)
#define ERRORMAX 5
#define RETRYMAX 5
#define WCEOT (-10)
#define SECSIZ 128	/* cp/m's Magic Number record size */
#define PATHLEN 257	/* ready for 4.2 bsd ? */
#define KSIZE 1024	/* record size with k option */
#define UNIXFILE 0x8000	/* happens to the the S_IFREG file mask bit for stat */

int Lastrx;
int Crcflg;
int Firstsec;
int Eofseen;		/* indicates cpm eof (^Z) has been received */
int totblocks;		/* total number of blocks received */
int errors;

#define DEFBYTL 2000000000L	/* default rx file size */
long Bytesleft;		/* number of bytes of incoming file left */
long Modtime;		/* Unix style mod time for incoming file */
short Filemode;		/* Unix style mode for incoming file */
char Pathname[PATHLEN];
char *Progname;		/* the name by which we were called */

int Batch=0;
int Wcsmask=0377;
int Topipe=0;
int MakeLCPathname=TRUE;	/* make received pathname lower case */
int Verbose=0;
int Quiet=0;		/* overrides logic that would otherwise set verbose */
int Rxbinary=FALSE;	/* receive all files in bin mode */
int Thisbinary;		/* current file is to be received in bin mode */
int Blklen;		/* record length of received packets */
char secbuf[KSIZE];
char linbuf[KSIZE];
int Lleft=0;		/* number of characters in linbuf */

jmp_buf tohere;		/* For the interrupt on RX timeout */

unsigned short updcrc();

alrm()
{
	longjmp(tohere, -1);
}

/* called by signal interrupt or terminate to clean things up */
bibi(n)
{
	canit(); mode(0);
	fprintf(stderr, "sb: caught signal %d; exiting", n);
	exit(128+n);
}

main(argc, argv)
char *argv[];
{
	register char *cp;
	register npats;
	char *virgin, **patts;
	int exitcode;

	setbuf(stderr, NULL);
	chkinvok(virgin=argv[0]);	/* if called as [-]rbCOMMAND set flag */
	npats = 0;
	while (--argc) {
		cp = *++argv;
		if (*cp == '-') {
			while( *++cp) {
				switch(*cp) {
				case '1':
					iofd = 1; break;
				case '7':
					Wcsmask = 0177;
				case 'b':
					Rxbinary=TRUE; break;
				case 'k':
				case 'c':
					Crcflg=TRUE; break;
				case 'q':
					Quiet=TRUE; Verbose=0; break;
				case 'u':
					MakeLCPathname=FALSE; break;
				case 'v':
					++Verbose; break;
				default:
					usage();
				}
			}
		}
		else if ( !npats && argc>0) {
			if (argv[0][0]) {
				npats=argc;
				patts=argv;
			}
		}
	}
	if (npats > 1)
		usage();
	if (Verbose) {
		if (freopen(LOGFILE, "a", stderr)==NULL) {
			printf("Can't open log file %s\n",LOGFILE);
			exit(0200);
		}
		setbuf(stderr, NULL);
		fprintf(stderr, "argv[0]=%s Progname=%s\n", virgin, Progname);
	}
	if (fromcu() && !Quiet) {
		if (Verbose == 0)
			Verbose = 2;
	}
	mode(1);
	if (signal(SIGINT, bibi) == SIG_IGN) {
		signal(SIGINT, SIG_IGN); signal(SIGKILL, SIG_IGN);
	}
	else {
		signal(SIGINT, bibi); signal(SIGKILL, bibi);
	}
	if (wcreceive(npats, patts)==ERROR) {
		exitcode=0200;
		canit();
	}
	mode(0);
	if (exitcode != 0)	/* bellow again with all thy might. */
		canit();
#ifdef REGULUS
	else
		printf("\6\6\6\6\6\n");	/* Regulus doesn't wait ... */
#endif
	exit(exitcode);
}


usage()
{
	fprintf(stderr,"%s %s by Chuck Forsberg\n", Progname, VERSION);
	fprintf(stderr,"Usage:	rb [-17buv]\n\tor rb [-1bcuv] file\n");
	exit(1);
}

wcreceive(argc, argp)
char **argp;
{
	if (Batch || argc==0) {
		Crcflg=(Wcsmask==0377);
		fprintf(stderr, "rb: ready ");
		for (;;) {
			totblocks=0;
			if (wcrxpn(secbuf)== ERROR)
				goto fubar;
			if (secbuf[0]==0)
				return OK;
			if (procheader(secbuf) == ERROR)
				goto fubar;
			if (wcrx()==ERROR)
				goto fubar;
		}
	} else {
		totblocks=0; Bytesleft = DEFBYTL; Filemode = 0; Modtime = 0L;

		strcpy(Pathname, *argp);
		if (fopen(*argp, "r") != NULL) {
			fprintf(stderr, "rb: %s exists\n", Pathname);
			goto fubar;
		}
		fprintf(stderr, "\nrb: ready to receive %s ", Pathname);
		if ((fout=fopen(Pathname, "w")) == NULL)
			return ERROR;
		if (wcrx()==ERROR)
			goto fubar;
	}
	return OK;
fubar:
	canit();
	if (Topipe && fout) {
		pclose(fout);  return ERROR;
	}
	if (fout)
		fclose(fout);
	return ERROR;
}


/*
 * Fetch a pathname from the other end as a C ctyle ASCIZ string.
 * Length is indeterminate as long as less than Blklen
 * a null string represents no more files
 */
wcrxpn(rpn)
char *rpn;	/* receive a pathname */
{
	register c;

#ifdef NFGVMIN
	readline(1);
#else
	purgeline();
#endif

et_tu:
	Firstsec=TRUE;
	sendline(Crcflg?WANTCRC:NAK);
	while ((c = wcgetsec(rpn, 100)) != 0) {
		log( "Pathname fetch returned %d\n", c);
		if (c == WCEOT) {
			sendline(ACK); readline(1); goto et_tu;
		}
		return ERROR;
	}
	sendline(ACK);
	return OK;
}

/*
 * Adapted from CMODEM13.C, written by
 * Jack M. Wierda and Roderick W. Hart
 */

wcrx()
{
	register int sectnum, sectcurr;
	register char sendchar;
	register char *p;
	int cblklen;			/* bytes to dump this block */
	time_t timep[2];

	Firstsec=TRUE;sectnum=0; Eofseen=FALSE;
	sendchar=Crcflg?WANTCRC:NAK;

	for (;;) {
		sendline(sendchar);	/* send it now, we're ready! */
		sectcurr=wcgetsec(secbuf, (sectnum&0177)?50:130);
		report(sectcurr);
		if (sectcurr==(sectnum+1 &Wcsmask)) {

			if (sectnum==0 && !Thisbinary)
				for (p=secbuf,sectcurr=Blklen;
				  *p != 032 && --sectcurr>=0; ++p)
					if (*p < 07 || (*p & 0200)) {
						Thisbinary++;
						if (Verbose)
							fprintf(stderr, "Changed to BIN\n");
						break;
					}
			sectnum++;
			cblklen = Bytesleft>Blklen ? Blklen:Bytesleft;
			if (putsec(secbuf, cblklen)==ERROR)
				return ERROR;
			if ((Bytesleft-=cblklen) < 0)
				Bytesleft = 0;
			sendchar=ACK;
		}
		else if (sectcurr==(sectnum&Wcsmask)) {
			log( "Received dup Sector\n");
			sendchar=ACK;
		}
		else if (sectcurr==WCEOT) {
			if (Topipe) {
				if (pclose(fout)!=ERROR) {
					sendline(ACK);
					return OK;
				}
				canit(); return ERROR;
			}
			if (fclose(fout)==ERROR) {
				canit();
				fprintf(stderr, "file close ERROR\n");
				return ERROR;
			}
			if (Modtime) {
				timep[0] = time(NULL);
				timep[1] = Modtime;
				utime(Pathname, timep);
			}
			if (Filemode)
				chmod(Pathname, (07777 & Filemode));
			sendline(ACK);
			return OK;
		}
		else if (sectcurr==ERROR)
			return ERROR;
		else {
			log( "Sync Error\n");
			return ERROR;
		}
	}
}

/*
 * wcgetsec fetches a Ward Christensen type sector.
 * Returns sector number encountered or ERROR if valid sector not received,
 * or CAN CAN received
 * or WCEOT if eot sector
 * time is timeout for first char, set to 4 seconds thereafter
 ***************** NO ACK IS SENT IF SECTOR IS RECEIVED OK **************
 *    (Caller must do that when he is good and ready to get next sector)
 */

wcgetsec(rxbuf, maxtime)
char *rxbuf;
int maxtime;
{
	register checksum, wcj, firstch;
	register unsigned short oldcrc;
	register char *p;
	int sectcurr;

	for (Lastrx=errors=0; errors<RETRYMAX; errors++) {

		if ((firstch=readline(maxtime))==STX) {
			Blklen=KSIZE; goto get2;
		}
		if (firstch==SOH) {
			Blklen=SECSIZ;
get2:
			sectcurr=readline(1);
			if ((sectcurr+(oldcrc=readline(1)))==Wcsmask) {
				oldcrc=checksum=0;
				for (p=rxbuf,wcj=Blklen; --wcj>=0; ) {
					if ((firstch=readline(1)) < 0)
						goto bilge;
					oldcrc=updcrc(firstch, oldcrc);
					checksum += (*p++ = firstch);
				}
				if ((firstch=readline(1)) < 0)
					goto bilge;
				if (Crcflg) {
					oldcrc=updcrc(firstch, oldcrc);
					if ((firstch=readline(1)) < 0)
						goto bilge;
					oldcrc=updcrc(firstch, oldcrc);
					if (oldcrc)
						log("CRC=0%o\n", oldcrc);
					else {
						Firstsec=FALSE;
						return sectcurr;
					}
				}
				else if (((checksum-firstch)&Wcsmask)==0) {
					Firstsec=FALSE;
					return sectcurr;
				}
				else
					log( "Checksum Error\n");
			}
			else
				log("Sector number garbled 0%o 0%o\n",
				 sectcurr, oldcrc);
		}
		/* make sure eot really is eot and not just mixmash */
#ifdef NFGVMIN
		else if (firstch==EOT && readline(1)==TIMEOUT)
			return WCEOT;
#else
		else if (firstch==EOT && Lleft==0)
			return WCEOT;
#endif
		else if (firstch==CAN) {
			if (Lastrx==CAN) {
				log( "Sender CANcelled\n");
				return ERROR;
			} else {
				Lastrx=CAN;
				continue;
			}
		}
		else if (firstch==TIMEOUT) {
			if (Firstsec)
				goto humbug;
bilge:
			log( "Timeout\n");
		}
		else
			log( "Got 0%o sector header\n", firstch);

humbug:
		Lastrx=0;
		while(readline(1)!=TIMEOUT)
			;
		if (Firstsec)
			sendline(Crcflg?WANTCRC:NAK);
		else {
			maxtime=40; sendline(NAK);
		}
	}
	/* try to stop the bubble machine. */
	canit();
	return ERROR;
}

/*
 * This version of readline is reasoably well suited for
 * reading many characters.
 *  (except, currently, for the Regulus version!)
 *
 * timeout is in tenths of seconds
 */
readline(timeout)
int timeout;
{
	register n;
	static char *cdq;	/* pointer for removing chars from linbuf */

	if (--Lleft >= 0) {
		if (Verbose > 8) {
			fprintf(stderr, "%02x ", *cdq&0377);
		}
		return (*cdq++ & Wcsmask);
	}
	n = timeout/10;
	if (n < 2)
		n = 3;
	if (Verbose > 3)
		fprintf(stderr, "Calling read: n=%d ", n);
	if (setjmp(tohere)) {
#ifdef TIOCFLUSH
/*		ioctl(iofd, TIOCFLUSH, 0); */
#endif
		Lleft = 0;
		if (Verbose>1)
			fprintf(stderr, "Readline:TIMEOUT\n");
		return TIMEOUT;
	}
	signal(SIGALRM, alrm); alarm(n);
#ifdef ONEREAD
	/* Sorry, Regulus and some others don't work right in raw mode! */
	Lleft=read(iofd, cdq=linbuf, 1);
#else
	Lleft=read(iofd, cdq=linbuf, KSIZE);
#endif
	alarm(0);
	if (Verbose > 3) {
		fprintf(stderr, "Read returned %d bytes\n", Lleft);
	}
	if (Lleft < 1)
		return TIMEOUT;
	--Lleft;
	if (Verbose > 8) {
		fprintf(stderr, "%02x ", *cdq&0377);
	}
	return (*cdq++ & Wcsmask);
}




purgeline()
{
	Lleft = 0;
#ifdef USG
	ioctl(iofd, TCFLSH, 0);
#else
	lseek(iofd, 0L, 2);
#endif
}

/* update CRC */
unsigned short
updcrc(c, crc)
register c;
register unsigned crc;
{
	register count;

	for (count=8; --count>=0;) {
		if (crc & 0x8000) {
			crc <<= 1;
			crc += (((c<<=1) & 0400)  !=  0);
			crc ^= 0x1021;
		}
		else {
			crc <<= 1;
			crc += (((c<<=1) & 0400)  !=  0);
		}
	}
	return crc;	
}

/*
 * process incoming header
 */
procheader(name)
char *name;
{
	register char *openmode, *p, **pp;

	/* set default parameters */
	openmode = "w"; Thisbinary=Rxbinary;
	Bytesleft = DEFBYTL; Filemode = 0; Modtime = 0L;

	p = name + 1 + strlen(name);
	if (*p) {	/* file coming from Unix type system */
		sscanf(p, "%ld%lo%o", &Bytesleft, &Modtime, &Filemode);
		if (Filemode & UNIXFILE)
			++Thisbinary;
		if (Verbose) {
			fprintf(stderr,  "Incoming: %s %ld %lo %o\n",
			  name, Bytesleft, Modtime, Filemode);
		}
	}
	else {		/* File coming from CP/M type system */
		for (p=name; *p; ++p)		/* change / to _ */
			if ( *p == '/')
				*p = '_';

		if ( *--p == '.')		/* zap trailing period */
			*p = 0;
	}

	/* scan for extensions that signify a binary file */
	if (p=substr(name, "."))
		for (pp=Extensions; **pp; ++pp)
			if (strcmp(p, *pp)==0) {
				Thisbinary=TRUE; break;
			}

	/* scan for files which should be appended */
	if ( !Thisbinary
	  && (substr(name, ".TXT")
	  || substr(name, ".txt")
	  || substr(name, ".MSG")))
		openmode = "a";
	if (MakeLCPathname && !IsAnyLower(name))
		uncaps(name);
	if (Topipe) {
		sprintf(Pathname, "%s %s", Progname+2, name);
		if (Verbose)
			fprintf(stderr,  "Topipe: %s %s\n",
			  Pathname, Thisbinary?"BIN":"ASCII");
		if ((fout=popen(Pathname, "w")) == NULL)
			return ERROR;
	} else {
		strcpy(Pathname, name);
		if (Verbose) {
			fprintf(stderr,  "Receiving %s %s %s\n",
			  name, Thisbinary?"BIN":"ASCII", openmode);
		}
		if ((fout=fopen(name, openmode)) == NULL)
			return ERROR;
	}
	return OK;
}

/* make string s lower case */
uncaps(s)
register char *s;
{
	for ( ; *s; ++s)
		if (isupper(*s))
			*s = tolower(*s);
}


/*
 * IsAnyLower returns TRUE if string s has lower case letters.
 */
IsAnyLower(s)
register char *s;
{
	for ( ; *s; ++s)
		if (islower(*s))
			return TRUE;
	return FALSE;
}
/*
 * putsec writes the n characters of buf to receive file fout.
 *  If not in binary mode, carriage returns, and all characters
 *  starting with CPMEOF are discarded.
 */
putsec(buf, n)
char *buf;
register n;
{
	register char *p;

	++totblocks;
	if (Thisbinary)
	{
		for (p=buf; --n>=0; )
			putc( *p++, fout);
	}
	else {
		if (Eofseen)
			return OK;
		for (p=buf; --n>=0; ++p ) {
			if ( *p == '\r')
				continue;
			if (*p == CPMEOF) {
				Eofseen=TRUE; return OK;
			}
			putc(*p ,fout);
		}
	}
	return OK;
}
sendline(c)
{
	char d;

	d = c;
	if (Verbose>2)
		fprintf(stderr, "Sendline: %x\n", c);
	write(1, &d, 1);
	Lleft=0;	/* Do read next time ... */
}


/*
 * substr(string, token) searches for token in string s
 * returns pointer to token within string if found, NULL otherwise
 */
char *
substr(s, t)
register char *s,*t;
{
	register char *ss,*tt;
	/* search for first char of token */
	for (ss=s; *s; s++)
		if (*s == *t)
			/* compare token with substring */
			for (ss=s,tt=t; ;) {
				if (*tt == 0)
					return s;
				if (*ss++ != *tt++)
					break;
			}
	return NULL;
}

/*VARARGS1*/
log(s,p,u)
char *s, *p, *u;
{
	if (!Verbose)
		return;
	fprintf(stderr, "error %d: ", errors);
	fprintf(stderr, s, p, u);
}

/* send 10 CAN's to try to get the other end to shut up */
canit()
{
	register n;
	for (n=10; --n>=0; )
		sendline(CAN);
}

#ifdef REGULUS
/*
 * copies count bytes from s to d
 * (No structure assignment in Regulus C compiler)
 */

movmem(s, d, count)
register char *s, *d;
register count;
{
	while (--count >= 0)
		*d++ = *s++;
}
#endif

/*
 * return 1 iff stdout and stderr are different devices
 *  indicating this program operating with a modem on a
 *  different line
 */
fromcu()
{
	struct stat a, b;
	fstat(1, &a); fstat(2, &b);
	return (a.st_rdev != b.st_rdev);
}

report(sct)
int sct;
{
	if (Verbose>1)
		fprintf(stderr,"%03d%c",sct,sct%10? ' ' : '\r');
}

/*
 * if called as [-][dir/../]vrbCOMMAND set Verbose to 1
 * if called as [-][dir/../]rbCOMMAND set the pipe flag
 */
chkinvok(s)
char *s;
{
	register char *p;

	p = s;
	while (*p == '-')
		s = ++p;
	while (*p)
		if (*p++ == '/')
			s = p;
	if (*s == 'v') {
		Verbose=1; ++s;
	}
	Progname = s;
	if (s[2] && s[0]=='r' && s[1]=='b')
		Topipe=TRUE;
}

SHAR_EOF
cat << \SHAR_EOF > rbsb.c
/* -rev 07-02-85
 * mode function and most of the rest of the system dependent
 * stuff for rb.c and sb.c   This file is #included so the includer
 * can set parameters such as HOWMANY.
 */

#ifdef USG
#include <sys/types.h>
#include <sys/stat.h>
#include <termio.h>
#include <sys/ioctl.h>
#define OS "USG"
#endif

#ifdef V7
#include <sys/types.h>
#include <sys/stat.h>
#include <sgtty.h>
#define OS "V7"
#endif

#ifndef OS
#include <termio.h>
#include <sys/ioctl.h>
#include <stat.h>
#define REGULUS
#define ONEREAD
#define OS "REGULUS"
#define void int
#define time_t long
#endif


#ifdef ICANON
struct termio oldtty, tty;
#else
struct sgttyb oldtty, tty;
struct tchars oldtch, tch;
#endif

int iofd = 0;		/* File descriptor for ioctls & reads */

/*
 * mode(n)
 *  2: set a cbreak, XON/XOFF control mode if using Pro-YAM's -g option
 *  1: save old tty stat, set raw mode 
 *  0: restore original tty mode
 */
mode(n)
{
	static did0 = FALSE;

	switch(n) {
#ifdef USG
	case 2:	/* Cbreak mode used by sb when -g detected */
		if(!did0)
			(void) ioctl(iofd, TCGETA, &oldtty);
		tty = oldtty;

		tty.c_iflag = BRKINT|IXON;

		tty.c_oflag = 0;	/* Transparent output */

		tty.c_cflag &= ~PARENB;	/* Disable parity */
		tty.c_cflag |= CS8;	/* Set character size = 8 */

		tty.c_lflag = ISIG;
		tty.c_cc[VINTR] = 030;	/* Interrupt on CANCEL */

		(void) ioctl(iofd, TCSETA, &tty);
		did0 = TRUE;
		return OK;
	case 1:
		if(!did0)
			(void) ioctl(iofd, TCGETA, &oldtty);
		tty = oldtty;

		tty.c_iflag = IGNBRK;

		 /* No echo, crlf mapping, INTR, QUIT, delays, no erase/kill */
		tty.c_lflag &= ~(ECHO | ICANON | ISIG);
		tty.c_lflag |= XCLUDE;

		tty.c_oflag = 0;	/* Transparent output */

		tty.c_cflag &= ~PARENB;	/* Leave baud rate alone, disable parity */
		tty.c_cflag |= CS8;	/* Set character size = 8 */
		tty.c_cc[VMIN] = HOWMANY; /* Satisfy reads when this many chars in */
		tty.c_cc[VTIME] = 1;	/* ... or in this many tenths of seconds */
		(void) ioctl(iofd, TCSETA, &tty);
		did0 = TRUE;
		return OK;
#endif
#ifdef V7
	case 2:
		if(!did0) {
			ioctl(iofd, TIOCEXCL, 0);
			ioctl(iofd, TIOCGETP, &oldtty);
			ioctl(iofd, TIOCGETC, &oldtch);
		}
		tty = oldtty;
		tch = oldtch;
		tch.t_intrc = 030;
		tty.sg_flags |= CBREAK;
		tty.sg_flags &= ~ECHO;
		ioctl(iofd, TIOCSETP, &tty);
		ioctl(iofd, TIOCSETC, &tch);
		did0 = TRUE;
		return OK;
	case 1:
		if(!did0) {
			ioctl(iofd, TIOCEXCL, 0);
			ioctl(iofd, TIOCGETP, &oldtty);
			ioctl(iofd, TIOCGETC, &oldtch);
		}
		tty = oldtty;
		tty.sg_flags |= RAW;
		tty.sg_flags &= ~ECHO;
		ioctl(iofd, TIOCSETP, &tty);
		did0 = TRUE;
		return OK;
#endif
#ifdef REGULUS
	case 2:
		return ERROR;
	case 1:
		if(!did0) {
			ioctl(iofd, TCGETA, &oldtty);
		}
		tty = oldtty;

		tty.c_lflag = 0;
		tty.c_iflag = IGNBRK;
		tty.c_oflag = 0;	/* Transparent output */

		tty.c_cflag &= ~PARENB;	/* Leave baud rate alone, disable parity */
		tty.c_cflag |= CS8;	/* Set character size = 8 */
		tty.c_cc[VMIN] = HOWMANY; /* Satisfy reads when this many chars in */
		tty.c_cc[VTIME] = 1;	/* ... or in this many tenths of seconds */
		ioctl(iofd, TCSETA, &tty);
		did0 = TRUE;
		return OK;
#endif
#ifdef REGULUS10
		if(!did0) {
			ioctl(iofd, TIOCGETP, &oldtty);
		}
		/* Sorry, No structure assignment in Regulus  C */
		movmem( (char *)&oldtty, (char *)&tty, sizeof(tty));
		tty.sg_flags |= (EIGHTBIT|RAW);
		tty.sg_flags &= ~ECHO;
		tty.sg_ledit &= ~LEDIT;
		ioctl(iofd, TIOCSETP, &tty);
		did0 = TRUE;
		return OK;
#endif
	case 0:
		if(!did0)
			return ERROR;
#ifdef USG
		(void) ioctl(iofd, TCSBRK, 1);	/* Wait for output to drain */
		(void) ioctl(iofd, TCFLSH, 1);	/* Flush input queue */
		(void) ioctl(iofd, TCSETAW, &oldtty);	/* Restore original modes */
		(void) ioctl(iofd, TCXONC,1);	/* Restart output */
#endif
#ifdef V7
		ioctl(iofd, TIOCSETP, &oldtty);
		ioctl(iofd, TIOCSETC, &oldtch);
		ioctl(iofd, TIOCNXCL, 0);
#endif
#ifdef REGULUS
		ioctl(iofd, TCSETAW, &oldtty);	/* Restore original modes */
#endif
#ifdef REGULUS10
		ioctl(iofd, TIOCSETP, &oldtty);
#endif
		return OK;
	default:
		return ERROR;
	}
}

SHAR_EOF
cat << \SHAR_EOF > sb.1
'\" Revision Level 
'\" Last Delta     07-02-85
.TH SB 1 OMEN
.SH NAME
sb \- send files in batch mode
.SH SYNOPSIS
.B sb
[
.B \-dfkquv
]
.B file ...
.SH DESCRIPTION
.B Sb
sends one or more files to yam or rb
in batch mode.

Only the file name part of the pathname is transmitted.

On Unix systems, additional information about the file is transmitted.
If the receiving program uses this information,
the transmitted file length controls the exact number of bytes written to
the output dataset,
and the modify time and file mode
are set accordingly.

Sb can send a single file to most MODEM protocol implementations.
These ignore the first block containing the file name.
(The received file name must be supplied by the user.)

If sb is invoked with stdout and stderr to different datasets,
Verbose is set to 2, causing frame by frame progress reports
to stderr.
This may be disabled with the
.B q
option.

Iff sb is invoked with $SHELL set and iff that vairable contains the
string ``rsh'' (restricted shell), sb operates in restricted mode.
Restricted mode restricts pathnames to the current directory and
PUBDIR (conventionally, /usr/spool/uucppublic) and/or subdirectories
thereof.

Sb supports the Pro-YAM
.B -g
option by switching to a "cbreak" tty mode with XON/XOFF folow control
and the interrupt character set to CAN.
The Pro-YAM
.B -g
option increases throughput over error free channels
(direct connection, X.PC, etc.)
by not acknowledging each transmitted sector.
.PP
The meanings of the available options are:
.PP
.PD 0
.TP
.B d
Change all instances of "." to "/" in the transmitted pathname.
Thus, C.omenB0000 (which is unacceptable to MSDOS or CP/M)
is transmitted as C/omenB0000.
If the resultant filename has more than 8 characters in the stem,
a "." in inserted to allow a total of eleven.
.TP
.B f
Send Full pathnname.
Normally directory prefices are stripped from the transmitted
filename.
.TP
.B k
Send files using 1024 byte blocks
rather than the default 128 byte blocks.
The user should determine experimentally
the conditions under which use of 1k blocks
actually improves throughput without causing
problems.
.TP
.B q
Quiet suppresses verbosity.
.TP
.B u
Unlink the file after successful transmission.
.TP
.B v
.IR Verbose
causes a list of file
names to be appended to
/tmp/rblog .
More v's generate more output.
.PD
.SH EXAMPLES
(Unix command)
.RS
sb -k *.c
.br
.RE
(Professional-YAM command)
.RS
<F1>
>>>C: rt -y
.br
.RE
.SH SEE ALSO
rb(omen), sq(omen), usq(omen), Professional-YAM manual, todos(omen),
tocpm(omen), tomac(omen)
.SH BUGS
The VMS version does not transmit the file date.

The VMS version does not recognize Pro-YAM\'s
.B -g
option.

The VMS version calculates the file length by counting the bytes therin.

When VMS is lightly loaded, the response time may be too quick for MODEM7
unless the MODEM7
.B "q"
modifier is used.

There may be unknown interactions between the VMS C standard i/o
package and RMS.
SHAR_EOF
cat << \SHAR_EOF > sb.c
#define VERSION "sb 2.17 07-02-85"
#define PUBDIR "/usr/spool/uucppublic"

/*% cc -O -DUSG sb.c -o sb

 * sb.c By Chuck Forsberg
 *
 * A small program for Unix which can send 1 or more
 * files in Batch mode to computers running YAM. (Use "rb" in YAM.)
 * Supports the CRC option or regular checksum.
 * Exit status is 0 for all transfers completed successfully,
 * 1 for 1 or more unreadable files or'd with 200 for incomplete file xfer.
 *
 * accepts -k option for 1kb record length.
 *
 * sb is derived from yam2.c
 * Uses buffered i/o to reduce the CPU time compared to UMODEM.
 *  USG UNIX (3.0) ioctl conventions courtesy  Jeff Martin
 * 	cc -O -DV7  sb.c -o sb		vanilla Unix version 7
 *	cc -O -DUSG sb.c -o sb		USG (3.0) Unix
 *  ******* Some systems (Venix, Coherent, Regulus) do not *******
 *  ******* support tty raw mode read(2) identically to    *******
 *  ******* Unix. ONEREAD must be defined to force one     *******
 *  ******* character reads for these systems.		   *******
 */

#define LOGFILE "/tmp/sblog"

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <ctype.h>

#define PATHLEN 256
#define OK 0
#define FALSE 0
#define TRUE 1
#define ERROR (-1)

#define HOWMANY 2
#include "rbsb.c"	/* most of the system dependent stuff here */

FILE *in;

/* Ward Christensen / CP/M parameters - Don't change these! */
#define ENQ 005
#define CAN ('X'&037)
#define XOFF ('s'&037)
#define XON ('q'&037)
#define SOH 1
#define STX 2
#define EOT 4
#define ACK 6
#define NAK 025
#define CPMEOF 032
#define WANTCRC 0103	/* send C not NAK to get crc not checksum */
#define WANTG 0107	/* Send G not NAK to get nonstop batch xmsn */
#define TIMEOUT (-2)
#define ERRORMAX 5
#define RETRYMAX 5
#define SECSIZ 128	/* cp/m's Magic Number record size */
#define KSIZE 1024

char Lastrx;
char Crcflg;
int Wcsmask=0377;
int Verbose=0;
int Restricted=0;	/* restricted; no /.. or ../ in filenames */
int Quiet=0;		/* overrides logic that would otherwise set verbose */
int Fullname=0;		/* transmit full pathname */
int Unlinkafter=0;	/* Unlink file after it is sent */
int Dottoslash=0;	/* Change foo.bar.baz to foo/bar/baz */
int firstsec;
int errcnt=0;		/* number of files unreadable */
int blklen=SECSIZ;	/* length of transmitted records */
int Optiong;		/* Let it rip no wait for sector ACK's */
int Noeofseen;
int Totsecs;		/* total number of sectors this file */
char txbuf[KSIZE];
int Filcnt=0;		/* count of number of files opened */

jmp_buf tohere;		/* For the interrupt on RX timeout */

unsigned updcrc();
char *substr(), *getenv();

/* called by signal interrupt or terminate to clean things up */
bibi(n)
{
	canit(); fflush(stdout); mode(0);
	fprintf(stderr, "sb: caught signal %d; exiting\n", n);
	if (n == SIGQUIT)
		abort();
	exit(128+n);
}

#ifdef REGULUS
sendline(c)
{
	static char d[2];

	d[0] = c&Wcsmask;
	write(1, d, 1);
}
#else
#define sendline(c) putchar(c & Wcsmask)
#endif

main(argc, argv)
char *argv[];
{
	register char *cp;
	register npats;
	int agcnt; char **agcv;
	char **patts;
	int exitcode;
#ifndef REGULUS
	static char xXbuf[BUFSIZ];
#endif

	if ((cp=getenv("SHELL")) && substr(cp, "rsh"))
		Restricted=TRUE;

	npats=0;
	if (argc<2)
		goto usage;
#ifndef REGULUS
	setbuf(stdout, xXbuf);		
#endif
	while (--argc) {
		cp = *++argv;
		if (*cp == '-') {
			while ( *++cp) {
				switch(*cp) {
				case '1':
					iofd = 1; break;
				case '7':
					Wcsmask=0177; break;
				case 'd':
					++Dottoslash;
					/* **** FALL THROUGH TO **** */
				case 'f':
					Fullname=TRUE; break;
				case 'k':
					blklen=KSIZE; break;
				case 'q':
					Quiet=TRUE; Verbose=0; break;
				case 'u':
					++Unlinkafter; break;
				case 'v':
					++Verbose; break;
				default:
					goto usage;
				}
			}
		}
		else if ( !npats && argc>0) {
			if (argv[0][0]) {
				npats=argc;
				patts=argv;
			}
		}
	}
	if (npats < 1) {
usage:
		fprintf(stderr,"%s by Chuck Forsberg\n", VERSION);
		fprintf(stderr,"Usage: sb [-7dfkquv] file ...\n");
		exit(1);
	}
	
	if (Verbose) {
		if (freopen(LOGFILE, "a", stderr)==NULL) {
			printf("Can't open log file %s\n",LOGFILE);
			exit(0200);
		}
		setbuf(stderr, NULL);
	}
	if (fromcu() && !Quiet) {
		if (Verbose == 0)
			Verbose = 2;
	}
	if (Verbose != 1) {
		fprintf(stderr, "sb: %d file%s requested:\r\n",
		 npats, npats>1?"s":"");
		for ( agcnt=npats, agcv=patts; --agcnt>=0; ) {
			fprintf(stderr, "%s ", *agcv++);
		}
	}

	mode(1);
	if (signal(SIGINT, bibi) == SIG_IGN) {
		signal(SIGINT, SIG_IGN); signal(SIGKILL, SIG_IGN);
	}
	else {
		signal(SIGINT, bibi); signal(SIGKILL, bibi);
		signal(SIGQUIT, bibi);
	}

	if (wcsend(npats, patts)==ERROR) {
		exitcode=0200;
		canit();
	}
	fflush(stdout);
	mode(0);
	exit((errcnt != 0) | exitcode);
}

wcsend(argc, argp)
char *argp[];
{
	register n;

	Crcflg=FALSE;
	firstsec=TRUE;
	for (n=0; n<argc; ++n) {
		Totsecs = 0;
		if (wcs(argp[n])==ERROR)
			goto fubar;
	}
	Totsecs = 0;
	if (Filcnt==0) {	/* bitch if we couldn't open ANY files */
		fprintf(stderr,"\r\nCan't open any requested files.\n");
		return ERROR;
	}
	else if (wctxpn("")==ERROR)
		goto fubar;
	return OK;
fubar:
	canit(); return ERROR;
}

wcs(oname)
char *oname;
{
	register c;
	register char *p;
	struct stat f;
	char name[PATHLEN];

	strcpy(name, oname);

	if (Restricted) {
		/* restrict pathnames to current tree or uucppublic */
		if ( substr(name, "../")
		 || (name[0]== '/' && strncmp(name, PUBDIR, strlen(PUBDIR))) ) {
			canit();
			fprintf(stderr,"\r\nsb:\tSecurity Violation\r\n");
			return ERROR;
		}
	}

	if ((in=fopen(oname, "r"))==NULL) {
		++errcnt;
		return OK;	/* pass over it, there may be others */
	}
	++Noeofseen;
	/* Check for directory or block special files */
#ifndef REGULUS		/* This doesn't seem to work on Regulus */
	fstat(fileno(in), &f);
	c = f.st_mode & S_IFMT;
	if (c == S_IFDIR || c == S_IFBLK) {
		fclose(in);
		return OK;
	}
#endif
	++Filcnt;
	if (wctxpn(name)== ERROR)
		return ERROR;
	if (wctx()==ERROR)
		return ERROR;
	if (Unlinkafter)
		unlink(oname);
	return 0;
}

/*
 * generate and transmit pathname block consisting of
 *  pathname (null terminated),
 *  file length, mode time and file mode in octal
 *  as provided by the Unix fstat call.
 *  N.B.: modifies the passed name, may extend it!
 */
wctxpn(name)
char *name;
{
	register firstch;
	register char *p, *q;
	char name2[PATHLEN];
	struct stat f;

	logent("\r\nAwaiting pathname nak for %s\r\n", *name?name:"<END>");
	if (getnak())
		return ERROR;

	q = (char *) 0;
	if (Dottoslash) {		/* change . to . */
		for (p=name; *p; ++p) {
			if (*p == '/')
				q = p;
			else if (*p == '.')
				*(q=p) = '/';
		}
		if (q && strlen(++q) > 8) {	/* If name>8 chars */
			q += 8;			/*   make it .ext */
			strcpy(name2, q);	/* save excess of name */
			*q = '.';
			strcpy(++q, name2);	/* add it back */
		}
	}

	for (p=name, q=txbuf ; *p; )
		if ((*q++ = *p++) == '/' && !Fullname)
			q = txbuf;
	*q++ = 0;
	p=q;
	while (q < (txbuf + KSIZE))
		*q++ = 0;
#ifndef REGULUS		/* This doesn't seem to work on Regulus */
	if (*name && fstat(fileno(in), &f)!= -1)
		sprintf(p, "%lu %lo %o", f.st_size, f.st_mtime, f.st_mode);
#endif
	/* force 1k blocks if name won't fit in 128 byte block */
	if (strlen(txbuf) > 127)
		blklen=KSIZE;
	if (wcputsec(txbuf, 0, SECSIZ)==ERROR)
		return ERROR;
	return OK;
}

getnak()
{
	register firstch;

	Lastrx = 0;
	for (;;) {
		switch (firstch = readock(800,2)) {
		case TIMEOUT:
			logent("Timeout on pathname\n");
			return TRUE;
		case WANTG:
			mode(2);	/* Set cbreak, XON/XOFF, etc. */
			Optiong = TRUE;
		case WANTCRC:
			Crcflg = TRUE;
		case NAK:
			return FALSE;
		case CAN:
			if (Lastrx == CAN)
				return TRUE;
		default:
			break;
		}
		Lastrx = firstch;
	}
}


wctx()
{
	register int sectnum, attempts, firstch;

	firstsec=TRUE;

	while ((firstch=readock(400, 2))!=NAK && firstch != WANTCRC
	  && firstch!=TIMEOUT && firstch!=CAN)
		;
	if (firstch==CAN) {
		logent("Receiver CANcelled\n");
		return ERROR;
	}
	if (firstch==WANTCRC)
		Crcflg=TRUE;
	sectnum=1;
	while (filbuf(txbuf, blklen)) {
		if (wcputsec(txbuf, sectnum, blklen)==ERROR) {
			return ERROR;
		} else
			sectnum++;
	}
	if (Verbose>1)
		fprintf(stderr, " Closing ");
	fclose(in);
	attempts=0;
	do {
		logent(" EOT ");
		purgeline();
		sendline(EOT);
		fflush(stdout);
		++attempts;
	}
		while ((firstch=(readock(100, 2)) != ACK) && attempts < RETRYMAX);
	if (attempts == RETRYMAX) {
		logent("No ACK on EOT\n");
		return ERROR;
	}
	else
		return OK;
}

wcputsec(buf, sectnum, cseclen)
char *buf;
int sectnum;
int cseclen;	/* data length of this sector to send */
{
	register checksum, wcj;
	register char *cp;
	unsigned oldcrc;
	int firstch;
	int attempts;

	firstch=0;	/* part of logic to detect CAN CAN */

	if (Verbose>1)
		fprintf(stderr, "\rSector %3d %2dk ", Totsecs, Totsecs/8 );
	for (attempts=0; attempts <= RETRYMAX; attempts++) {
		Lastrx= firstch;
		sendline(cseclen==KSIZE?STX:SOH);
		sendline(sectnum);
		sendline(-sectnum -1);
		oldcrc=checksum=0;
		for (wcj=cseclen,cp=buf; --wcj>=0; ) {
			sendline(*cp);
			oldcrc=updcrc(*cp, oldcrc);
			checksum += *cp++;
		}
		if (Crcflg) {
			oldcrc=updcrc(0,updcrc(0,oldcrc));
			sendline((int)oldcrc>>8);
			sendline((int)oldcrc);
		}
		else
			sendline(checksum);

		if (Optiong) {
			firstsec = FALSE; return OK;
		}
		firstch = readock(400, (Noeofseen&&sectnum) ? 2:1);
gotnak:
		switch (firstch) {
		case CAN:
			if(Lastrx == CAN) {
cancan:
				logent("Cancelled\n");  return ERROR;
			}
			break;
		case TIMEOUT:
			logent("Timeout on sector ACK\n"); continue;
		case WANTCRC:
			if (firstsec)
				Crcflg = TRUE;
		case NAK:
			logent("NAK on sector\n"); continue;
		case ACK: 
			firstsec=FALSE;
			Totsecs += (cseclen>>7);
			return OK;
		case ERROR:
			logent("Got burst for sector ACK\n"); break;
		default:
			logent("Got %02x for sector ACK\n", firstch); break;
		}
		for (;;) {
			Lastrx = firstch;
			if ((firstch = readock(400, 2)) == TIMEOUT)
				break;
			if (firstch == NAK || firstch == WANTCRC)
				goto gotnak;
			if (firstch == CAN && Lastrx == CAN)
				goto cancan;
		}
	}
	logent("Retry Count Exceeded\n");
	return ERROR;
}


/* fill buf with count chars padding with ^Z for CPM */
filbuf(buf, count)
register char *buf;
{
	register c, m;
	m=count;
	while ((c=getc(in))!=EOF) {
		*buf++ =c;
		if (--m == 0)
			break;
	}
	if (m==count)
		return (Noeofseen=0);
	else
		while (--m>=0)
			*buf++ = CPMEOF;
	return count;
}


alrm()
{
	longjmp(tohere, -1);
}


/*
 * readock(timeout, count) reads character(s) from file descriptor 0
 *  (1 <= count <= 3)
 * it attempts to read count characters. If it gets more than one,
 * it is an error unless all are CAN
 * (otherwise, only normal response is ACK, CAN, or C)
 *
 * timeout is in tenths of seconds
 */
readock(timeout, count)
{
	register int c;
	static char byt[5];

	fflush(stdout);
	if (setjmp(tohere)) {
		logent("TIMEOUT\n");
		return TIMEOUT;
	}
	c = timeout/10;
	if (c<2)
		c=2;
	if (Verbose>3)
		fprintf(stderr, "Timeout=%d Calling alarm(%d) ", timeout, c);
	signal(SIGALRM, alrm); alarm(c);
#ifdef ONEREAD
	c=read(iofd, byt, 1);		/* regulus raw read is unique */
#else
	c=read(iofd, byt, count);
#endif
	alarm(0);
	if (Verbose>5)
		fprintf(stderr, "ret cnt=%d %x %x\n", c, byt[0], byt[1]);
	if (c<1)
		return TIMEOUT;
	if (c==1)
		return (byt[0]&0377);
	else
		while (c)
			if (byt[--c] != CAN)
				return ERROR;
	return CAN;
}

purgeline()
{
#ifdef USG
	ioctl(iofd, TCFLSH, 0);
#else
	lseek(iofd, 0L, 2);
#endif
}

/* update CRC */
unsigned updcrc(c, crc)
register c;
register unsigned crc;
{
	register count;

	for (count=8; --count>=0;) {
		if (crc & 0x8000) {
			crc <<= 1;
			crc += (((c<<=1) & 0400)  !=  0);
			crc ^= 0x1021;
		}
		else {
			crc <<= 1;
			crc += (((c<<=1) & 0400)  !=  0);
		}
	}
	return crc;	
}

/* send 10 CAN's to try to get the other end to shut up */
canit()
{
	register n;
	for (n=10; --n>=0; )
		sendline(CAN);
}

#ifdef REGULUS
/*
 * copies count bytes from s to d
 * (No structure assignment in Regulus C compiler)
 */
movmem(s, d, count)
register char *s, *d;
register count;
{
	while (--count >= 0)
		*d++ = *s++;
}
#endif

/*VARARGS1*/
logent(a, b, c)
char *a, *b, *c;
{
	if(Verbose)
		fprintf(stderr, a, b, c);
}

/*
 * return 1 iff stdout and stderr are different devices
 *  indicating this program operating with a modem on a
 *  different line
 */
fromcu()
{
	struct stat a, b;
	fstat(1, &a); fstat(2, &b);
	return (a.st_rdev != b.st_rdev);
}

/*
 * substr(string, token) searches for token in string s
 * returns pointer to token within string if found, NULL otherwise
 */
char *
substr(s, t)
register char *s,*t;
{
	register char *ss,*tt;
	/* search for first char of token */
	for (ss=s; *s; s++)
		if (*s == *t)
			/* compare token with substring */
			for (ss=s,tt=t; ;) {
				if (*tt == 0)
					return s;
				if (*ss++ != *tt++)
					break;
			}
	return NULL;
}

SHAR_EOF
#	End of shell archive
exit 0
-- 
  Chuck Forsberg WA7KGX   ...!tektronix!reed!omen!caf   CIS:70715,131
Omen Technology Inc     17505-V NW Sauvie Island Road Portland OR 97231
Voice: 503-621-3406     Modem: 503-621-3746 (Hit CR's for speed detect)
Home of Professional-YAM, the most powerful COMM program for the IBM PC