/***********************************************************

Copyright 1987, 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.


Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/
/*****************************************************************
 *  Stuff to create connections --- OS dependent
 *
 *      EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets,
 *      CloseDownConnection, CheckConnections,
 *      OnlyListToOneClient,
 *      ListenToAllClients,
 *
 *      (WaitForSomething is in its own file)
 *
 *      In this implementation, a client socket table is not kept.
 *      Instead, what would be the index into the table is just the
 *      file descriptor of the socket.  This won't work for if the
 *      socket ids aren't small nums (0 - 2^8)
 *
 *****************************************************************/

#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <nx-X11/X.h>
#include <nx-X11/Xproto.h>
#define XSERV_t
#define TRANS_SERVER
#define TRANS_REOPEN
#include <nx-X11/Xtrans/Xtrans.h>
#include <nx-X11/Xtrans/Xtransint.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/socket.h>

#if defined(TCPCONN)
# include <netinet/in.h>
# include <arpa/inet.h>

/* FIXME: correct indentation levels after ancient platform support clean-up */

#  ifdef apollo
#   ifndef NO_TCP_H
#    include <netinet/tcp.h>
#   endif
#  else
#   ifdef CSRG_BASED
#    include <sys/param.h>
#   endif
#   include <netinet/tcp.h>
#  endif
# include <arpa/inet.h>
#endif

#include <sys/uio.h>
#include "misc.h"
#include "osdep.h"
#include <nx-X11/Xpoll.h>
#include "opaque.h"
#include "dixstruct.h"
#include "list.h"
#ifdef XCSECURITY
#define _SECURITY_SERVER
#include <nx-X11/extensions/security.h>
#endif

#ifdef X_NOT_POSIX
#define Pid_t int
#else
#define Pid_t pid_t
#endif

int lastfdesc;			/* maximum file descriptor */

fd_set NotifyReadFds;           /* mask for other file descriptors */
fd_set NotifyWriteFds;          /* mask for other write file descriptors */
fd_set AllSockets;		/* select on this */
fd_set AllClients;		/* available clients */
fd_set LastSelectMask;		/* mask returned from last select call */
fd_set LastSelectWriteMask;     /* mask returned from last select call */
fd_set ClientsWithInput;	/* clients with FULL requests in buffer */
fd_set ClientsWriteBlocked;	/* clients who cannot receive output */
fd_set OutputPending;		/* clients with reply/event data ready to go */
int MaxClients = 0;
int NumNotifyWriteFd;           /* Number of NotifyFd members with write set */
Bool NewOutputPending;		/* not yet attempted to write some new output */
Bool AnyWritesPending;          /* true if some client blocked on write or NotifyFd with write */
Bool NoListenAll;               /* Don't establish any listening sockets */
Bool RunFromSmartParent;	/* send SIGUSR1 to parent process */
static char dynamic_display[7]; /* display name */
Bool PartialNetwork;		/* continue even if unable to bind all addrs */
static Pid_t ParentProcess;

static Bool debug_conns = FALSE;

fd_set IgnoredClientsWithInput;
static fd_set GrabImperviousClients;
static fd_set SavedAllClients;
static fd_set SavedAllSockets;
static fd_set SavedClientsWithInput;
int GrabInProgress = 0;

static void
QueueNewConnections(int curconn, int ready, void *data);

int *ConnectionTranslation = NULL;

XtransConnInfo 	*ListenTransConns = NULL;
int	       	*ListenTransFds = NULL;
int		ListenTransCount;

static void ErrorConnMax(XtransConnInfo /* trans_conn */);

static
void CloseDownFileDescriptor(
    OsCommPtr /*oc*/
);


static XtransConnInfo
lookup_trans_conn (int fd)
{
    if (ListenTransFds)
    {
	int i;
	for (i = 0; i < ListenTransCount; i++)
	    if (ListenTransFds[i] == fd)
		return ListenTransConns[i];
    }

    return (NULL);
}

/* Set MaxClients and lastfdesc, and allocate ConnectionTranslation */

