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

#define	TIME_T_DEFINED
#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 "dixstruct.h"
#include "osstruct.h"
#include "opaque.h"
#include "osdep.h"
#include "generic.h"
#include "funcs.h"

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

extern char *display;			/* The display number */

#ifdef X_PRINT_PORT
static int PrinterSocket;
static int printfd;
#endif
#ifdef XDMCP
extern int xdmcpSocket;
#endif
u_long AllClients;
u_long InputSockets;
u_long ClosingClients;
u_long WellKnownSockets;
int MaxClients = NPORTS;
u_long myaddr;
u_long broadcast_addr;
u_long CloseTimeOut = 30000;

OsCommPtr MyPrivate[NPORTS];

static int listen_socket(int port);
static void ErrorConnMax(int fd);

int WellKnownSocket;
OsCommPtr oneClient;
static int tcpportReg;	    /* port with same byte order as server */
static int net_is_open=0;

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

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

void
CreateWellKnownSockets()
{
    struct net_info ni;

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

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

    if (net_info(WellKnownSocket, &ni) < 0) {
	net_perror("net_info");
    } else {
	myaddr = ni.ip_address;
	broadcast_addr = ni.ip_broadcast;
    }

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

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

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 (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
EstablishNewConnections(mask)
u_long mask;		/* mask of connections ready */
{
    int newconn;                  /* fd of new client */
    ClientPtr client;
    u_long connect_time;
    OsCommPtr	oc;
    int i;
    struct net_addr addr;

    mask = mask;	/* We know it's WellKnownSocket. */

    connect_time = GetTimeInMillis();

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

    newconn = net_accept(WellKnownSocket, &addr);
    if (newconn < 0) {
	net_perror("net_accept");
	if (neterrno == NETERR_WOULD_BLOCK)
	    return;
	(void)net_release(WellKnownSocket);
    }

    if (newconn < 0 || newconn == WellKnownSocket) {
	if (WellKnownSocket >= 0)
	    WellKnownSockets &= ~(1L << WellKnownSocket);

	WellKnownSocket = listen_socket(tcpportReg);

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

    if (newconn < 0)
	return;

    oc = (OsCommPtr)xalloc(sizeof (OsCommRec));

    if (!oc) {
	ErrorConnMax(newconn);
	net_release(newconn);
	return;
    }

    AllClients |= 1L << newconn;
    InputSockets |= 1L << newconn;

    oc->fd = newconn;
    oc->conn_time = connect_time;
    oc->input = 0;
    oc->output = 0;
    oc->flags = 0;
    oc->ipaddress = addr.host;
    MyPrivate[newconn] = oc;

    if ((client = NextAvailableClient((pointer)oc)) != 0)
    {
	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
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) == 1)
	    break;
	if (neterrno != NETERR_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);
    net_write(fd, noroom, csp.lengthReason + (-csp.lengthReason & 3));
}

/*****************
 * 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);
    CloseDownFileDescriptor(oc);
    if (WellKnownSocket < 0) {
	WellKnownSocket = listen_socket(tcpportReg);
	if (WellKnownSocket >= 0) {
	    WellKnownSockets |= 1L << WellKnownSocket;
	}
    }
    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;
{
    oneClient = (OsCommPtr)client->osPrivate;
/*
printf("only %d\n", oneClient->client);
*/
}

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

void
ListenToAllClients()
{
    oneClient = 0;
/*
printf("all\n");
*/
}

static int
listen_socket(port)
int port;
{
    struct net_addr addr;
    int request;

    addr.socket = port;
    addr.host = 0;
    request = net_socket(NET_TYPE_TCP, &addr);
    if (request < 0) {
	mxFixPage();
    }
    return request;
}

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

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

	print_bytes = net_read(PrinterSocket, printer_buf, sizeof printer_buf);
	if (print_bytes <= 0) {
	    if (neterrno == NETERR_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
ClientNetAddr(client)
ClientPtr client;
{
    return ((OsCommPtr)(client->osPrivate))->ipaddress;
}

static void netshut(void);

void
start_network(file)
const char *file;
{
    int i;

    i = net_open(file);
    if (i)
	FatalError("Net error %d\n", i);
    net_is_open++;
    atexit(netshut);
}

static void
netshut()
{
    OsCommPtr oc;
    int i;

    if (!net_is_open)
	return;
    net_is_open = 0;

    /* Close down all those file descriptors that can be easily closed. */

    for (i = 0; i < NPORTS; i++) {
	oc = MyPrivate[i];
	if (!oc)
	    continue;
	if (oc->flags & OS_FCLOSED ||
	    net_drain(i) < 0 &&
	    neterrno != NETERR_WOULD_BLOCK) {
		ClosingClients &= ~(1L << i);
		net_release(i);
		xfree(oc);
		MyPrivate[i] = 0;
	}
    }
    net_release(WellKnownSocket);
#ifdef XDMCP
    net_release(xdmcpSocket);
#endif

    net_shutdown();
}

void
debug_print()
{
}

void
netsleep()
{
}
