/*****************************************************************
 *  Stuff to create connections --- OS dependent
 *
 *      EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets,
 *      CloseDownConnection, CheckConnections, AddEnabledDevice,
 *	RemoveEnabledDevice, OnlyListToOneClient,
 *      ListenToAllClients,
 *
 *      (WaitForSomething is in its own file)
 *
 *****************************************************************/

#include <signal.h>
#include <time.h>
#undef NULL
#include "X.h"
#include "Xproto.h"
#include "Xos.h"			/* for strings, file, time */

#include <stdlib.h>
#include <stdio.h>
#include "osstruct.h"
#include "opaque.h"
#include "dixstruct.h"
#include "osdep.h"
#include <sys/tk_types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <xti.h>

char *display;			/* The display number */

#ifdef X_PRINT_PORT
static int PrinterSocket;
static int printfd;
#endif
extern int _near MaxClients;
extern int _near nClients;
u_long _near myaddr = 0;
u_long _near broadcast_addr;
u_long _near CloseTimeOut = 30000;

OsCommPtr _near MyPrivate[NPORTS];

static int _near listen_socket(int port);
static void _near ErrorConnMax(int fd);
u_long _near _fastcall _near ClientNetAddr(ClientPtr client);

int _near WellKnownSocket;
static Bool GrabDone = FALSE;
OsCommPtr _near oneClient;
static int tcpportReg;	    /* port with same byte order as server */

/* These are hacks because we know we only do MIT-MAGIC-COOKIE-1. */
int _near MitMagicLen;
char _near * _near MitMagicData;
char _near MitMagicName[18] = "MIT-MAGIC-COOKIE-1";

/*****************
 * CreateWellKnownSockets
 *    At initialization, create the sockets to listen on for new clients.
 *****************/

void
CreateWellKnownSockets()
{

    tcpportReg = atoi(display);
    tcpportReg += X_TCP_PORT;

    WellKnownSocket = listen_socket(tcpportReg);
    if (WellKnownSocket < 0)
	FatalError("Can't create Socket");

#ifdef X_PRINT_PORT
    PrinterSocket = listen_socket(X_PRINT_PORT);
#endif
    signal (SIGINT, GiveUp);
    signal (SIGTERM, GiveUp);
    ResetHosts(display);
#ifdef XDMCP
    XdmcpInit ();
#endif
    EnableLocalHost();
}

void
ResetWellKnownSockets ()
{
    ResetHosts(display);
#ifdef XDMCP
    XdmcpReset ();
#endif
    EnableLocalHost();
}

static char noroom[] = "Maximum number of clients reached";

/*****************************************************************
 * ClientAuthorized
 *
 *     	It is hoped that eventually one protocol will be agreed upon.  In the
 *        mean time, a server that implements a different protocol than the
 *        client expects, or a server that only implements the host-based
 *        mechanism, will simply ignore this information.
 *
 *****************************************************************/

char * 
ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
    ClientPtr client;
    char *auth_proto, *auth_string;
    unsigned short proto_n, string_n;
{
    OsCommPtr priv;
    Bool authorized = FALSE;

    if (nClients > MaxClients)
	return noroom;
    if (MitMagicLen && proto_n == sizeof MitMagicName &&
	memcmp(auth_proto, MitMagicName, sizeof MitMagicName) == 0 &&
	string_n == MitMagicLen &&
	memcmp(auth_string, MitMagicData, MitMagicLen) == 0)
	    authorized = TRUE;

    priv = (OsCommPtr)client->osPrivate;

    if (!authorized && InvalidHost(&priv->ipaddress, sizeof priv->ipaddress)) {
	    return "Client is not authorized to connect to Server";
    }

    priv->conn_time = 0;

    /* At this point, if the client is authorized to change the access control
     * list, we should getpeername() information, and add the client to
     * the selfhosts list.  It's not really the host machine, but the
     * true purpose of the selfhosts list is to see who may change the
     * access control list.
     */
    return((char *)0);
}    

/*****************
 * EstablishNewConnections
 *    If anyone is waiting on listened sockets, accept them.
 *****************/