void
InitConnectionLimits(void)
{
    lastfdesc = -1;

#ifndef __CYGWIN__

#if !defined(XNO_SYSCONF) && defined(_SC_OPEN_MAX)
    lastfdesc = sysconf(_SC_OPEN_MAX) - 1;
#endif

#ifdef HAS_GETDTABLESIZE
    if (lastfdesc < 0)
	lastfdesc = getdtablesize() - 1;
#endif

#ifdef _NFILE
    if (lastfdesc < 0)
	lastfdesc = _NFILE - 1;
#endif

#endif /* __CYGWIN__ */

    /* This is the fallback */
    if (lastfdesc < 0)
	lastfdesc = MAXSOCKS;

    if (lastfdesc > MAXSELECT)
	lastfdesc = MAXSELECT;

    if (lastfdesc > MAXCLIENTS)
    {
	lastfdesc = MAXCLIENTS;
	if (debug_conns)
	    ErrorF( "REACHED MAXIMUM CLIENTS LIMIT %d\n", MAXCLIENTS);
    }
    MaxClients = lastfdesc;

#ifdef DEBUG
    ErrorF("InitConnectionLimits: MaxClients = %d\n", MaxClients);
#endif

    ConnectionTranslation = (int *)xnfalloc(sizeof(int)*(lastfdesc + 1));
}

/*
 * If SIGUSR1 was set to SIG_IGN when the server started, assume that either
 *
 *  a- The parent process is ignoring SIGUSR1
 *
 * or
 *
 *  b- The parent process is expecting a SIGUSR1
 *     when the server is ready to accept connections
 *
 * In the first case, the signal will be harmless, in the second case,
 * the signal will be quite useful.
 */
static void
InitParentProcess(void)
{
    OsSigHandlerPtr handler;
    handler = OsSignal (SIGUSR1, SIG_IGN);
    if ( handler == SIG_IGN)
	RunFromSmartParent = TRUE;
    OsSignal(SIGUSR1, handler);
    ParentProcess = getppid ();
#ifdef __UNIXOS2__
    /*
     * fg030505: under OS/2, xinit is not the parent process but
     * the "grant parent" process of the server because execvpe()
     * presents us an additional process number;
     * GetPPID(pid) is part of libemxfix
     */
    ParentProcess = GetPPID (ParentProcess);
#endif /* __UNIXOS2__ */
}

void
NotifyParentProcess(void)
{
    if (displayfd >= 0) {
#ifdef NXAGENT_SERVER
	if (displayfd == STDERR_FILENO)
	{
	    const char *msg = "Auto-detected display number is: DISPLAY=:";
	    if (write(displayfd, msg, strlen(msg)) != strlen(msg))
		FatalError("Cannot write display number to fd %d\n", displayfd);
	}
#endif
	if (write(displayfd, display, strlen(display)) != strlen(display))
	    FatalError("Cannot write display number to fd %d\n", displayfd);
	if (write(displayfd, "\n", 1) != 1)
	    FatalError("Cannot write display number to fd %d\n", displayfd);
	close(displayfd);
	displayfd = -1;
    }
    if (RunFromSmartParent) {
       if (ParentProcess > 1) {
           kill (ParentProcess, SIGUSR1);
       }
    }
}

static Bool
TryCreateSocket(int num, int *partial)
{
    char port[20];

    snprintf(port, sizeof(port), "%d", num);

    return (_XSERVTransMakeAllCOTSServerListeners(port, partial,
                                                  &ListenTransCount,
                                                  &ListenTransConns) >= 0);
}

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

