#ifndef	lint
static char sccsid[] = "@(#)server_rpc.c 1.9 88/12/21";
#endif	/*lint*/

#include "cbratp.h"
#include "romfs.h"
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/file.h>

#define WIRETAPPORT	9473	/* Arbitrary 'WIRE' port number */

extern int vsdev;
extern int errno;
extern char *host;

fd_set	non_blocking_fds;
fd_set	stopped_fds;
fd_set	lseek_fds;

#define MAXHOSTNAME 80

tcp_init(inited)
int inited;
{
#ifdef WIRETAP
    return (iconnect(host, WIRETAPPORT));
#endif WIRETAP
#ifdef HELPER
    char   myname[MAXHOSTNAME+1];
    static int    s;
    u_short portnum = 2048;
    struct sockaddr_in sa;
    struct hostent *hp;
    struct servent *sp;

    if (inited) 
	return(wait_for_connection(s));

    bzero(&sa,sizeof(struct sockaddr_in));      /* clear our address */
    gethostname(myname,MAXHOSTNAME);            /* who are we? */
    hp= gethostbyname(myname);                  /* get our address info */
    if (hp == NULL)                             /* we don't exist !? */
        return(-1);
    sa.sin_family= hp->h_addrtype;              /* this is our host address */
    sa.sin_port= htons(WIRETAPPORT); 		/* this is our port number */
    if ((s= socket(AF_INET,SOCK_STREAM,0)) < 0) /* create socket */
        return(-1);
    if (bind(s,&sa,sizeof sa,0) < 0) {
        close(s);
        return(-1);                               /* bind address to socket */
    }
    listen(s, 1);                               /* max # of queued connects */
    return(wait_for_connection(s));
}

int wait_for_connection(s)
int s;
{
    fd_set readfd;
    int t;

    FD_ZERO(&readfd);
    FD_SET(s, &readfd);

#ifdef DEBUG
    printf("Waiting for a connection\n");
#endif DEBUG

    while (1) {
	select(s+1, &readfd, (fd_set *)0, (fd_set *)0, NULL);
	if ((t = get_connection(s)) < 0) {
	    if (errno == EINTR)
		continue;
	    perror("accept");
	    exit(1);
	}
	return(t);
    }
}

int get_connection(s)
int s;                    /* socket created with establish() */
{
    struct sockaddr_in isa; /* address of socket */
    int i;                  /* size of address */
    int t;                  /* socket of connection */

    i = sizeof(isa);                   /* find socket's address */
    getsockname(s,&isa,&i);            /* for accept() */

    if ((t = accept(s,&isa,&i)) < 0)   /* accept connection if there is one */
        return(-1);
    return(t);
#endif HELPER
}
