/*****************************************************************
 *  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 <pctcp\options.h>
#include <pctcp\error.h>
#include <pctcp\netinfo.h>

#ifdef DNETCONN
#include <netdnet/dn.h>
#endif /* DNETCONN */

char *display;			/* The display number */

#ifdef X_PRINT_PORT
struct tcpport _far PrinterPort;
static int PrinterSocket;
static int printfd;
#endif
u_long _near AllClients;
u_long _near ClosingClients;
u_long _near WellKnownSockets;
static int printfd;
extern int near MaxClients;
extern int near nClients;
in_name near myaddr;
in_name near broadcast_addr;
u_long CloseTimeOut = 30000;

OsCommPtr near MyPrivate[NPORTS];

static int near listen_socket(int port);
static void _near ErrorConnMax(int fd);
extern int _near InvalidHost(void *saddr,int  len);

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

/* 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()
{
    struct netinfo ni;

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

    WellKnownSocket = listen_socket(tcpportReg);
    if (WellKnownSocket < 0)
	FatalError("Can't create Socket");
    net_open++;
    WellKnownSockets = 1L << WellKnownSocket;

    if (net_info(WellKnownSocket, &ni) < 0) {
	pneterror("net_info");
    } else {
	myaddr = ni.ip_address;
	broadcast_addr = (ni.ip_address & ni.ip_subnet) | (-1 & ~ni.ip_subnet);
    }

#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;
    struct addr addr;

    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 (get_peer(priv->fd, &addr) < 0) {
	pneterror("get_peer");
	return "Software error";
    }
    if (!authorized && InvalidHost(&addr.fhost, sizeof (addr.fhost))) {
	    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;

    connect_time = GetTimeInMillis();

    /* 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);     
	}
    }

    newconn = WellKnownSocket;
    WellKnownSocket = listen_socket(tcpportReg);

    AllClients |= WellKnownSockets;
    WellKnownSockets &= ~(1L << newconn);

    if (WellKnownSocket >= 0) {
	WellKnownSockets |= 1L << WellKnownSocket;
    }

    oc = (OsCommPtr)xalloc(sizeof (OsCommRec));
    if (!oc) {
	ErrorConnMax(newconn);
	AllClients &= ~(1L << newconn);
	net_release(newconn);
	return;
    }
	
    oc->fd = newconn;
    oc->conn_time = connect_time;
    oc->input = 0;
    oc->output = 0;
    oc->flags = 0;
    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;

    /* 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 (net_read(fd, &byteOrder, 1, 0, 0) == 1)
	    break;
	if (neterrno != NET_ERR_WOULD_BLOCK)
	    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);
    }
    net_write(fd, (char *)&csp, sz_xConnSetupPrefix, 0);
    net_write(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);
	if (WellKnownSocket >= 0) {
	    WellKnownSockets |= 1L << WellKnownSocket;
	}
    }
    return TRUE;
}

/* Flush data from any closing clients.  Free the descriptor when the
 * client has sent the EOF.
 */
void _near
FlushData(mask)
u_long mask;
{
    int i;
    OsCommPtr	oc;

    for (i = 0; i < NPORTS; i++)
	if (mask & (1L << i)) {
	    oc = MyPrivate[i];
	    if (oc->flags & OS_FCLOSED ||
		net_read(i, 0, 4096, 0, NET_FLG_DRAIN) < 0 &&
		neterrno != NET_ERR_WOULD_BLOCK) {
		    ClosingClients &= ~(1L << i);
		    net_release(i);
		    xfree(oc);
		    MyPrivate[i] = 0;
	    }
	}
}

/*****************
 * 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 addr addr;
    int request;

    request = net_getdesc();
    if (request < 0) {
	pneterror("net_getdesc");
	return request;
    }

    if (set_option(request, 0, NET_OPT_NONBLOCKING, (char far *)1, 0)) {
	pneterror("set_option");
	net_release(request);
	return -1;
    }
    addr.lsocket = port;
    addr.fhost = 0;
    addr.fsocket = 0;
    if (net_listen(request, STREAM, &addr) < 0) {
	pneterror("net_listen");
	net_release(request);
	return -1;
    }
    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

unsigned long _fastcall
ClientNetAddr(client)
ClientPtr client;
{
    struct addr addr;

    get_peer(((OsCommPtr)(client->osPrivate))->fd, &addr);
    return addr.fhost;
}

#ifdef notdef
debug_print()
{
    OsCommPtr oc;
    int i;
    ConnectionOutputPtr oco;
    ConnectionInputPtr oci;
    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 ((oco = oc->output) && oco->count) {
		printf(" output count %d ", oco->count);
	}
	if ((oci = oc->input) && oci->bufcnt) {
		printf(" input count %d ", oci->bufcnt);
		request = (xReq *)oci->buffer;
		printf(" request %d len %d",  request->reqType, request->length);
	}
	printf("\n");
    }
}
#endif

static void _far netshut(void);
static called=0;

void
start_network()
{
    atexit(netshut);
}

static void _far
netshut()
{
    if (net_open) {
	net_open = 0;
	net_releaseall();
    }
}