void _near
EstablishNewConnections()
{
    int newconn;                  /* fd of new client */
    ClientPtr client;
    u_long connect_time;
    OsCommPtr	port, oc;
    int i;
    struct t_call call;
    struct sockaddr_in addr;

    newconn = t_open(T_TCP, O_RDWR|O_NONBLOCK, NULL);
    if (newconn < 0) {
	t_error("t_open");
	return;
    }
    if (t_bind(newconn, NULL, NULL) < 0) {
	t_error("t_bind");
	(void)t_close(newconn);
	return;
    }
    bzero(&call, sizeof call);
    call.addr.maxlen = sizeof (struct sockaddr_in);
    call.addr.len = sizeof (struct sockaddr_in);
    call.addr.buf = (char *)&addr;
    if (t_accept(WellKnownSocket, newconn, &call) < 0) {
	t_error("t_accept");
	(void)t_close(newconn);
	return;
    }
    connect_time = GetTimeInMillis();

    /* clean up */
    for (i = 0; i < NPORTS; i++)
	if (port = MyPrivate[i]) {
	    if (port->flags & OS_CLOSING && port->conn_time != 0 &&
		connect_time - port->conn_time >= CloseTimeOut) {
		    (void)t_close(i);
		    MyPrivate[i] = 0;
		    xfree(port);
	    }
	}

    /* kill off stragglers */
    for (i=1; i<currentMaxClients; i++)
    {
	if (client = clients[i])
	{
	    port = (OsCommPtr)client->osPrivate;
	    if (port && (port->conn_time != 0) &&
		(connect_time - port->conn_time) >= TimeOutValue)
		CloseDownClient(client);     
	}
    }

    oc = (OsCommPtr)_nmalloc(sizeof (OsCommRec));
    if (!oc) {
	ErrorConnMax(newconn);
	(void)t_close(newconn);
	return;
    }
	
    oc->fd = newconn;
    oc->conn_time = connect_time;
    oc->input = 0;
    oc->output = 0;
    oc->flags = 0;
    oc->ipaddress = addr.sin_addr.s_addr;
    MyPrivate[newconn] = oc;

    if (client = NextAvailableClient((pointer)oc))
    {
	oc->client = client->index;
    }
    else
    {
	ErrorConnMax(newconn);
	CloseDownFileDescriptor(oc);	/* this may free some memory */
	return;
    }
/*
printf("new connection %d\n", client->index);
*/
#ifdef XDMCP
    /* indicate to Xdmcp protocol that we've opened new client */
    XdmcpOpenDisplay(newconn, ClientNetAddr(client));
#endif /* XDMCP */
}

/************
 *   ErrorConnMax
 *     Fail a connection due to lack of client or file descriptor space
 ************/

static void _near
ErrorConnMax(fd)
int	fd;
{
    xConnSetupPrefix csp;
    char byteOrder = 0;
    unsigned long time, now;
    int flags = 0;

    /* Let's wait a half second for the client to send us at least its
     * byte order. */
    _disable();
    time = n_clicks();
    _enable();
    now = time;

    while (now - time < 6L) {
	if (t_rcv(fd, &byteOrder, 1, &flags) == 1)
	    break;
	if (t_errno != TNODATA)
	    return;
	_disable();
	now = n_clicks();
	_enable();
    }
    if (byteOrder != 'l' && byteOrder != 'B')
	return;
    csp.success = xFalse;
    csp.lengthReason = sizeof(noroom) - 1;
    csp.length = (sizeof(noroom) + 2) >> 2;
    csp.majorVersion = X_PROTOCOL;
    csp.minorVersion = X_PROTOCOL_REVISION;
    if (byteOrder == 'B') {
	csp.majorVersion = lswaps(csp.majorVersion);
	csp.minorVersion = lswaps(csp.minorVersion);
	csp.length = lswaps(csp.length);
    }
    t_snd(fd, (char *)&csp, sz_xConnSetupPrefix, T_MORE);
    t_snd(fd, noroom, csp.lengthReason + (-csp.lengthReason & 3), 0);
}

/*****************
 * CloseDownConnection
 *    Delete client from AllClients and free resources 
 *****************/

Bool
CloseDownConnection(client)
    ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;

    if (oc == NULL) {
	printf("client %d: osPrivate is NULL!\n", client->index);
	return FALSE;
    }
#ifdef XDMCP
    XdmcpCloseDisplay(oc->fd);
