/*
 *	B D T T C P . C
 *
 * BiDirectional Test TCP connection.  Makes a connection on port 5001
 * and transfers fabricated buffers or data copied from stdin.
 *
 * Usable on 4.2, 4.3, and 4.1a systems by defining one of
 * BSD42 BSD43 (BSD41a)
 * Machines using System V with BSD sockets should define SYSV.
 *
 * Modified for operation under 4.2BSD, 18 Dec 84
 *      T.C. Slattery, USNA
 * Minor improvements, Mike Muuss and Terry Slattery, 16-Oct-85.
 * Modified in 1989 at Silicon Graphics, Inc.
 *	catch SIGPIPE to be able to print stats when receiver has died 
 *	for tcp, don't look for sentinel during reads to allow small transfers
 *	increased default buffer size to 8K, nbuf to 2K to transfer 16MB
 *	moved default port to 5001, beyond IPPORT_USERRESERVED
 *	make sinkmode default because it is more popular, 
 *		-s now means don't sink/source 
 *	count number of read/write system calls to see effects of 
 *		blocking from full socket buffers
 *	for tcp, -D option turns off buffered writes (sets TCP_NODELAY sockopt)
 *	buffer alignment options, -A and -O
 *	print stats in a format that's a bit easier to use with grep & awk
 *	for SYSV, mimic BSD routines to use most of the existing timing code
 * Modified by Steve Miller of the University of Maryland, College Park
 *	-b sets the socket buffer size (SO_SNDBUF/SO_RCVBUF)
 * Modified Sept. 1989 at Silicon Graphics, Inc.
 *	restored -s sense at request of tcs@brl
 * Modified Oct. 1991 at Silicon Graphics, Inc.
 *	use getopt(3) for option processing, add -f and -T options.
 *	SGI IRIX 3.3 and 4.0 releases don't need #define SYSV.
 * Modified Jan. 1995 by Seth Robertson, SOS Corporation <seth@soscorp.com>
 *	Added BIDIRECTIONAL -cEFV
 *	Added SOCKS
 *	Added BRIMSTONE -aek (local hacks--encryption and SKID authentication)
 *	Added sos_* routines for better host and name lookup
 *	Removed udp (sorry!)
 *      Mostly a total rewrite
 * Modified April. 1995 by Seth Robertson, SOS Corporation <seth@soscorp.com>
 *	Removed functions duplicated in libsos (sorry)
 *	Ported to BSDI
 * Modified May 1995 by James Tanis, SOS Corporation <jtt@soscorp.com>
 *	Updated to latest libsos.  Encryption #ifdeffed for export.
 *	Keys read from /etc/bs.rmnt.conf or env BDTTCP_KEY_FILE
 *
 *
 * Distribution Status -
 *      Public Domain.  Distribution Unlimited.
 */
#ifndef lint
static char RCSid[] = "ttcp.c $Revision: 1.16 $";
#endif

/* #define BSD43 */
/* #define BSD42 */
/* #define BSD41a */
/* #define SYSV */	/* required on SGI IRIX releases before 3.3 */

#ifdef __svr4__
#define SYSV
#undef BSD43
#endif /* SVR4 */

#include "sos.h"
#if defined ( __sun__ ) && defined ( __svr4__ )
#define SOLARIS
#include <sys/rusage.h>
#include <sys/times.h> /* This might by a SYSV thing, I don't know */
#else
#include <sys/resource.h>
#endif

#if defined(SOCKS)
#define connect	Rconnect
#define getsockname	Rgetsockname
#define listen	Rlisten
#define accept	Raccept
#define rcmd	Rrcmd
#if defined(SHORTENED_RBIND)
#define bind	Rbind
#else
#define bind	LONG_BIND_NEEDS_PORTING
#endif
#endif
#if !defined(SOCKS) && defined(bind)
#define SOCKS
#endif /*SOCKS*/


#define VECLEN		10	/* Number queued bufs / connection */
#define TOTBUF		16	/* Total number of buffers to allocate */
#define DEFBUF		8192	/* Default buffer size */
#define ALIGN_LEN	16384	/* Default buffer alignment */
#define NUMSINK		2048	/* Default number bufs for sinkmode */
#define DEFPORT		5001	/* Default port number */


struct sockaddr_in sinme;
struct sockaddr_in sinhim;
struct sockaddr_in frominet;

int fromlen;			/* size for accept */
int fd = -1;			/* fd of network socket */

int buflen = DEFBUF;		/* default length of buffer */
int nbuf = NUMSINK;		/* number of buffers to send in sinkmode */
int veclen = VECLEN;		/* Vector length */
int totbuf = TOTBUF;		/* Total number of buffers */

caddr_t sinkbuf;		/* Buffer for sink mode only */

int bufoffset = 0;		/* align buffer to this */
int bufalign = ALIGN_LEN;	/* modulo this */