void
CreateWellKnownSockets(void)
{
    int		i;
    int		partial;

    FD_ZERO(&AllSockets);
    FD_ZERO(&AllClients);
    FD_ZERO(&LastSelectMask);
    FD_ZERO(&ClientsWithInput);

    for (i=0; i<MaxClients; i++) ConnectionTranslation[i] = 0;

    /* display is initialized to "0" by main(). It is then set to the display
     * number if specified on the command line. */
    if (NoListenAll) {
	ListenTransCount = 0;
    }
#ifndef NXAGENT_SERVER
    else if ((displayfd < 0) || explicit_display) {
#else
    else if (displayfd < 0) {
#endif /* ! NXAGENT_SERVER */
        if (TryCreateSocket(atoi(display), &partial) &&
            ListenTransCount >= 1)
            if (!PartialNetwork && partial)
                FatalError ("Failed to establish all listening sockets");
    }
    else { /* -displayfd and no explicit display number */
	Bool found = 0;
	int i_offset = 0;
#ifdef NXAGENT_SERVER
	if (explicit_display)
	     i_offset = atoi(display);
#endif /* NXAGENT_SERVER */
	for (i = i_offset; i < 65536 - X_TCP_PORT; i++) {
	    if (TryCreateSocket(i, &partial) && !partial) {
		found = 1;
		break;
	    }
	    else
		CloseWellKnownConnections();
	}
	if (!found)
	    FatalError("Failed to find a socket to listen on");
	snprintf(dynamic_display, sizeof(dynamic_display), "%d", i);
	display = dynamic_display;
	LogSetDisplay();
    }

    ListenTransFds = malloc(ListenTransCount * sizeof (int));

    for (i = 0; i < ListenTransCount; i++) {
        int fd = _XSERVTransGetConnectionNumber(ListenTransConns[i]);

        ListenTransFds[i] = fd;
	SetNotifyFd(fd, QueueNewConnections, X_NOTIFY_READ, NULL);

        if (!_XSERVTransIsLocal(ListenTransConns[i]))
            DefineSelf (fd);
    }

    if (ListenTransCount == 0 && !NoListenAll)
        FatalError ("Cannot establish any listening sockets - Make sure an X server isn't already running");
    OsSignal (SIGPIPE, SIG_IGN);
    OsSignal (SIGHUP, AutoResetServer);
    OsSignal (SIGINT, GiveUp);
    OsSignal (SIGTERM, GiveUp);
    ResetHosts(display);

    InitParentProcess();

#ifdef XDMCP
    XdmcpInit ();
#endif
}

#ifdef NX_TRANS_SOCKET

/*
 * The following block is now defined also
 * under Cygwin to support this environment.
 */

#ifndef __DARWIN__

/*
 * This is defined in Xtranssock.c and must
 * be called explicitly as it doesn't share
 * a pointer in the transport function table.
 */

extern void _XSERVTransSocketRejectConnection(XtransConnInfo);

void
RejectWellKnownSockets ()
{
    int i;

    for (i = 0; i < ListenTransCount; i++)
    {
        _XSERVTransSocketRejectConnection(ListenTransConns[i]);
    }
}

#endif /* #ifndef __DARWIN__ */

#else /* #ifdef NX_TRANS_SOCKET */

void
RejectWellKnownSockets ()
{
}

#endif /* #ifdef NX_TRANS_SOCKET */

void
ResetWellKnownSockets (void)
{
    int i;

    ResetOsBuffers();

    for (i = 0; i < ListenTransCount; i++)
    {
	int status = _XSERVTransResetListener (ListenTransConns[i]);

	if (status != TRANS_RESET_NOOP)
	{
	    if (status == TRANS_RESET_FAILURE)
	    {
		/*
		 * ListenTransConns[i] freed by xtrans.
		 * Remove it from out list.
		 */

		RemoveNotifyFd(ListenTransFds[i]);
		ListenTransFds[i] = ListenTransFds[ListenTransCount - 1];
		ListenTransConns[i] = ListenTransConns[ListenTransCount - 1];
		ListenTransCount -= 1;
		i -= 1;
	    }
	    else if (status == TRANS_RESET_NEW_FD)
	    {
		/*
		 * A new file descriptor was allocated (the old one was closed)
		 */

		int newfd = _XSERVTransGetConnectionNumber (ListenTransConns[i]);

		ListenTransFds[i] = newfd;
	    }
	}
    }

    for (i = 0; i < ListenTransCount; i++)
	SetNotifyFd(ListenTransFds[i], QueueNewConnections, X_NOTIFY_READ, NULL);

    ResetAuthorization ();
    ResetHosts(display);
    /*
     * restart XDMCP
     */
#ifdef XDMCP
    XdmcpReset ();
#endif
}

void
CloseWellKnownConnections(void)
{
    int i;

    for (i = 0; i < ListenTransCount; i++) {
	if (ListenTransConns[i] != NULL) {
	    _XSERVTransClose(ListenTransConns[i]);
	    ListenTransConns[i] = NULL;
	    if (ListenTransFds != NULL)
		RemoveNotifyFd(ListenTransFds[i]);
	}
    }
    ListenTransCount = 0;
}

static void
AuthAudit (ClientPtr client, Bool letin, 
    struct sockaddr *saddr, int len, 
    unsigned int proto_n, char *auth_proto, int auth_id)
{
    char addr[128];
    char *out = addr;

    char client_uid_string[64];
    LocalClientCredRec *lcc;

    if (!len)
        strcpy(out, "local host");
    else
	switch (saddr->sa_family)
	{
	case AF_UNSPEC:
#if defined(UNIXCONN) || defined(LOCALCONN)
	case AF_UNIX:
#endif
	    strcpy(out, "local host");
	    break;
#if defined(TCPCONN)
	case AF_INET:
	    sprintf(out, "IP %s",
		inet_ntoa(((struct sockaddr_in *) saddr)->sin_addr));
	    break;
#if defined(IPv6) && defined(AF_INET6)
	case AF_INET6: {
	    char ipaddr[INET6_ADDRSTRLEN];
	    inet_ntop(AF_INET6, &((struct sockaddr_in6 *) saddr)->sin6_addr,
	      ipaddr, sizeof(ipaddr));
	    sprintf(out, "IP %s", ipaddr);
	}
	    break;
#endif
#endif
	default:
	    strcpy(out, "unknown address");
	}

    if (GetLocalClientCreds(client, &lcc) != -1) {
	int slen; /* length written to client_uid_string */

	strcpy(client_uid_string, " ( ");
	slen = 3;

	if (lcc->fieldsSet & LCC_UID_SET) {
	    snprintf(client_uid_string + slen,
	             sizeof(client_uid_string) - slen,
	             "uid=%ld ", (long) lcc->euid);
	    slen = strlen(client_uid_string);
	}

	if (lcc->fieldsSet & LCC_GID_SET) {
	    snprintf(client_uid_string + slen,
	             sizeof(client_uid_string) - slen,
	             "gid=%ld ", (long) lcc->egid);
	    slen = strlen(client_uid_string);
    }

	if (lcc->fieldsSet & LCC_PID_SET) {
	    snprintf(client_uid_string + slen,
	             sizeof(client_uid_string) - slen,
	             "pid=%ld ", (long) lcc->pid);
	    slen = strlen(client_uid_string);
	}

	if (lcc->fieldsSet & LCC_ZID_SET) {
	    snprintf(client_uid_string + slen,
	            sizeof(client_uid_string) - slen,
	            "zoneid=%ld ", (long) lcc->zoneid);
	    slen = strlen(client_uid_string);
	}

	snprintf(client_uid_string + slen, sizeof(client_uid_string) - slen, ")");
	FreeLocalClientCreds(lcc);
    }
    else {
	client_uid_string[0] = '\0';
    }

    if (proto_n)
	AuditF("client %d %s from %s%s\n  Auth name: %.*s ID: %d\n",
	       client->index, letin ? "connected" : "rejected", addr,
	       client_uid_string, (int)proto_n, auth_proto, auth_id);
    else 
	AuditF("client %d %s from %s%s\n",
	       client->index, letin ? "connected" : "rejected", addr,
	       client_uid_string);
}

XID
AuthorizationIDOfClient(ClientPtr client)
{
    if (client->osPrivate)
	return ((OsCommPtr)client->osPrivate)->auth_id;
    else
	return None;
}


/*****************************************************************
 * ClientAuthorized
 *
 *    Sent by the client at connection setup:
 *                typedef struct _xConnClientPrefix {
 *                   CARD8	byteOrder;
 *                   BYTE	pad;
 *                   CARD16	majorVersion, minorVersion;
 *                   CARD16	nbytesAuthProto;    
 *                   CARD16	nbytesAuthString;   
 *                 } xConnClientPrefix;
 *
 *     	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(ClientPtr client, 
    unsigned int proto_n, char *auth_proto, 
    unsigned int string_n, char *auth_string)
{
    OsCommPtr 		priv;
    Xtransaddr		*from = NULL;
    int 		family;
    int			fromlen;
    XID	 		auth_id;
    char	 	*reason = NULL;
    XtransConnInfo	trans_conn;

    priv = (OsCommPtr)client->osPrivate;
    trans_conn = priv->trans_conn;

    auth_id = CheckAuthorization (proto_n, auth_proto,
				  string_n, auth_string, client, &reason);

    if (auth_id == (XID) ~0L)
    {
	if (
#ifdef XCSECURITY	    
	    (proto_n == 0 ||
	    strncmp (auth_proto, XSecurityAuthorizationName, proto_n) != 0) &&
#endif
	    _XSERVTransGetPeerAddr (trans_conn,
	        &family, &fromlen, &from) != -1)
	{
	    if (
		InvalidHost ((struct sockaddr *) from, fromlen, client))
		AuthAudit(client, FALSE, (struct sockaddr *) from,
			  fromlen, proto_n, auth_proto, auth_id);
	    else
	    {
		auth_id = (XID) 0;
		if (auditTrailLevel > 1)
		    AuthAudit(client, TRUE,
			(struct sockaddr *) from, fromlen,
			proto_n, auth_proto, auth_id);
	    }

	    free ((char *) from);
	}

	if (auth_id == (XID) ~0L) {
	    if (reason)
		return reason;
	    else
		return "Client is not authorized to connect to Server";
	}
    }
    else if (auditTrailLevel > 1)
    {
	if (_XSERVTransGetPeerAddr (trans_conn,
	    &family, &fromlen, &from) != -1)
	{
	    AuthAudit(client, TRUE, (struct sockaddr *) from, fromlen,
		      proto_n, auth_proto, auth_id);

	    free ((char *) from);
	}
    }
    priv->auth_id = auth_id;
    priv->conn_time = 0;

#ifdef XDMCP
    /* indicate to Xdmcp protocol that we've opened new client */
    XdmcpOpenDisplay(priv->fd);
#endif /* XDMCP */
    /* 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 *)NULL);
}

static ClientPtr
AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time)
{
    OsCommPtr	oc;
    ClientPtr	client;
    
    if (
	fd >= lastfdesc
	)
	return NullClient;
    oc = (OsCommPtr)malloc(sizeof(OsCommRec));
    if (!oc)
	return NullClient;
    oc->trans_conn = trans_conn;
    oc->fd = fd;
    oc->input = (ConnectionInputPtr)NULL;
    oc->output = (ConnectionOutputPtr)NULL;
    oc->auth_id = None;
    oc->conn_time = conn_time;
    if (!(client = NextAvailableClient((void *)oc)))
    {
	free (oc);
	return NullClient;
    }
    client->local = ComputeLocalClient(client);
    {
	ConnectionTranslation[fd] = client->index;
	if (GrabInProgress)
	{
	    FD_SET(fd, &SavedAllClients);
	    FD_SET(fd, &SavedAllSockets);
	}
	else
	{
	    FD_SET(fd, &AllClients);
	    FD_SET(fd, &AllSockets);
	}
    }

#ifdef DEBUG
    ErrorF("AllocNewConnection: client index = %d, socket fd = %d\n",
	   client->index, fd);
#endif

    return client;
}

/*****************
 * EstablishNewConnections
 *    If anyone is waiting on listened sockets, accept them.
 *    Returns a mask with indices of new clients.  Updates AllClients
 *    and AllSockets.
 *****************/

static Bool
EstablishNewConnections(ClientPtr clientUnused, void * closure)
{
    int curconn = (int) (intptr_t) closure;
    int newconn;       /* fd of new client */
    CARD32 connect_time;
    int i;
    ClientPtr client;
    OsCommPtr oc;
    XtransConnInfo trans_conn, new_trans_conn;
    int status;

    connect_time = GetTimeInMillis();
    /* kill off stragglers */
    for (i=1; i<currentMaxClients; i++)
    {
	if ((client = clients[i]))
	{
	    oc = (OsCommPtr)(client->osPrivate);
	    if ((oc && (oc->conn_time != 0) &&
		(connect_time - oc->conn_time) >= TimeOutValue) || 
		(client->noClientException != Success && !client->clientGone))
		CloseDownClient(client);     
	}
    }
    if ((trans_conn = lookup_trans_conn(curconn)) == NULL)
	return TRUE;

    if ((new_trans_conn = _XSERVTransAccept(trans_conn, &status)) == NULL)
	return TRUE;

    newconn = _XSERVTransGetConnectionNumber(new_trans_conn);

    if (newconn < lastfdesc) {
	int clientid;

	clientid = ConnectionTranslation[newconn];
	if (clientid && (client = clients[clientid]))
	    CloseDownClient(client);
    }

    _XSERVTransSetOption(new_trans_conn, TRANS_NONBLOCKING, 1);

    if (trans_conn->flags & TRANS_NOXAUTH)
        new_trans_conn->flags = new_trans_conn->flags | TRANS_NOXAUTH;

    if (!AllocNewConnection(new_trans_conn, newconn, connect_time)) {
	ErrorConnMax(new_trans_conn);
     }

    return TRUE;
}

static void
QueueNewConnections(int fd, int ready, void *data)
{
    QueueWorkProc(EstablishNewConnections, NULL, (void *) (intptr_t) fd);
}

#define NOROOM "Maximum number of clients reached"

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

static void
ConnMaxNotify(int fd, int events, void *data)
{
    XtransConnInfo trans_conn = data;
    char order = 0;

    /* try to read the byte-order of the connection */
    (void)_XSERVTransRead(trans_conn, &order, 1);
    if (order == 'l' || order == 'B' || order == 'r' || order == 'R')
    {

	xConnSetupPrefix csp;
	char pad[3] = { 0, 0, 0 };
	int whichbyte = 1;
	struct iovec iov[3];

	csp.success = xFalse;
	csp.lengthReason = sizeof(NOROOM) - 1;
	csp.length = (sizeof(NOROOM) + 2) >> 2;
	csp.majorVersion = X_PROTOCOL;
	csp.minorVersion = X_PROTOCOL_REVISION;
	if (((*(char *) &whichbyte) && (order == 'B' || order == 'R')) ||
	    (!(*(char *) &whichbyte) && (order == 'l' || order == 'r')))
	{
	    swaps(&csp.majorVersion);
	    swaps(&csp.minorVersion);
	    swaps(&csp.length);
	}
	iov[0].iov_len = sz_xConnSetupPrefix;
	iov[0].iov_base = (char *) &csp;
	iov[1].iov_len = csp.lengthReason;
	iov[1].iov_base = NOROOM;
	iov[2].iov_len = (4 - (csp.lengthReason & 3)) & 3;
	iov[2].iov_base = pad;
	(void)_XSERVTransWritev(trans_conn, iov, 3);
    }
    RemoveNotifyFd(trans_conn->fd);
    _XSERVTransClose(trans_conn);
}

static void
ErrorConnMax(XtransConnInfo trans_conn)
{
    if (!SetNotifyFd(trans_conn->fd, ConnMaxNotify, X_NOTIFY_READ, trans_conn))
	_XSERVTransClose(trans_conn);
}

/************
 *   CloseDownFileDescriptor:
 *     Remove this file descriptor and it's I/O buffers, etc.
 ************/

static void
CloseDownFileDescriptor(OsCommPtr oc)
{
    int connection = oc->fd;

    if (oc->trans_conn) {
	_XSERVTransDisconnect(oc->trans_conn);
	_XSERVTransClose(oc->trans_conn);
    }
    FreeOsBuffers(oc);
    free(oc);
    ConnectionTranslation[connection] = 0;
    FD_CLR(connection, &AllSockets);
    FD_CLR(connection, &AllClients);
    FD_CLR(connection, &ClientsWithInput);
    FD_CLR(connection, &GrabImperviousClients);
    if (GrabInProgress)
    {
	FD_CLR(connection, &SavedAllSockets);
	FD_CLR(connection, &SavedAllClients);
	FD_CLR(connection, &SavedClientsWithInput);
    }
    FD_CLR(connection, &ClientsWriteBlocked);
    if (!XFD_ANYSET(&ClientsWriteBlocked) && NumNotifyWriteFd == 0)
	AnyWritesPending = FALSE;
    FD_CLR(connection, &OutputPending);
}

/*****************
 * CheckConnections
 *    Some connection has died, go find which one and shut it down 
 *    The file descriptor has been closed, but is still in AllClients.
 *    If would truly be wonderful if select() would put the bogus
 *    file descriptors in the exception mask, but nooooo.  So we have
 *    to check each and every socket individually.
 *****************/

void
CheckConnections(void)
{
    fd_mask		mask;
    fd_set		tmask; 
    int			curclient, curoff;
    int			i;
    struct timeval	notime;
    int r;

    notime.tv_sec = 0;
    notime.tv_usec = 0;

    for (i=0; i<howmany(XFD_SETSIZE, NFDBITS); i++)
    {
	mask = AllClients.fds_bits[i];
        while (mask)
    	{
	    curoff = ffs (mask) - 1;
	    curclient = curoff + (i * (sizeof(fd_mask)*8));
            FD_ZERO(&tmask);
            FD_SET(curclient, &tmask);
            r = Select (curclient + 1, &tmask, NULL, NULL, &notime);
            if (r < 0)
		CloseDownClient(clients[ConnectionTranslation[curclient]]);
	    mask &= ~((fd_mask)1 << curoff);
	}
    }	
}


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

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

    if (FlushCallback)
	CallCallbacks(&FlushCallback, client);

    if (oc->output && oc->output->count)
	FlushClient(client, oc, (char *)NULL, 0);
#ifdef XDMCP
    XdmcpCloseDisplay(oc->fd);
#endif
    CloseDownFileDescriptor(oc);
    client->osPrivate = (void *)NULL;
    if (auditTrailLevel > 1)
	AuditF("client %d disconnected\n", client->index);
}