#endif
    oc->client = -1;
    client->osPrivate = 0;
    FlushClient(oc, (char *)0, 0);
    CloseDownFileDescriptor(oc);
    if (WellKnownSocket < 0) {
	WellKnownSocket = listen_socket(tcpportReg);
    }
    return TRUE;
}

/*****************
 * OnlyListenToOneClient:
 *    Only accept requests from  one client.  Continue to handle new
 *    connections, but don't take any protocol requests from the new
 *    ones.
 *    Note also that there is no timeout for this in the protocol.
 *    This routine is "undone" by ListenToAllClients()
 *****************/

void
OnlyListenToOneClient(client)
    ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;

    if (!GrabDone) {
	oneClient = oc;
	GrabDone = TRUE;
    }
}

/****************
 * ListenToAllClients:
 *    Undoes OnlyListentToOneClient()
 ****************/

void
ListenToAllClients()
{
    if (GrabDone) {
	oneClient = 0;
	GrabDone = FALSE;
    }
}

static int _near
listen_socket(port)
int port;
{
    struct t_bind *bind;
    struct sockaddr_in *sin;
    int request;

    request = t_open(T_TCP, O_RDWR|O_NONBLOCK, NULL);
    if (request < 0) {
	t_error("t_open");
	return request;
    }

    bind = (struct t_bind *)t_alloc(request, T_BIND, T_ALL);
    if (bind == 0) {
	t_error("t_alloc");
	(void)t_close(request);
	return -1;
    }

    bind->qlen = 5;
    bind->addr.len = sizeof (struct sockaddr_in);
    sin = (struct sockaddr_in *)bind->addr.buf;
    sin->sin_family = AF_INET;
    sin->sin_port = htons(port);
    sin->sin_addr.s_addr = INADDR_ANY;

    if (t_bind(request, bind, bind) < 0) {
	t_error("t_bind");
	(void)t_free((char *)bind, T_BIND);
	(void)t_close(request);
	return -1;
    }
    if (!myaddr) {
printf("myaddr=%#lx\n", myaddr);
	myaddr = sin->sin_addr.s_addr;
    }
    (void)t_free((char *)bind, T_BIND);
    return request;
}

#ifdef X_PRINT_PORT
int _near
PrintOpen()
{
	printfd = open("prn", O_WRONLY);
	if(printfd < 0) {
	    SoWrite(PrinterSocket, "Can't open printer.\r\n", 21);
	    close(printfd);
	    printfd = -1;
	    SoClose(PrinterSocket);
	    PrinterSocket = listen_socket(X_PRINT_PORT);
	    return 0;
	}
	return 1;
}

int _near
PrintIt()
{
	char printer_buf[256];
	int print_bytes;

	print_bytes = net_read(PrinterSocket, printer_buf, sizeof printer_buf,
	    0, 0);
	if (print_bytes <= 0) {
	    if (neterrno == NET_ERR_WOULD_BLOCK)
		return 1;
	    net_release(PrinterSocket);
	    close(printfd);
	    printfd = -1;
	    PrinterSocket = listen_socket(X_PRINT_PORT);
	    return 0;
	}
	(void)write(printfd, printer_buf, print_bytes);
	return 1;
}
#endif

u_long _near _fastcall
ClientNetAddr(client)
ClientPtr client;
{

    return ((OsCommPtr)(client->osPrivate))->ipaddress;
}

#ifdef notdef
debug_print()
{
    OsCommPtr oc;
    int i;
    ConnectionPtr occ;
    xReq *request;

/*    PrintWindowTree(); */
    if (oneClient)
	printf("Only %d\n", oneClient->client);

    for (i = 0; i < NPORTS; i++) {
	if (!MyPrivate[i])
	    continue;
	oc = MyPrivate[i];
	printf("client %d fd %d ptr %lx flags=%x", oc->client, i, oc, oc->flags);
	if ((occ = oc->output) && occ->count) {
		printf(" output count %d ", occ->count);
	}
	if ((occ = oc->input) && occ->bufcnt) {
		printf(" input count %d ", occ->count);
		request = (xReq *)occ->buffer;
		printf(" request %d len %d",  request->reqType, request->length);
	}
	printf("\n");
    }
}
#endif

void
start_network()
{
}