#ifdef SO_REUSEADDR
int options = SO_REUSEADDR;	/* socket options */
#else /*SO_REUSEADDR*/
int options = 0;		/* socket options */
#endif /*SO_REUSEADDR*/

short port = DEFPORT;		/* TCP port number */
char *host;			/* ptr to name of host */
char *prog;			/* program name */

int one = 1;                    /* for 4.3 BSD style setsockopt() */
int trans;			/* 0=receive, !0=transmit mode */
int sinkmode = 0;		/* 0=normal I/O, !0=sink/source mode */
int verbose = 0;		/* 0=print basic info, 1=print cpu rate, proc
				 * resource usage. */
int nodelay = 0;		/* set TCP_NODELAY socket option */
int b_flag = 0;			/* use mread() */
int sockbufsize = 0;		/* socket buffer size to use */
char fmt = 'K';			/* output format: k = kilobits, K = kilobytes,
				 *  m = megabits, M = megabytes, 
				 *  g = gigabits, G = gigabytes */
int touchdata = 0;		/* access data after reading */
int quiet = 0;			/* Quiet! */

int do_exec = 0;		/* Perform exec of command line */
int bi_pid = 0;			/* Bidirectional pid */
int bi_pgrp = 0;		/* Process group of ttcp set */
int bi_common_exit = 0;		/* Exit both streams when one dies */
int Server = 0;			/* Server mode */

extern int errno;
extern int optind;
extern char *optarg;

char Usage[] = "\
Usage: %s -t [-options] host [cmd args...] [ < in > out ]\n\
       %s -r [-options] %s [cmd args...] [ < in > out]\n\
\n\
	-t	Connect to remote host on startup\n\
	-r	Wait for remote host to connect to you\n\
\n\
Common options:\n\
	-l ##	length of bufs read from or written to network (default 8192)\n\
	-p ##	port number to send to or listen at (default 5001)\n\
	-s	-t: source a pattern to network\n\
		-r: sink (discard) all data from network\n\
	-A	align the start of buffers to this modulus (default 16384)\n\
	-E	Execute command following host with stdio directed via ttcp\n\
	-c	Exit when either I/O stream finishes (default requires both)\n\
	-F	Total number of buffers (-F * -l == memory usage) (default 16)\n\
	-V	Max length of queue for each writer (default 10)\n\
	-a	Encryption on/authentication on\n\
        -e #    Encryption set to arg\n\
        -k #    Authentication set to arg\n\
	-O	start buffers at this offset from the modulus (default 0)\n\
	-v	verbose: print more statistics\n\
	-q	quiet--print only error messages\n\

	-d	set SO_DEBUG socket option\n\
	-b ##	set socket buffer size (if supported)\n\
	-f X	format for rate: k,K = kilo{bit,byte}; m,M = mega; g,G = giga\n\
	-B	for -s, only output full blocks as specified by -l (for TAR)\n\
	-T	\"touch\": access each byte as it's read from the net\n\
	-D	don't buffer TCP writes (sets TCP_NODELAY socket option)\n\
	-n##	number of source bufs written to network (default 2048)\n\
\n\
Receive options:\n\
	-S	Server mode--fork off clients to handle individual connections\n\
";	

char stats[128];
unsigned long nbytes = 0;	/* bytes on net */
unsigned long numCalls;		/* # of I/O system calls */
double cput, realt;		/* user, real time (seconds) */

void err();
void mes();
int pattern();
void prep_timer();
double read_timer();
int Nread();
int Nwrite();
void delay();
int mread();
char *outfmt();
char *getfreebuf();
void sos_run_authentication();

int bs_on = 0;
int bs_enc_on = -1;
int bs_skid_on = -1;
char *key_file;

void
sigpipe()
{
}

void reapchild()
{
#if defined(SOLARIS)
        siginfo_t infop;
        int options = WNOHANG|WEXITED|WCONTINUED|WSTOPPED|WTRAPPED;

fprintf(stderr,"Hello\n");
        while (waitid(P_ALL,0,&infop,options) == 0) ;
fprintf(stderr,"Hello\n");

#else /*SOLARIS*/
# ifdef WNOHANG
        union wait status;

        while (wait3((int *)&status, WNOHANG, (struct rusage *) NULL) > 0)
                continue;
# else /*WNOHANG*/
        auto int status;

        while (wait((int *)&status) > 0)
                continue;
# endif /*WNOHANG*/
#endif /*SOLARIS*/
}



