[net.sources] X/YMODEM *nix file transfer programs

caf@omen.UUCP (Chuck Forsberg WA7KGX) (01/27/86)

In response to numerous requests, here is are the latest versions of
the Unix/Xenix/Vemnix/Coherent/Regulus rb and sb programs.  The man
pages have been extensively revised since their last posting.

Rb and sb support XMODEM and YMODEM protocol text and binary file transfers
to (rb) and from (sb) Unix systems.  YMODEM supports batch transfers,
1k packets with YMODEM programs such as YAM, IMP, MEX, and others.  Sb supports
YMODEM-g streaming protocol for even greater efficiency downloading
from Unix to Pro-YAM, twice as fast as XMODEM at 9600 bps.

Ready to print versions of the manual pages are included with the VMS
sources being posted at the same time.

#	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: Mon Jan 27 01:38:55 1986
echo shar: extracting rb.1 '(5320 characters)'
cat << \SHAR_EOF > rb.1
'\" Revision Level 
'\" Last Delta     01-26-86
.TH RB 1 OMEN
.SH NAME
rb \- X/YMODEM batch file receive
.SH SYNOPSIS
.B rb
[
.B \-1bquv
]
.PP
.B rb
[
.B \-1bcquv
]
.I file
.PP
.B [-][v]rbCOMMAND
.SH DESCRIPTION
.B Rb
uses the XMODEM and YMODEM error correcting protocols to receive
files over a serial port from a variety of programs running under
PC-DOS, CP/M, *nix, and other operating systems.

The first form of
.B rb
(Receive Batch)
receives files with YMODEM batch protocol.
Rb accepts either standard 128 byte sectors or
1024 byte sectors
(YAM
.B k
option).
The user should determine experimentally
the conditions under which use of 1k blocks
actually improves throughput without causing
problems.

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 packet 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 (most significant)
bit is set, that file will be received in binary mode anyway.
Otherwise,
if the raw pathname ends in .MSG, or .TXT, an existing file will
be appended to rather than replaced.

If extended file information (file length, etc.)
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 no extended file information is received,
slashes in the pathname are changed to underscore,
and 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.

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.

The second form of
.B rb
receives a single
.I file
with XMODEM protocol.
The user must supply the file name to both sending and receiving programs.

In the third form,
.B rb
is invoked as
.B rbCOMMAND
(with an optional leading \- as generated by login(1)).
For each received file,
rb will pipe the file to ``COMMAND filename''
where filename is the name of the transmitted file
with the file contents as standard input.

The file transfer is completed when COMMAND exits with 0 status.
A non zero exit status terminates the transfer.

A typical use for this form is
.I rbrmail
which calls rmail(1)
to post mail to the user specified by the transmitted file name.
For example, sending the file "caf" from a PC-DOS system to
.I rbrmail
on a Unix system
would result in the contents of the DOS file "caf" being mailed to user "caf".

On some
.SM Unix
systems, the login directory must contain a link to
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:
.ce
rbrmail::5:1::/bin:/usr/local/rbrmail
If the SHELL environment variable includes
.I "rsh"
or
.I "rksh"
(restricted shell),
rb will not accept absolute pathnames
or references to a parent directory,
will not modify an existing file, and
removes any files received in error.

.PP
The meanings of the available options are:
.PP
.PD 0
.TP
.B 1
Use file descriptor 1 for ioctls and reads (Unix only).
By default, file descriptor 0 is used.
This option allows
.B rb
to be used with the
.I cu
~$
command.
.TP
.B b
Transfer all files in binary
(tell it like it is)
mode.
This option disables file append.
.TP
.B c
Request 16 bit CRC
(single file transfers default to 8 bit 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
.ne 6
(
.SM Unix
command)
.RS
$
.I rb
.br
rb: ready C
.br
.RE
(Pro-YAM command)
.RS
.I <ALT-2>
.br
YAM Command:
.I "sb *.h *.c"
.br
.RE
.SH SEE ALSO
YMODEM.DOC,
IMP(CP/M),
cu(1),
Professional-YAM manual,
sb(omen),
usq(omen),
undos(omen)

Compile time options required
for various operating systems are described in the
rbsb.c source file.
.SH BUGS
Pathnames are restricted to 127 characters.
In XMODEM single file mode, the pathname given on the command line
is still processed as described above.
The CR/LF to NL translation merely deletes CR\'s;
undos(omen) performs a more intelligent translation.
.SH "VMS VERSION"
Some of the #includes with file names enclosed with angle brackets <>
may need to have the angle brackets changed to "", or vice versa.

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 sometimes loses incoming characters, resulting in retries
and degradation of throughput.

The VMS C standard i/o package and RMS sometimes interact to modify
file contents unexpectedly.

The VMS version does not support invocation as
.B rbCOMMAND .
SHAR_EOF
echo shar: extracting rb.c '(17620 characters)'
cat << \SHAR_EOF > rb.c
#define VERSION "2.17 12-07-85"
#define PUBDIR "/usr/spool/uucppublic"

/*% cc -DUSG -DNFGVMIN -O -K % -o rb
 *
 * rb.c By Chuck Forsberg
 *
 *  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!).
 *
 * A program for Unix which can receive
 *  files from computers running YAM or MODEM.
 *  rb uses Unix System III buffered input to reduce CPU time.
 *  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
 */
#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;
int Restricted=0;	/* restricted; no /.. or ../ in filenames */

#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;
	char *getenv();
	int exitcode;

	setbuf(stderr, NULL);
	if ((cp=getenv("SHELL")) && (substr(cp, "rsh") || substr(cp, "rsh")))
		Restricted=TRUE;

	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);
		checkpath(Pathname);
		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);
	if (Restricted) {
		unlink(Pathname);
		fprintf(stderr, "\r\nrb: %s removed.\r\n", Pathname);
	}
	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)) {
					canit(); return ERROR;
				}
				sendline(ACK); return OK;
			}
			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 or DOS 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 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);
		}
		checkpath(name);
		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;
}