struct notify_fd {
    struct xorg_list list;
    int fd;
    int mask;
    NotifyFdProcPtr notify;
    void *data;
};

static struct xorg_list notify_fds;

void
InitNotifyFds(void)
{
    struct notify_fd *s, *next;
    static int been_here;

    if (been_here)
	xorg_list_for_each_entry_safe(s, next, &notify_fds, list)
	     RemoveNotifyFd(s->fd);

    xorg_list_init(&notify_fds);
    NumNotifyWriteFd = 0;
    been_here = 1;
}

/*****************
 * SetNotifyFd
 *    Registers a callback to be invoked when the specified
 *    file descriptor becomes readable.
 *****************/

Bool
SetNotifyFd(int fd, NotifyFdProcPtr notify, int mask, void *data)
{
    struct notify_fd *n;
    int changes;

    xorg_list_for_each_entry(n, &notify_fds, list)
	if (n->fd == fd)
	    break;

    if (&n->list == &notify_fds) {
	if (mask == 0)
	    return TRUE;

	n = calloc(1, sizeof (struct notify_fd));
	if (!n)
	    return FALSE;
	n->fd = fd;
	xorg_list_add(&n->list, &notify_fds);
    }

    changes = n->mask ^ mask;

    if (changes & X_NOTIFY_READ) {
	if (mask & X_NOTIFY_READ) {
	    FD_SET(fd, &NotifyReadFds);
	    FD_SET(fd, &AllSockets);
	    if (GrabInProgress)
		FD_SET(fd, &SavedAllSockets);
	} else {
	    FD_CLR(fd, &AllSockets);
	    if (GrabInProgress)
		FD_CLR(fd, &SavedAllSockets);
	     FD_CLR(fd, &NotifyReadFds);
	}
    }

    if (changes & X_NOTIFY_WRITE) {
	if (mask & X_NOTIFY_WRITE) {
	    FD_SET(fd, &NotifyWriteFds);
	    if (!NumNotifyWriteFd++)
		AnyWritesPending = TRUE;
	} else {
	    FD_CLR(fd, &NotifyWriteFds);
	    if (!--NumNotifyWriteFd)
		if (!XFD_ANYSET(&ClientsWriteBlocked))
		    AnyWritesPending = FALSE;
	}
    }

    if (mask == 0) {
	xorg_list_del(&n->list);
	free(n);
    } else {
	n->mask = mask;
	n->data = data;
	n->notify = notify;
    }

    return TRUE;
}