main(argc,argv)
int argc;
char **argv;
{
	unsigned long addr_tmp;
	int c;

	if (argc < 2) goto usage;

	key_file = SOS_ENV_GWD("BDTTCP_KEY_FILE", "/etc/bs.rmnt.conf");

	while ((c = getopt(argc, argv, "i:drstvBDTaEcqSF:V:e:k:b:f:l:n:p:A:O:")) != -1) {
	  switch (c) {

		case 'B':
			b_flag = 1;
			break;
		case 't':
			trans = 1;
			break;
		case 'r':
			trans = 0;
			break;
		case 'd':
			options |= SO_DEBUG;
			break;
		case 'D':
#ifdef TCP_NODELAY
			nodelay = 1;
#else
			fprintf(stderr, 
	"ttcp: -D option ignored: TCP_NODELAY socket option not supported\n");
#endif
			break;
		case 'n':
			nbuf = atoi(optarg);
			break;
		case 'l':
			buflen = atoi(optarg);
			break;
		case 's':
			sinkmode = !sinkmode;
			break;
		case 'p':
			port = sos_getsbyfoo(optarg);
			if (port < 0)
			  {
			      fprintf(stderr,"ttcp: Invalid port %s\n",optarg);
			      goto usage;
			  }
			
			break;
		case 'v':
			verbose = 1;
			break;
		case 'q':
			quiet = 1;
			break;
                case 'a':
                        bs_enc_on = 1;
                        bs_skid_on = 1;
                        bs_on = 1;
                        break;
                case 'e':
                        bs_on = 1;
                        bs_enc_on = atoi(optarg);
                        break;
                case 'k':
                        bs_on = 1;
                        bs_skid_on = atoi(optarg);
                        break;
                case 'E':
			do_exec = 1;
                        break;
                case 'S':
			Server = 1;
                        break;
                case 'c':
			bi_common_exit = 1;
                        break;
		case 'F':
			veclen = atoi(optarg);
			break;
		case 'V':
			totbuf = atoi(optarg);
			break;
		case 'A':
			bufalign = atoi(optarg);
			break;
		case 'O':
			bufoffset = atoi(optarg);
			break;
		case 'b':
#if defined(SO_SNDBUF) || defined(SO_RCVBUF)
			sockbufsize = atoi(optarg);
#else
			fprintf(stderr, 
"ttcp: -b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported\n");
#endif
			break;
		case 'f':
			fmt = *optarg;
			break;
		case 'T':
			touchdata = 1;
			break;
		case 'i':
			key_file=strdup(optarg);
			break;
		default:
			goto usage;
		}
	}

	if (veclen < 1 || totbuf < 1 || nbuf < 0 || buflen < 1)
	  goto usage;

	if (trans && Server)
	  goto usage;

#ifdef SOCKS
	if ((optind == argc) || ( do_exec && (optind+2 > argc)))
	  {
	    goto usage;
	  }
#else /*SOCKS*/
	if (trans)
	  {
	    if ((optind == argc) || ( do_exec && (optind+2 > argc)))
	      {
		goto usage;
	      }
	  }
	else
	  {
	    if ( do_exec && (optind+1 > argc))
	      {
		goto usage;
	      }
	  }
#endif /*SOCKS*/

	if(trans)  {
		/* xmitr */
		if (optind == argc)
			goto usage;
#ifdef SYSV
		memset((void *)&sinhim, sizeof(sinhim), 0);
#else
		bzero((char *)&sinhim, sizeof(sinhim));
#endif
		host = argv[optind++];
		sinhim.sin_family = AF_INET;
#ifdef OLDCODE
		sinhim.sin_addr.s_addr = sos_getabyfoo(host);
		if (sinhim.sin_addr.s_addr == -1)
		  err("bad hostname");
#else
		if (sos_getabyfoo(host, &sinhim.sin_addr) == -1)
		  err("bad hostname");
#endif
		sinhim.sin_port = htons(port);
		sinme.sin_port = 0;		/* free choice */
	} else {
		/* rcvr */
#ifdef SOCKS
		if (optind == argc)
			goto usage;
#ifdef SYSV
		memset((void *)&sinhim, sizeof(sinhim), 0);
#else
		bzero((char *)&sinhim, sizeof(sinhim));
#endif
		host = argv[optind++];
		sinhim.sin_family = AF_INET;
#ifdef OLDCODE
		sinhim.sin_addr.s_addr = sos_getabyfoo(host);
		if (sinhim.sin_addr.s_addr == -1)
		  err("bad hostname");
#else
		if (sos_getabyfoo(host, &sinhim.sin_addr) == -1)
		  err("bad hostname");
#endif
#endif /*SOCKS*/
		sinme.sin_port =  htons(port);
	}


	if (!quiet) {
	    if (trans) {
		fprintf(stderr,
			"ttcp-t: buflen=%d, nbuf=%d, align=%d/%d, port=%d",
			buflen, nbuf, bufalign, bufoffset, port);
		if (sockbufsize)
		  fprintf(stderr, ", sockbufsize=%d", sockbufsize);
		fprintf(stderr, "  tcp  -> %s\n", host);
	    } else {
		fprintf(stderr,
			"ttcp-r: buflen=%d, nbuf=%d, align=%d/%d, port=%d",
			buflen, nbuf, bufalign, bufoffset, port);
		if (sockbufsize)
		  fprintf(stderr, ", sockbufsize=%d", sockbufsize);
		fprintf(stderr, "  tcp\n");
	    }
	}

	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		err("socket");
	mes("socket");

	sinme.sin_family = AF_INET;

	if (!trans)
#ifdef SOCKS
		if (Rbind(fd, (struct sockaddr *)&sinme, sizeof(sinme),sinhim.sin_addr.s_addr) < 0)
#else /*SOCKS*/
		if (bind(fd, (struct sockaddr *)&sinme, sizeof(sinme)) < 0)
#endif /*SCOKS*/
			err("bind");

#if defined(SO_SNDBUF) || defined(SO_RCVBUF)
	if (sockbufsize) {
	    if (trans) {
		if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&sockbufsize,
		    sizeof sockbufsize) < 0)
			err("setsockopt: sndbuf");
		mes("sndbuf");
	    } else {
		if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize,
		    sizeof sockbufsize) < 0)
			err("setsockopt: rcvbuf");
		mes("rcvbuf");
	    }
	}