checkpath(name)
char *name;
{
	if (Restricted) {
		if (fopen(name, "r") != NULL) {
			canit();
			fprintf(stderr, "\r\nrb: %s exists\n", name);
			bibi();
		}
		/* restrict pathnames to current tree or uucppublic */
		if ( substr(name, "../")
		 || (name[0]== '/' && strncmp(name, PUBDIR, strlen(PUBDIR))) ) {
			canit();
			fprintf(stderr,"\r\nrb:\tSecurity Violation\r\n");
			bibi();
		}
	}
}

SHAR_EOF
echo shar: extracting rbsb.c '(4166 characters)'
cat << \SHAR_EOF > rbsb.c
/* -rev 09-13-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 */

#ifdef XCLUDE
		tty.c_lflag = XCLUDE | ISIG;
#else
		tty.c_lflag = ISIG;
#endif

		tty.c_cc[VINTR] = 030;	/* Interrupt on CANCEL */
		tty.c_cc[VMIN] = 1;

		(void) ioctl(iofd, TCSETAW, &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);
#ifdef XCLUDE
		tty.c_lflag |= XCLUDE;
#endif

		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, TCSETAW, &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
echo shar: extracting sb.1 '(3679 characters)'
cat << \SHAR_EOF > sb.1
'\" Revision Level 
'\" Last Delta     12-07-85
.TH SB 1 OMEN
.SH NAME
sb \- X/YMODEM Batch file Send
.SH SYNOPSIS
.B sb
[
.B \-1dfkquv
]
.I file ...
.br
.B "sb -X"
[
.B \-1kquv
]
.I file
.SH DESCRIPTION
.B Sb
uses the XMODEM and YMODEM error correcting protocols to send
files over a serial port to a variety of programs running under
PC-DOS, CP/M, *nix, and other operating systems.

The first form of
.B sb
sends one or more files with YMODEM batch protocol.
Normally, only the file name part of the pathname is transmitted.
On
.SM 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.