/*****************
 * HandlNotifyFds
 *    A WorkProc to be called when any of the registered
 *    file descriptors are readable.
 *****************/

void
HandleNotifyFds(void)
{
    struct notify_fd *n, *next;

    xorg_list_for_each_entry_safe(n, next, &notify_fds, list) {
	int ready = 0;
	if ((n->mask & X_NOTIFY_READ) && FD_ISSET(n->fd, &LastSelectMask))
	    ready |= X_NOTIFY_READ;
	if ((n->mask & X_NOTIFY_WRITE) & FD_ISSET(n->fd, &LastSelectWriteMask))
	    ready |= X_NOTIFY_WRITE;
	if (ready != 0)
	    n->notify(n->fd, ready, n->data);
    }
}

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

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

    if (! GrabInProgress)
    {
	XFD_COPYSET(&ClientsWithInput, &SavedClientsWithInput);
	XFD_ANDSET(&ClientsWithInput,
		       &ClientsWithInput, &GrabImperviousClients);
	if (FD_ISSET(connection, &SavedClientsWithInput))
	{
	    FD_CLR(connection, &SavedClientsWithInput);
	    FD_SET(connection, &ClientsWithInput);
	}
	XFD_UNSET(&SavedClientsWithInput, &GrabImperviousClients);
	XFD_COPYSET(&AllSockets, &SavedAllSockets);
	XFD_COPYSET(&AllClients, &SavedAllClients);
	XFD_UNSET(&AllSockets, &AllClients);
	XFD_ANDSET(&AllClients, &AllClients, &GrabImperviousClients);
	FD_SET(connection, &AllClients);
	XFD_ORSET(&AllSockets, &AllSockets, &AllClients);
	GrabInProgress = client->index;
    }
}

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