#endif

	signal(SIGPIPE, sigpipe);
	signal(SIGCHLD, reapchild);
	if (trans) {
	  /* We are the client if transmitting */
	  if (options)  {
#if defined(BSD42)
	    if( setsockopt(fd, SOL_SOCKET, options, 0, 0) < 0)
#else /* BSD43 */
            if( setsockopt(fd, SOL_SOCKET, options, (char *)&one, sizeof(one)) < 0)
#endif
	      err("setsockopt");
	  }
#ifdef TCP_NODELAY
	  if (nodelay) {
	    struct protoent *p;
	    p = getprotobyname("tcp");
	    if( p && setsockopt(fd, p->p_proto, TCP_NODELAY, 
				(char *)&one, sizeof(one)) < 0)
	      err("setsockopt: nodelay");
	    mes("nodelay");
	  }
#endif
	  if(connect(fd, (struct sockaddr *)&sinhim, sizeof(sinhim) ) < 0)
	    err("connect");
	  mes("connect");
	} else {
	  int serverfd = fd;
	  /* otherwise, we are the server and 
	   * should listen for the connections
	   */
	  listen(serverfd,2);

	  if(options)  {
#if defined(BSD42)
	    if( setsockopt(serverfd, SOL_SOCKET, options, 0, 0) < 0)
#else /* BSD43 */
	    if( setsockopt(serverfd, SOL_SOCKET, options, (char *)&one, sizeof(one)) < 0)
#endif
	      err("setsockopt");
	  }
	  while (1)
	    {
	      fromlen = sizeof(frominet);
	      memset((char *)&frominet, 0, fromlen);
	      if((fd=accept(serverfd, (struct sockaddr *)&frominet, &fromlen) ) < 0)
		{
		  if (errno == EINTR)
		    continue;	/* Probably just SIGCHLD */
		  err("accept");
		}
	      if (Server)
		{
		  switch (fork())
		    {
		    case -1:
		      err("fork");
		      break;
		    case 0:	/* Child */
		      break;	/* handle connection */
		    default:	/* Parent */
		      close(fd);
		      continue;	/* Accept some more */
		    }
		  break;
		}	
	      else
		{
		  break;	/* Handle connection */
		}
	    }
	  {
	    struct sockaddr_in peer;
	    int peerlen = sizeof(peer);
	    if (getpeername(fd, (struct sockaddr *) &peer, 
			    &peerlen) < 0) {
	      err("getpeername");
	    }
	    if (!quiet)
	      fprintf(stderr,"ttcp-r: accept from %s\n", 
		      inet_ntoa(peer.sin_addr));
	  }
	}

	if (sinkmode)
	  {
	    if ((sinkbuf = (caddr_t)malloc(buflen+bufalign)) == NULL)
	      {
		if ( (sinkbuf = (char *)malloc(buflen+bufalign)) == (char *)NULL)
		  err("malloc");
		if (bufalign != 0)
		  sinkbuf += (bufalign - ((int)sinkbuf % bufalign) + bufoffset) % bufalign;
	      }
	  }

        /*
         * Authenticate and run options
         */
        if (bs_on)
	  {
	    (void)sos_run_authentication(key_file,fd); 
	  }

	if (do_exec)
	  {
	    /* Have process groups set up correctly */
	    setsid();
#if defined(__bsdi__) || defined(__sgi__) || defined(__svr4__)
	    bi_pgrp = getpgrp();
#else
	    bi_pgrp = getpgrp(0);
#endif
	    (void)run_command(fd,optind,argv);
	  }

	prep_timer();
	errno = 0;
	if (sinkmode) {      
		register int cnt;
		if (trans)  {
			pattern( sinkbuf, buflen );
			while (nbuf-- && Nwrite(fd,sinkbuf,buflen) == buflen)
				nbytes+= buflen;
		} else {
		  while ((cnt=Nread(fd,sinkbuf,buflen)) > 0)  {
		    nbytes += cnt;
		  }
		}
	} else {
	  struct sos_bdr_fdpair relay[2], *prelay;
	  struct sos_bdr_auxinfo auxinfo;
	  int count;

	  auxinfo.veclen = veclen;
	  auxinfo.totbuf = totbuf;
	  auxinfo.buflen = buflen;
	  auxinfo.align = bufalign;
	  auxinfo.offset = bufoffset;
	  auxinfo.common_exit = bi_common_exit;
	  auxinfo.fullread = b_flag;

	  relay[0].rinfo.fd = 0;
	  relay[0].rinfo.iofun = read;
	  relay[0].winfo.fd = fd;
	  relay[0].winfo.iofun = Nwrite;
	  relay[0].curRbuf.iov_base = NULL;
	  relay[0].curRbuf.iov_len = 0;
	  relay[0].shutdown = 0;
	  relay[0].nbytes = 0;
	  relay[0].filter = NULL;
	  relay[0].bd.cur_write_hand = 0;
	  relay[0].bd.cur_read_hand = -1;
	  if (!(relay[0].bd.curWbuf = (struct iovec *)malloc(sizeof(struct iovec)*auxinfo.veclen)))
	    err("malloc");
	  if (!(relay[0].bd.fullbuf = (struct iovec *)malloc(sizeof(struct iovec)*auxinfo.veclen)))
	    err("malloc");

	  relay[1].rinfo.fd = fd;
	  relay[1].rinfo.iofun = Nread;
	  relay[1].winfo.fd = 1;
	  relay[1].winfo.iofun = 
	      (int (*) (int, void *, __SIZE_TYPE__)) write;
	  relay[1].curRbuf.iov_base = NULL;
	  relay[1].curRbuf.iov_len = 0;
	  relay[1].bd.cur_write_hand = 0;
	  relay[1].bd.cur_read_hand = -1;
	  relay[1].shutdown = 0;
	  relay[1].nbytes = 0;
	  relay[1].filter = NULL;
	  if (!(relay[1].bd.curWbuf = (struct iovec *)malloc(sizeof(struct iovec)*auxinfo.veclen)))
	    err("malloc");
	  if (!(relay[1].bd.fullbuf = (struct iovec *)malloc(sizeof(struct iovec)*auxinfo.veclen)))
	    err("malloc");

	  prelay = relay;
	  count = 2;
	  if (sos_bdrelay(&prelay,&count,&auxinfo) < 0)
	    err("relay");

	  nbytes = relay[0].nbytes + relay[1].nbytes;
	}

	(void)read_timer(stats,sizeof(stats));

	if( cput <= 0.0 )  cput = 0.001;
	if( realt <= 0.0 )  realt = 0.001;

	if (!quiet)
	  {
	      fprintf(stderr,
		      "ttcp%s: %ld bytes in %.2f real seconds = %s/sec +++\n",
		      trans?"-t":"-r",
		      nbytes, realt, outfmt(((double)nbytes)/realt));
	      if (verbose) {
		  fprintf(stderr,
			  "ttcp%s: %ld bytes in %.2f CPU seconds = %s/cpu sec\n",
			  trans?"-t":"-r",
			  nbytes, cput, outfmt(((double)nbytes)/cput));
	      }
	      fprintf(stderr,
		      "ttcp%s: %d I/O calls, msec/call = %.2f, calls/sec = %.2f\n",
		      trans?"-t":"-r",
		      numCalls,
		      1024.0 * realt/((double)numCalls),
		      ((double)numCalls)/realt);
	      fprintf(stderr,"ttcp%s: %s\n", trans?"-t":"-r", stats);
	  }

	exit(0);