The second form of
.B sb
uses the
.B -X
flag to send a single
.I file
with XMODEM protocol.
The user must supply the file name to both sending and receiving programs.

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 variable contains the
string
.I "rsh"
or
.I "rksh"
(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.

Unix
.B sb
supports YMODEM-g
with "cbreak" tty mode, XON/XOFF flow control,
and the interrupt character set to CAN.
YMODEM-g
(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 1
Use file descriptor 1 for ioctls and reads (Unix only).
By default, file descriptor 0 is used.
This option allows
.B sb
to be used with the
.I cu
^$
command.
.TP
.B X
(XMODEM protocol)
Send a single file without the filename packet.
.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.
1024 byte packets speed file transfers at high bit rates.
.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/sblog .
More v's generate more output.
.PD
.SH EXAMPLES
.ne 7
(Unix command)
.RS
$
.I "sb -k *.c"
.br
.RE
(Pro-YAM command)
.RS
.I "<F3>"
.br
.RE
(8-bit YAM Commands)
.br
.RS
.I "^E"
.br
>>>c:
.I "rt"
.br
.RE
.SH SEE ALSO
rb(omen),
YMODEM.DOC,
Professional-YAM manual,
IMP(CP/M),
cu(1),
sq(omen),
todos(omen),
tocpm(omen),
tomac(omen)

Compile time options required for various operating systems are described in
the rbsb.c source file.
.SH BUGS
On VMS,
some of the #includes with file names enclosed with angle brackets <>
may need to have the angle brackets removed, or vice versa.

The VMS version does not transmit the file date.

The VMS version does not recognize YMODEM-g.

The VMS version calculates the file length by reading the file
and counting the bytes.

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

The VMS C standard i/o package and RMS sometimes interact to modify
file contents unexpectedly.
SHAR_EOF
echo shar: extracting sb.c '(14026 characters)'
cat << \SHAR_EOF > sb.c
#define VERSION "sb 2.26 01-26-86"
#define PUBDIR "/usr/spool/uucppublic"

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

 * sb.c By Chuck Forsberg
 *
 *  USG UNIX (3.0) ioctl conventions courtesy  Jeff Martin
 * 	cc -O -DV7  sb.c -o sb		Unix version 7, 2.8 - 4.3 BSD
 *	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.		   *******
 *
 * A small program for Unix to send 1 or more files YMODEM Batch protocol.
 *  Supports the CRC option or regular checksum.
 *  Exit status is 0 if all transfers completed successfully,
 *  1 for 1 or more unreadable files or'd with 200 for incomplete file xfer.
 *
 *  Sb accepts -k option for 1kb record length.
 *
 *  Sb uses buffered i/o to reduce the CPU time compared to UMODEM.
 */

#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 RETRYMAX 10
#define SECSIZ 128	/* cp/m's Magic Number record size */
#define KSIZE 1024

char Lastrx;
char Crcflg;
int Wcsmask=0377;
int Verbose=0;
int Modem=0;		/* MODEM - don't send pathnames */
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") || substr(cp, "rsh")))
		Restricted=TRUE;

	npats=0;
	if (argc<2)
		usage();
#ifndef REGULUS
	setbuf(stdout, xXbuf);		
#endif
	while (--argc) {
		cp = *++argv;
		if (*cp++ == '-' && *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;
				case 'X':
					++Modem; break;
				default:
					usage();
				}
			}
		}
		else if ( !npats && argc>0) {
			if (argv[0][0]) {
				npats=argc;
				patts=argv;
				if ( !strcmp(*patts, "-"))
					iofd = 1;
			}
		}
	}
	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);
	}
	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++);
		}
	}
	if ( !Modem)
		printf("\r\n\bSending in Batch Mode\r\n");
	fflush(stdout);

	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 ( !strcmp(oname, "-")) {
		sprintf(name, "s%d.sb", getpid());
		in = stdin;
	}
	else 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;

	if (Modem)
		return OK;
	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;
	if (in == stdin)
		strcpy(p, "1999999999");
#ifndef REGULUS		/* This doesn't seem to work on Regulus */
	else 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 (txbuf[125])
		blklen=KSIZE;
	else {		/* A little goodie for IMP/KMD */
		txbuf[127] = f.st_size >>7;
		txbuf[126] = f.st_size >>15;
	}
	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;
			blklen=KSIZE;
		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 != WANTG && firstch!=TIMEOUT && firstch!=CAN)
		;
	if (firstch==CAN) {
		logent("Receiver CANcelled\n");
		return ERROR;
	}
	if (firstch==WANTCRC)
		Crcflg=TRUE;
	if (firstch==WANTG)
		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, 1)) != 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;
	static lfseen=0;

	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)
 *  Only looks for one if Optiong, which signifies cbreak, not raw input
 *
 * timeout is in tenths of seconds
 */
readock(timeout, count)
{
	register int c;
	static char byt[5];

	if (Optiong)
		count = 1;	/* Special hack for cbreak */

	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);
		byt[1] = 0;
	}
	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;
}

usage()
{
	fprintf(stderr,"%s by Chuck Forsberg\n", VERSION);
	fprintf(stderr,"Usage: sb [-17dfkquvX] [-] file ...\n");
	fprintf(stderr,"	1 Use stdout for all modem i/o\n");
	fprintf(stderr,"	d Change '.' to '/' in pathnames\n");
	fprintf(stderr,"	f Send full pathname\n");
	fprintf(stderr,"	k Send 1024 byte packets\n");
	fprintf(stderr,"	q Quiet (no progress reports)\n");
	fprintf(stderr,"	u Unlink file after transmission\n");
	fprintf(stderr,"	v Verbose - give more information\n");
	fprintf(stderr,"	X XMODEM protocol - send no pathnames\n");
	fprintf(stderr,"- as pathname sends standard input, filename=sPID.sb, requires -1 flag\n");
	exit(1);
}
SHAR_EOF
#	End of shell archive
exit 0
-- 
   Chuck Forsberg WA7KGX  ...!tektronix!reed!omen!caf   CIS:70715,131
   Author of Professional-YAM communications Tools for PCDOS and Unix
 Omen Technology Inc     17505-V NW Sauvie Island Road Portland OR 97231
Voice: 503-621-3406 TeleGodzilla: 621-3746 300/1200 L.sys entry for omen:
omen Any ACU 1200 1-503-621-3746 se:--se: link ord: Giznoid in:--in: uucp