/*****************************************************************
 *  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 <netinet/in.h>

char *display;			/* The display number */

#ifdef X_PRINT_PORT
static int PrinterSocket;
static int printfd;
#endif
fd_set _near AllSockets;
static int printfd;
#ifdef notdef
extern int near MaxClients;
extern int near nClients;
#endif
u_long near myaddr;
u_long 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 */

/* 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";

extern int near lastRequest;

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

void
CreateWellKnownSockets()
{
    tcpportReg = atoi(display);
    tcpportReg += X_TCP_PORT;

    myaddr = getmyipaddr();	/* TODO: broadcast_addr */

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

    FD_SET(WellKnownSocket, &AllSockets);

#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 ()
{
    soclose(WellKnownSocket);
    FD_ZERO(&AllSockets);

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

    FD_SET(WellKnownSocket, &AllSockets);

    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 sockaddr_in addr;
    int len;

#ifdef notdef
    if (nClients > MaxClients)
	return noroom;
#endif
    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;

    len = sizeof addr;
    if (getpeername(priv->fd, (SADDR_PTR)&addr, &len) < 0) {
	soperror("get_peer");
	return "Software error";
    }
    if (!authorized && InvalidHost(&addr.sin_addr, sizeof (addr.sin_addr))) {
	    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 sockaddr_in addr;

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

    i = sizeof addr;
    newconn = accept(WellKnownSocket, (SADDR_PTR)&addr, &i);
    if (newconn < 0) {
	soperror("accept");
	return;
    }

    i = 1;
    if (ioctl(newconn, FIONBIO, (char *)&i)) {
	soperror("ioctl");
	soclose(newconn);
	return;
    }

    oc = (OsCommPtr)xalloc(sizeof (OsCommRec));
    if (!oc) {
	ErrorConnMax(newconn);
	soclose(newconn);
	return;
    }

    FD_SET(newconn, &AllSockets);
	
    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 */
	MyPrivate[newconn] = 0;
	xfree(oc);
	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 (soread(fd, &byteOrder, 1) == 1)
	    break;
	if (errno != EWOULDBLOCK)
	    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);
    }
    sowrite(fd, (char *)&csp, sz_xConnSetupPrefix);
    sowrite(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! lastRequest %d\n", client->index, lastRequest);
	return FALSE;
    }
#ifdef XDMCP
    XdmcpCloseDisplay(oc->fd);
#endif
    oc->client = -1;
    client->osPrivate = 0;
    FlushClient(oc, (char *)0, 0);
    CloseDownFileDescriptor(oc);
    MyPrivate[oc->fd] = 0;
    xfree(oc);
    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 sockaddr_in addr;
    int len;
    int request;

    request = socket(PF_INET, SOCK_STREAM, 0);
    if (request < 0) {
	soperror("socket");
	return request;
    }

    len = 1;
    if (ioctl(request, FIONBIO, (char *)&len)) {
	soperror("ioctl");
	soclose(request);
	return -1;
    }

    addr.sin_family = PF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = 0;
    memset(addr.sin_zero, 0, sizeof addr.sin_zero);
    if (bind(request, (SADDR_PTR)&addr, sizeof addr) < 0) {
	soperror("bind");
	soclose(request);
	return -1;
    }
    if (listen(request, 5) < 0) {
	soperror("listen");
	soclose(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 (errno == EWOULDBLOCK)
		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 _near
ClientNetAddr(client)
ClientPtr client;
{
    struct sockaddr_in addr;
    int len;
    OsCommPtr priv = (OsCommPtr)client->osPrivate;

    len = sizeof addr;
    (void)getpeername(priv->fd, (SADDR_PTR)&addr, &len);
    return addr.sin_addr.s_addr;
}

#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);
extern int near xdmcpSocket;

void
start_network()
{
    atexit(netshut);
}

static void _far
netshut()
{
    if (WellKnownSocket >= 0) {
	soclose(WellKnownSocket);
	WellKnownSocket = -1;
    }
    if (xdmcpSocket >= 0) {
	soclose(xdmcpSocket);
	xdmcpSocket = -1;
    }
}