usage:
	{
	  char *host = "";
#ifdef SOCKS
	  if (!trans)
	    host = "host ";
#endif /*SOCKS*/

	  fprintf(stderr,Usage,
		  argv[0],
		  argv[0],
		  host  );
	}
	exit(1);
}

void
err(s)
char *s;
{
	fprintf(stderr,"ttcp%s: ", trans?"-t":"-r");
	perror(s);
	fprintf(stderr,"errno=%d\n",errno);
	if (fd >= 0)
	  shutdown(fd,trans?1:0);
	exit(1);
}

void
mes(s)
char *s;
{
    if (!quiet)
	fprintf(stderr,"ttcp%s: %s\n", trans?"-t":"-r", s);
}

pattern( cp, cnt )
register char *cp;
register int cnt;
{
	register char c;
	c = 0;
	while( cnt-- > 0 )  {
		while( !isprint((c&0x7F)) )  c++;
		*cp++ = (c++&0x7F);
	}
}

char *
outfmt(b)
double b;
{
    static char obuf[50];
    switch (fmt) {
	case 'G':
	    sprintf(obuf, "%.2f GB", b / 1024.0 / 1024.0 / 1024.0);
	    break;
	default:
	case 'K':
	    sprintf(obuf, "%.2f KB", b / 1024.0);
	    break;
	case 'M':
	    sprintf(obuf, "%.2f MB", b / 1024.0 / 1024.0);
	    break;
	case 'g':
	    sprintf(obuf, "%.2f Gbit", b * 8.0 / 1024.0 / 1024.0 / 1024.0);
	    break;
	case 'k':
	    sprintf(obuf, "%.2f Kbit", b * 8.0 / 1024.0);
	    break;
	case 'm':
	    sprintf(obuf, "%.2f Mbit", b * 8.0 / 1024.0 / 1024.0);
	    break;
    }
    return obuf;
}

