#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <webster.h>

#ifdef _AIX
#include <sys/select.h>
#endif

#ifdef SUNRPC
#include <rpc/rpc.h>
#include <sunrpcweb.h>
#else !SUNRPC
#include <netinet/in.h>
#endif !SUNRPC

#ifdef TTYCLIENT
extern int	interactive;
#endif TTYCLIENT

#ifndef SUNRPC
FILE *WebsterSock;
#endif SUNRPC

extern char	*whoami;
extern char	**hostlist;

#ifndef SUNRPC
/*
 * connectup - connects to the Webster server.
 */
connectup()
{
	register int	s;
	struct sockaddr_in sin;
	register struct hostent *hp;
	register struct servent *sp;
	struct hostent *gethostbyname();
	struct servent *getservbyname();

	/*
	 * Try each server in turn until one works.
	 */

	while (*hostlist) {

		/*
		 * Look up the host in the host file.
		 */
		if ((hp = gethostbyname(*hostlist)) == NULL) {
			hostlist++;
			continue;
		}

		bzero((char *) & sin, sizeof(struct sockaddr_in));

		/*
		 * Build the server's address.
		 */
		sin.sin_family = AF_INET;
		bcopy(hp->h_addr, (char *) & sin.sin_addr, hp->h_length);

		if ((sp = getservbyname(WEBSTERNAME, "tcp")) == NULL)
			sin.sin_port = htons(WEBSTERPORT);
		else
			sin.sin_port = sp->s_port;

		/*
		 * Get a TCP socket.
		 */
		if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
			perror("webster: socket");
			exit(1);
		}

		/*
		 * Try to connect.
		 */
		if (connect(s, (struct sockaddr *)&sin,
			    sizeof(struct sockaddr_in )) <
		    0) {
			hostlist++;
			continue;
		} else
			break;
	}
	if (!*hostlist) {
		fprintf(stderr, "There are no webster servers available.  Please send mail to bug-sipb and\ninform them of this problem.\n");
		exit(1);
	}

	/*
	 * Open the socket for stdio.
	 */
	WebsterSock = fdopen(s, "r");
}


#endif !SUNRPC

#ifdef SUNRPC
bool_t
xdr_longstring(xdrs, cpp)
XDR *xdrs;
char	**cpp;
{
	if (xdr_string(xdrs, cpp, MAXDEFNLEN)) {
		return(TRUE);
	}
	return(FALSE);
}


#endif SUNRPC

/*
 * byebye - called on exit.
 */
byebyeval(val)
int val;
{
#ifdef TTYCLIENT
	/*
	 * If interactive, reset the tty modes.
	 */
	if (interactive)
	    reset_terminal ();
#endif TTYCLIENT
	/*
	 * Close the socket and exit.
	 */
#ifndef SUNRPC
	(void) fclose(WebsterSock);
#endif !SUNRPC
	(void) write(1, "\n", 1);
	exit(val);
}

byebye()
{
     byebyeval(0);
}

memerror()
{
	int	byebye();

	printf("%s: out of memory\n", whoami);
	byebyeval(-1);
}