void
ListenToAllClients(void)
{
    if (GrabInProgress)
    {
	XFD_ORSET(&AllSockets, &AllSockets, &SavedAllSockets);
	XFD_ORSET(&AllClients, &AllClients, &SavedAllClients);
	XFD_ORSET(&ClientsWithInput, &ClientsWithInput, &SavedClientsWithInput);
	GrabInProgress = 0;
    }	
}

/****************
 * IgnoreClient
 *    Removes one client from input masks.
 *    Must have cooresponding call to AttendClient.
 ****************/

void
IgnoreClient (ClientPtr client)
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;
    int connection = oc->fd;

    isItTimeToYield = TRUE;
    if (!GrabInProgress || FD_ISSET(connection, &AllClients))
    {
    	if (FD_ISSET (connection, &ClientsWithInput))
	    FD_SET(connection, &IgnoredClientsWithInput);
    	else
	    FD_CLR(connection, &IgnoredClientsWithInput);
    	FD_CLR(connection, &ClientsWithInput);
    	FD_CLR(connection, &AllSockets);
    	FD_CLR(connection, &AllClients);
	FD_CLR(connection, &LastSelectMask);
    }
    else
    {
    	if (FD_ISSET (connection, &SavedClientsWithInput))
	    FD_SET(connection, &IgnoredClientsWithInput);
    	else
	    FD_CLR(connection, &IgnoredClientsWithInput);
	FD_CLR(connection, &SavedClientsWithInput);
	FD_CLR(connection, &SavedAllSockets);
	FD_CLR(connection, &SavedAllClients);
    }
}