static struct	timeval time0;	/* Time at which timing started */
static struct	rusage ru0;	/* Resource utilization at the start */

static void prusage();
static void tvadd();
static void tvsub();
static void psecs();

#if defined(SYSV)
/*ARGSUSED*/
static
getrusage(ignored, ru)
    int ignored;
    register struct rusage *ru;
{
    struct tms buf;

    times(&buf);

    /* Assumption: HZ <= 2147 (LONG_MAX/1000000) */
    ru->ru_stime.tv_sec  = buf.tms_stime / HZ;

#ifdef SOLARIS
    ru->ru_stime.tv_nsec = ((buf.tms_stime % HZ) * 1000000) / HZ;
#else 
    ru->ru_stime.tv_usec = ((buf.tms_stime % HZ) * 1000000) / HZ;
#endif 
    ru->ru_utime.tv_sec  = buf.tms_utime / HZ;


#ifdef SOLARIS
    ru->ru_utime.tv_nsec = ((buf.tms_utime % HZ) * 1000000) / HZ;
#else /* SOLARIS */
    ru->ru_utime.tv_usec = ((buf.tms_utime % HZ) * 1000000) / HZ;
#endif /* SOLARIS */
}

/*ARGSUSED*/
static 
gettimeofday(tp, zp)
    struct timeval *tp;
    struct timezone *zp;
{
    tp->tv_sec = time(0);
    tp->tv_usec = 0;
}
#endif /* SYSV */

/*
 *			P R E P _ T I M E R
 */
void
prep_timer()
{
	gettimeofday(&time0, (struct timezone *)0);
	getrusage(RUSAGE_SELF, &ru0);
}

/*
 *			R E A D _ T I M E R
 * 
 */
double
read_timer(str,len)
char *str;
{
	struct timeval timedol;
	struct rusage ru1;
	struct timeval td;
	struct timeval tend, tstart;
	char line[132];

	getrusage(RUSAGE_SELF, &ru1);
	gettimeofday(&timedol, (struct timezone *)0);
	prusage(&ru0, &ru1, &timedol, &time0, line);
	(void)strncpy( str, line, len );

	/* Get real time */
	tvsub( &td, &timedol, &time0 );
	realt = td.tv_sec + ((double)td.tv_usec) / 1000000;

	/* Get CPU time (user+sys) */
	tvadd( &tend, &ru1.ru_utime, &ru1.ru_stime );
	tvadd( &tstart, &ru0.ru_utime, &ru0.ru_stime );
	tvsub( &td, &tend, &tstart );
	cput = td.tv_sec + ((double)td.tv_usec) / 1000000;
	if( cput < 0.00001 )  cput = 0.00001;
	return( cput );
}

static void
prusage(r0, r1, e, b, outp)
	register struct rusage *r0, *r1;
	struct timeval *e, *b;
	char *outp;
{
	struct timeval tdiff;
	register time_t t;
	register char *cp;
	register int i;
	int ms;

	t = (r1->ru_utime.tv_sec-r0->ru_utime.tv_sec)*100+
#ifdef SOLARIS
	    (r1->ru_utime.tv_nsec-r0->ru_utime.tv_nsec)/10000+
#else /* SOLARIS */
	    (r1->ru_utime.tv_usec-r0->ru_utime.tv_usec)/10000+
#endif /* SOLARIS */

	    (r1->ru_stime.tv_sec-r0->ru_stime.tv_sec)*100+

#ifdef SOLARIS
	      (r1->ru_stime.tv_nsec-r0->ru_stime.tv_nsec)/10000;
#else /* SOLARIS */
	    (r1->ru_stime.tv_usec-r0->ru_stime.tv_usec)/10000;
#endif /* SOLARIS */
	ms =  (e->tv_sec-b->tv_sec)*100 + (e->tv_usec-b->tv_usec)/10000;

#define END(x)	{while(*x) x++;}
#if defined(SYSV)
	cp = "%Uuser %Ssys %Ereal %P";
#else
#if defined(sgi)		/* IRIX 3.3 will show 0 for %M,%F,%R,%C */
	cp = "%Uuser %Ssys %Ereal %P %Mmaxrss %F+%Rpf %Ccsw";
#else
	cp = "%Uuser %Ssys %Ereal %P %Xi+%Dd %Mmaxrss %F+%Rpf %Ccsw";
#endif
#endif
	for (; *cp; cp++)  {
		if (*cp != '%')
			*outp++ = *cp;
		else if (cp[1]) switch(*++cp) {

		case 'U':
			tvsub(&tdiff, &r1->ru_utime, &r0->ru_utime);
			sprintf(outp,"%d.%01d", tdiff.tv_sec, tdiff.tv_usec/100000);
			END(outp);
			break;

		case 'S':
			tvsub(&tdiff, &r1->ru_stime, &r0->ru_stime);
			sprintf(outp,"%d.%01d", tdiff.tv_sec, tdiff.tv_usec/100000);
			END(outp);
			break;

		case 'E':
			psecs(ms / 100, outp);
			END(outp);
			break;

		case 'P':
			sprintf(outp,"%d%%", (int) (t*100 / ((ms ? ms : 1))));
			END(outp);
			break;

#if !defined(SYSV)
		case 'W':
			i = r1->ru_nswap - r0->ru_nswap;
			sprintf(outp,"%d", i);
			END(outp);
			break;

		case 'X':
			sprintf(outp,"%d", t == 0 ? 0 : (r1->ru_ixrss-r0->ru_ixrss)/t);
			END(outp);
			break;

		case 'D':
			sprintf(outp,"%d", t == 0 ? 0 :
			    (r1->ru_idrss+r1->ru_isrss-(r0->ru_idrss+r0->ru_isrss))/t);
			END(outp);
			break;

		case 'K':
			sprintf(outp,"%d", t == 0 ? 0 :
			    ((r1->ru_ixrss+r1->ru_isrss+r1->ru_idrss) -
			    (r0->ru_ixrss+r0->ru_idrss+r0->ru_isrss))/t);
			END(outp);
			break;

		case 'M':
			sprintf(outp,"%d", r1->ru_maxrss/2);
			END(outp);
			break;

		case 'F':
			sprintf(outp,"%d", r1->ru_majflt-r0->ru_majflt);
			END(outp);
			break;

		case 'R':
			sprintf(outp,"%d", r1->ru_minflt-r0->ru_minflt);
			END(outp);
			break;

		case 'I':
			sprintf(outp,"%d", r1->ru_inblock-r0->ru_inblock);
			END(outp);
			break;

		case 'O':
			sprintf(outp,"%d", r1->ru_oublock-r0->ru_oublock);
			END(outp);
			break;
		case 'C':
			sprintf(outp,"%d+%d", r1->ru_nvcsw-r0->ru_nvcsw,
				r1->ru_nivcsw-r0->ru_nivcsw );
			END(outp);
			break;
			    
#endif /* !SYSV */
		}
	}
	*outp = '\0';
}

static void
tvadd(tsum, t0, t1)
	struct timeval *tsum, *t0, *t1;
{

	tsum->tv_sec = t0->tv_sec + t1->tv_sec;
	tsum->tv_usec = t0->tv_usec + t1->tv_usec;
	if (tsum->tv_usec > 1000000)
		tsum->tv_sec++, tsum->tv_usec -= 1000000;
}

static void
tvsub(tdiff, t1, t0)
	struct timeval *tdiff, *t1, *t0;
{

	tdiff->tv_sec = t1->tv_sec - t0->tv_sec;
	tdiff->tv_usec = t1->tv_usec - t0->tv_usec;
	if (tdiff->tv_usec < 0)
		tdiff->tv_sec--, tdiff->tv_usec += 1000000;
}

static void
psecs(l,cp)
long l;
register char *cp;
{
	register int i;

	i = l / 3600;
	if (i) {
		sprintf(cp,"%d:", i);
		END(cp);
		i = l % 3600;
		sprintf(cp,"%d%d", (i/60) / 10, (i/60) % 10);
		END(cp);
	} else {
		i = l;
		sprintf(cp,"%d", i / 60);
		END(cp);
	}
	i %= 60;
	*cp++ = ':';
	sprintf(cp,"%d%d", i / 10, i % 10);
}

/*
 *			N R E A D
 */