/****************
 * AttendClient
 *    Adds one client back into the input masks.
 ****************/

void
AttendClient (ClientPtr client)
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;
    int connection = oc->fd;
    if (!GrabInProgress || GrabInProgress == client->index ||
	FD_ISSET(connection, &GrabImperviousClients))
    {
    	FD_SET(connection, &AllClients);
    	FD_SET(connection, &AllSockets);
	FD_SET(connection, &LastSelectMask);
    	if (FD_ISSET (connection, &IgnoredClientsWithInput))
	    FD_SET(connection, &ClientsWithInput);
    }
    else
    {
	FD_SET(connection, &SavedAllClients);
	FD_SET(connection, &SavedAllSockets);
	if (FD_ISSET(connection, &IgnoredClientsWithInput))
	    FD_SET(connection, &SavedClientsWithInput);
    }
}

/* make client impervious to grabs; assume only executing client calls this */

void
MakeClientGrabImpervious(ClientPtr client)
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;
    int connection = oc->fd;

    FD_SET(connection, &GrabImperviousClients);

    if (ServerGrabCallback)
    {
	ServerGrabInfoRec grabinfo;
	grabinfo.client = client;
	grabinfo.grabstate  = CLIENT_IMPERVIOUS;
	CallCallbacks(&ServerGrabCallback, &grabinfo);
    }
}

/* make client pervious to grabs; assume only executing client calls this */

void
MakeClientGrabPervious(ClientPtr client)
{
    OsCommPtr oc = (OsCommPtr)client->osPrivate;
    int connection = oc->fd;

    FD_CLR(connection, &GrabImperviousClients);
    if (GrabInProgress && (GrabInProgress != client->index))
    {
	if (FD_ISSET(connection, &ClientsWithInput))
	{
	    FD_SET(connection, &SavedClientsWithInput);
	    FD_CLR(connection, &ClientsWithInput);
	}
	FD_CLR(connection, &AllSockets);
	FD_CLR(connection, &AllClients);
	isItTimeToYield = TRUE;
    }

    if (ServerGrabCallback)
    {
	ServerGrabInfoRec grabinfo;
	grabinfo.client = client;
	grabinfo.grabstate  = CLIENT_PERVIOUS;
	CallCallbacks(&ServerGrabCallback, &grabinfo);
    }
}