Nread( fd, buf, count )
int fd;
void *buf;
int count;
{
	struct sockaddr_in from;
	int len = sizeof(from);
	register int cnt;
	if( sinkmode && b_flag )
	  cnt = mread( fd, buf, count );	/* fill buf */
	else {
	  cnt = sosRawRead( fd, buf, count );
	  numCalls++;
	}
	if (touchdata && cnt > 0) {
	  register int c = cnt, sum;
	  register char *b = buf;
	  while (c--)
	    sum += *b++;
	}
	return(cnt);
}

/*
 *			N W R I T E
 */
Nwrite( fd, buf, count )
int fd;
void *buf;
int count;
{
	register int cnt;

	cnt = sosRawWrite( fd, buf, count );
	numCalls++;
	return(cnt);
}

void
delay(us)
{
	struct timeval tv;

	tv.tv_sec = 0;
	tv.tv_usec = us;
	(void)select( 1, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
}

/*
 *			M R E A D
 *
 * This function performs the function of a read(II) but will
 * call read(II) multiple times in order to get the requested
 * number of characters.  This can be necessary because
 * network connections don't deliver data with the same
 * grouping as it is written with.  Written by Robert S. Miles, BRL.
 */
int
mread(fd, bufp, n)
int fd;
register char	*bufp;
unsigned	n;
{
	register unsigned	count = 0;
	register int		nread;

	do {
		nread = sosRawRead(fd, bufp, n-count);
		numCalls++;
		if(nread < 0)  {
			perror("ttcp_mread");
			return(-1);
		}
		if(nread == 0)
			return((int)count);
		count += (unsigned)nread;
		bufp += nread;
	 } while(count < n);

	return((int)count);
}

/*
 * Run the command specified on the command line with the stdio
 * directed to the network.
 *
 * bdttcp -E -r /bin/sh
 * bdttcp -t localhost
 *
 * The above would give you a remote shell, sort of
 */
run_command(int fd, int optind, char *optarg[])
{
  int sv[2];
  int vs[2];

  if (pipe(sv) < 0)
    {
      perror("pipe");
      exit(3);
    }

  if (pipe(vs) < 0)
    {
      perror("pipe");
      exit(3);
    }

  switch(fork())
    {
    case -1:
      perror("fork");
      exit(3);
    case 0:			/* child */
      dup2(sv[0],0);
      dup2(vs[1],1);
      dup2(vs[1],2);
      close(sv[1]);
      close(vs[0]);
      execv(optarg[optind],optarg+optind);
      perror("execv");
      exit(3);

    default:			/* parent */
      dup2(vs[0],0);
      dup2(sv[1],1);
      close(vs[1]);
      close(sv[0]);
    }
  return(0);
}

#define ENCRYPT "encryption"
#define AUTHENT "authentication"
#define ENCRYPTKEY "encryptkey"
#define AUTHKEY "authkey"

void
sos_run_authentication(char *config_file, int fd)
{
  sos_config_t remote_config;

  if ( !(remote_config = sos_config_read(config_file,0)) ) 
    {
      fprintf(stderr,"Could not access/read config file. Exiting\n");
      exit (1);
    }
    
  /*
   * Command line over-rides
   *
   * XXX cannot set bs options to MUST_NOT or PREFER via command line, usually.
   */
  
  if (bs_enc_on == 1 )
    sos_opt_set_value(ENCRYPT, SOS_OPT_LPREF, SOS_OPT_MUST);
  if (bs_enc_on == 0 )
    sos_opt_set_value(ENCRYPT, SOS_OPT_LPREF, SOS_OPT_MUST_NOT);

  if ( bs_skid_on == 1 )
    sos_opt_set_value(AUTHENT, SOS_OPT_LPREF, SOS_OPT_MUST);
  if ( bs_skid_on == 0 )
    sos_opt_set_value(AUTHENT, SOS_OPT_LPREF, SOS_OPT_MUST_NOT);


  if ( sos_negotiate_options(fd, sosRawRead, fd, sosRawWrite) < 0)
    {
      fprintf(stderr,"Options negotiation failed with peer\n");
      exit(1);
      
    }

#ifdef EXPORT_VERSION
  if (sos_opt_get_state(ENCRYPT) == SOS_OPT_ON &&
      sos_encrypt_init(sos_config_getnext(remote_config, ENCRYPTKEY, 
					  SOS_CONFIG_NULL,
					  SOS_CONFIG_NULL),
		       fd) < 0)
  
    {
      fprintf(stderr,"Encryption initialization failed with peer\n");
      exit(1);
    }
#endif /*EXPORT_VERSION*/

  if (sos_opt_get_state(AUTHENT) == SOS_OPT_ON &&
      sos_skid(fd,sos_config_getnext(remote_config, AUTHKEY, 
				     SOS_CONFIG_NULL,
				     SOS_CONFIG_NULL),
	       sosBIOread, sosBIOwrite) != 1 )
    {
      fprintf(stderr,"SKID authentication failed with peer\n");
      exit(1);
    }
  
}
