aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/os
diff options
context:
space:
mode:
Diffstat (limited to 'nx-X11/programs/Xserver/os')
-rw-r--r--nx-X11/programs/Xserver/os/Imakefile.NX.original235
-rw-r--r--nx-X11/programs/Xserver/os/Imakefile.X.original200
-rw-r--r--nx-X11/programs/Xserver/os/WaitFor.c.NX.original882
-rw-r--r--nx-X11/programs/Xserver/os/WaitFor.c.X.original701
-rw-r--r--nx-X11/programs/Xserver/os/auth.c.NX.original608
-rw-r--r--nx-X11/programs/Xserver/os/auth.c.X.original400
-rw-r--r--nx-X11/programs/Xserver/os/connection.c.NX.original1424
-rw-r--r--nx-X11/programs/Xserver/os/connection.c.X.original1385
-rw-r--r--nx-X11/programs/Xserver/os/log.c.NX.original716
-rw-r--r--nx-X11/programs/Xserver/os/log.c.X.original633
-rw-r--r--nx-X11/programs/Xserver/os/oscolor.c.NX.original483
-rw-r--r--nx-X11/programs/Xserver/os/oscolor.c.X.original303
-rw-r--r--nx-X11/programs/Xserver/os/utils.c.NX.original2440
-rw-r--r--nx-X11/programs/Xserver/os/utils.c.X.original2296
-rw-r--r--nx-X11/programs/Xserver/os/xdmcp.c.NX.original1710
-rw-r--r--nx-X11/programs/Xserver/os/xdmcp.c.X.original1681
-rw-r--r--nx-X11/programs/Xserver/os/xprintf.c.NX.original163
-rw-r--r--nx-X11/programs/Xserver/os/xprintf.c.X.original104
18 files changed, 0 insertions, 16364 deletions
diff --git a/nx-X11/programs/Xserver/os/Imakefile.NX.original b/nx-X11/programs/Xserver/os/Imakefile.NX.original
deleted file mode 100644
index 22be06074..000000000
--- a/nx-X11/programs/Xserver/os/Imakefile.NX.original
+++ /dev/null
@@ -1,235 +0,0 @@
-XCOMM $Xorg: Imakefile,v 1.3 2000/08/17 19:53:40 cpqbld Exp $
-
-
-
-
-XCOMM $XFree86: xc/programs/Xserver/os/Imakefile,v 3.40 2003/09/09 03:20:41 dawes Exp $
-
-/**************************************************************************/
-/* */
-/* Copyright (c) 2001, 2011 NoMachine, http://www.nomachine.com/. */
-/* */
-/* NX-X11, NX protocol compression and NX extensions to this software */
-/* are copyright of NoMachine. Redistribution and use of the present */
-/* software is allowed according to terms specified in the file LICENSE */
-/* which comes in the source distribution. */
-/* */
-/* Check http://www.nomachine.com/licensing.html for applicability. */
-/* */
-/* NX and NoMachine are trademarks of Medialogic S.p.A. */
-/* */
-/* All rights reserved. */
-/* */
-/**************************************************************************/
-
-#include <Server.tmpl>
-
-/*
- * If you have any extra files to be put into the library, define them here.
- */
-
-#if NXLibraries
-
-NX_INCLUDES = -I../../../../nxcomp
-
-NX_DEFINES = -DNX_TRANS_SOCKET \
- -DNX_TRANS_AUTH \
- -DNX_TRANS_FOPEN \
- -DNX_TRANS_SLEEP \
- -DNX_TRANS_EXIT \
- -DNX_TRANS_WAKEUP=1000
-
-# -DNX_TRANS_WARN \
-# -DNX_TRANS_INFO \
-# -DNX_TRANS_TEST \
-# -DNX_TRANS_DEBUG \
-
-#endif
-
-/*
- * do not modify the following two definitions
- */
-
-#ifndef OtherSources
-#define OtherSources
-#endif
-
-#ifndef OtherObjects
-#define OtherObjects
-#endif
-
-#if HasXdmAuth
-XDMAUTHDEFS = -DHASXDMAUTH
-XDMAUTHOBJS = xdmauth.o
-XDMAUTHSRCS = xdmauth.c
-#else
-XDMAUTHDEFS =
-XDMAUTHOBJS =
-XDMAUTHSCRS =
-#endif
-
-#if HasSecureRPC
-RPCDEFS = -DSECURE_RPC
-RPCOBJS = rpcauth.o
-RPCSRCS = rpcauth.c
-#else
-RPCDEFS =
-RPCOBJS =
-RPCSRCS =
-#endif
-
-#if HasKrb5
-KRB5OBJS = k5auth.o k5encode.o
-KRB5SRCS = k5auth.c k5encode.c
-#endif
-
-#if HasBSD44Sockets
- SOCK_DEFINES = -DBSD44SOCKETS
-#endif
-
-#if HasGetIfAddrs
- IFADDRS_DEFINES = -DHAS_GETIFADDRS
-#endif
-
-#if BuildLBX
- LBX_SRCS = lbxio.c
- LBX_OBJS = lbxio.o
-#else
- LBX_SRCS =
- LBX_OBJS =
-#endif
-
-#if !defined(DDXOsColor)
-COLOR_SRCS=oscolor.c
-COLOR_OBJS=oscolor.o
-#endif
-
-#if UseInternalMalloc
-MALLOC_SRCS=xalloc.c
-MALLOC_OBJS=xalloc.o
-#endif
-
-#if !HasSnprintf
-SNPRINTF_SRCS = snprintf.c
-SNPRINTF_OBJS = snprintf.o
-#endif
-
-#if !HasStrlcat
-STRLCAT_SRCS = strlcat.c strlcpy.c
-STRLCAT_OBJS = strlcat.o strlcpy.o
-#endif
-
-#if HasGetpeerucred
-GETPEER_DEFINES = -DHAS_GETPEERUCRED
-#else
-# if HasGetpeereid
-GETPEER_DEFINES = -DHAS_GETPEEREID
-# endif
-#endif
-
-BOOTSTRAPCFLAGS =
- SRCS = WaitFor.c access.c connection.c io.c $(COLOR_SRCS) \
- osinit.c utils.c log.c auth.c mitauth.c secauth.c \
- $(XDMAUTHSRCS) $(RPCSRCS) $(KRB5SRCS) xdmcp.c OtherSources \
- transport.c $(SNPRINTF_SRCS) $(STRLCAT_SRCS) \
- $(MALLOC_SRCS) $(LBX_SRCS) xprintf.c
- OBJS = WaitFor.o access.o connection.o io.o $(COLOR_OBJS) \
- osinit.o utils.o log.o auth.o mitauth.o secauth.o \
- $(XDMAUTHOBJS) $(RPCOBJS) $(KRB5OBJS) xdmcp.o OtherObjects \
- transport.o $(SNPRINTF_OBJS) $(STRLCAT_OBJS) \
- $(MALLOC_OBJS) $(LBX_OBJS) xprintf.o
-
-#if SpecialMalloc
- MEM_DEFINES = -DSPECIAL_MALLOC
-#endif /* SpecialMalloc */
-#if UseInternalMalloc
- MEM_DEFINES = -DINTERNAL_MALLOC
-#endif
-#if UseMemLeak
- MEM_DEFINES = -DMEMBUG
-#endif
-#if UseRgbTxt
- RGB_DEFINES = -DUSE_RGB_TXT
-#endif
- DBM_DEFINES = NdbmDefines
- ADM_DEFINES = -DADMPATH=\"$(ADMDIR)/X\%smsgs\"
- XDMCP_DEFINES = ServerXdmcpDefines
- KRB5_DEFINES = Krb5Defines
- XALLOC_DEFINES = XallocDefines
- ERROR_DEFINES = ServerErrorDefines
-#if HasPam && HasPamMisc
- PAM_DEFINES = -DUSE_PAM
-#endif
- DEFINES = -DXSERV_t -DTRANS_SERVER $(CONNECTION_FLAGS) $(MEM_DEFINES) \
- $(XDMAUTHDEFS) $(RPCDEFS) $(SIGNAL_DEFINES) $(OS_DEFINES) \
- $(KRB5_DEFINES) $(RGB_DEFINES) $(GETPEER_DEFINES) \
- $(RANDOM_DEFINES) $(BUGMSG) $(XTRANS_FAILDEFINES) $(NX_DEFINES)
- INCLUDES = -I. -I../include -I$(XINCLUDESRC) -I$(EXTINCSRC) \
- -I$(SERVERSRC)/Xext -I$(FONTINCSRC) -I$(SERVERSRC)/render \
- -I$(TOP)/lib/Xau -I../lbx -I../Xprint Krb5Includes $(NX_INCLUDES)
- DEPEND_DEFINES = $(DBM_DEFINES) $(XDMCP_DEFINES) $(EXT_DEFINES) \
- $(TRANS_INCLUDES) $(CONNECTION_FLAGS) $(GETPEER_DEFINES) \
- DependDefines
- LINTLIBS = ../dix/llib-ldix.ln
-
-#ifdef NEED_ALLOCA_FROM_LIBPW
- PWLIB = /lib/libPW.a
-#endif /* NEED_ALLOCA_FROM_LIBPW */
-
-NormalLibraryObjectRule()
-NormalLibraryTarget(os,$(OBJS))
-LintLibraryTarget(os,$(SRCS))
-NormalLintTarget($(SRCS))
-
-#ifdef NEED_ALLOCA_FROM_LIBPW
-XCOMM
-XCOMM And this one is to get the version of alloca that lives in /lib/libPW.a
-XCOMM without getting all of the rest of the stuff in there.
-XCOMM
-alloca.o: $(PWLIB)
- rm -f alloca.o
- ar x $(PWLIB) alloca.o
-#endif /* NEED_ALLOCA_FROM_LIBPW */
-
-SpecialCObjectRule(access,$(ICONFIGFILES),$(XDMCP_DEFINES) $(SOCK_DEFINES) $(IFADDRS_DEFINES))
-SpecialCObjectRule(auth,$(ICONFIGFILES),$(XDMCP_DEFINES))
-SpecialCObjectRule(xdmauth,$(ICONFIGFILES),$(XDMCP_DEFINES))
-SpecialCObjectRule(xdmcp,$(ICONFIGFILES),$(SOCK_DEFINES) $(XDMCP_DEFINES))
-SpecialCObjectRule(connection,$(ICONFIGFILES),$(SOCK_DEFINES) $(XDMCP_DEFINES))
-SpecialCObjectRule(transport,$(ICONFIGFILES),$(TRANS_INCLUDES) $(CONN_DEFINES) $(SOCK_DEFINES))
-LinkSourceFile(transport.c,$(TRANSCOMMSRC))
-SpecialCObjectRule(osinit,$(ICONFIGFILES),$(ADM_DEFINES))
-SpecialCObjectRule(WaitFor,$(ICONFIGFILES),$(EXT_DEFINES))
-SpecialCObjectRule(io,$(ICONFIGFILES),$(EXT_DEFINES))
-#if BuildLBX
-SpecialCObjectRule(lbxio,$(ICONFIGFILES),$(EXT_DEFINES))
-#endif
-SpecialCObjectRule(utils,$(ICONFIGFILES),$(XDMCP_DEFINES) $(EXT_DEFINES) $(ERROR_DEFINES) $(PAM_DEFINES))
-SpecialCObjectRule(xalloc,$(ICONFIGFILES),$(XALLOC_DEFINES))
-#if defined(SparcArchitecture) && HasGcc && !HasGcc2
-oscolor.o: oscolor.c $(ICONFIGFILES)
- $(RM) $@
- cc -c $(DBM_DEFINES) $(CDEBUGFLAGS) $(ALLDEFINES) $*.c
-#else
-SpecialCObjectRule(oscolor,$(ICONFIGFILES),$(DBM_DEFINES))
-#endif
-
-#if HasKrb5
-LinkSourceFile(k5encode.c,$(XAUTHSRC))
-#endif
-
-#if !HasSnprintf
-LinkSourceFile(snprintf.c,$(LIBSRC)/misc)
-#endif
-
-#if !HasStrlcat
-LinkSourceFile(strlcat.c,$(LIBSRC)/misc)
-LinkSourceFile(strlcpy.c,$(LIBSRC)/misc)
-#endif
-
-#if DoLoadableServer
-AllTarget(libcwrapper.o)
-ObjectFromSpecialSource(libcwrapper,$(XF86OSSRC)/shared/libc_wrapper,-DSELF_CONTAINED_WRAPPER)
-#endif
-
-DependTarget()
diff --git a/nx-X11/programs/Xserver/os/Imakefile.X.original b/nx-X11/programs/Xserver/os/Imakefile.X.original
deleted file mode 100644
index c24a016dc..000000000
--- a/nx-X11/programs/Xserver/os/Imakefile.X.original
+++ /dev/null
@@ -1,200 +0,0 @@
-XCOMM $Xorg: Imakefile,v 1.3 2000/08/17 19:53:40 cpqbld Exp $
-
-
-
-
-XCOMM $XFree86: xc/programs/Xserver/os/Imakefile,v 3.40 2003/09/09 03:20:41 dawes Exp $
-
-#include <Server.tmpl>
-
-/*
- * If you have any extra files to be put into the library, define them here.
- */
-
-/*
- * do not modify the following two definitions
- */
-
-#ifndef OtherSources
-#define OtherSources
-#endif
-
-#ifndef OtherObjects
-#define OtherObjects
-#endif
-
-#if HasXdmAuth
-XDMAUTHDEFS = -DHASXDMAUTH
-XDMAUTHOBJS = xdmauth.o
-XDMAUTHSRCS = xdmauth.c
-#else
-XDMAUTHDEFS =
-XDMAUTHOBJS =
-XDMAUTHSCRS =
-#endif
-
-#if HasSecureRPC
-RPCDEFS = -DSECURE_RPC
-RPCOBJS = rpcauth.o
-RPCSRCS = rpcauth.c
-#else
-RPCDEFS =
-RPCOBJS =
-RPCSRCS =
-#endif
-
-#if HasKrb5
-KRB5OBJS = k5auth.o k5encode.o
-KRB5SRCS = k5auth.c k5encode.c
-#endif
-
-#if HasBSD44Sockets
- SOCK_DEFINES = -DBSD44SOCKETS
-#endif
-
-#if HasGetIfAddrs
- IFADDRS_DEFINES = -DHAS_GETIFADDRS
-#endif
-
-#if BuildLBX
- LBX_SRCS = lbxio.c
- LBX_OBJS = lbxio.o
-#else
- LBX_SRCS =
- LBX_OBJS =
-#endif
-
-#if !defined(DDXOsColor)
-COLOR_SRCS=oscolor.c
-COLOR_OBJS=oscolor.o
-#endif
-
-#if UseInternalMalloc
-MALLOC_SRCS=xalloc.c
-MALLOC_OBJS=xalloc.o
-#endif
-
-#if !HasSnprintf
-SNPRINTF_SRCS = snprintf.c
-SNPRINTF_OBJS = snprintf.o
-#endif
-
-#if !HasStrlcat
-STRLCAT_SRCS = strlcat.c strlcpy.c
-STRLCAT_OBJS = strlcat.o strlcpy.o
-#endif
-
-#if HasGetpeerucred
-GETPEER_DEFINES = -DHAS_GETPEERUCRED
-#else
-# if HasGetpeereid
-GETPEER_DEFINES = -DHAS_GETPEEREID
-# endif
-#endif
-
-BOOTSTRAPCFLAGS =
- SRCS = WaitFor.c access.c connection.c io.c $(COLOR_SRCS) \
- osinit.c utils.c log.c auth.c mitauth.c secauth.c \
- $(XDMAUTHSRCS) $(RPCSRCS) $(KRB5SRCS) xdmcp.c OtherSources \
- transport.c $(SNPRINTF_SRCS) $(STRLCAT_SRCS) \
- $(MALLOC_SRCS) $(LBX_SRCS) xprintf.c
- OBJS = WaitFor.o access.o connection.o io.o $(COLOR_OBJS) \
- osinit.o utils.o log.o auth.o mitauth.o secauth.o \
- $(XDMAUTHOBJS) $(RPCOBJS) $(KRB5OBJS) xdmcp.o OtherObjects \
- transport.o $(SNPRINTF_OBJS) $(STRLCAT_OBJS) \
- $(MALLOC_OBJS) $(LBX_OBJS) xprintf.o
-
-#if SpecialMalloc
- MEM_DEFINES = -DSPECIAL_MALLOC
-#endif /* SpecialMalloc */
-#if UseInternalMalloc
- MEM_DEFINES = -DINTERNAL_MALLOC
-#endif
-#if UseMemLeak
- MEM_DEFINES = -DMEMBUG
-#endif
-#if UseRgbTxt
- RGB_DEFINES = -DUSE_RGB_TXT
-#endif
- DBM_DEFINES = NdbmDefines
- ADM_DEFINES = -DADMPATH=\"$(ADMDIR)/X\%smsgs\"
- XDMCP_DEFINES = ServerXdmcpDefines
- KRB5_DEFINES = Krb5Defines
- XALLOC_DEFINES = XallocDefines
- ERROR_DEFINES = ServerErrorDefines
-#if HasPam && HasPamMisc
- PAM_DEFINES = -DUSE_PAM
-#endif
- DEFINES = -DXSERV_t -DTRANS_SERVER $(CONNECTION_FLAGS) $(MEM_DEFINES) \
- $(XDMAUTHDEFS) $(RPCDEFS) $(SIGNAL_DEFINES) $(OS_DEFINES) \
- $(KRB5_DEFINES) $(RGB_DEFINES) $(GETPEER_DEFINES) \
- $(RANDOM_DEFINES) $(BUGMSG) $(XTRANS_FAILDEFINES)
- INCLUDES = -I. -I../include -I$(XINCLUDESRC) -I$(EXTINCSRC) \
- -I$(SERVERSRC)/Xext -I$(FONTINCSRC) -I$(SERVERSRC)/render \
- -I$(TOP)/lib/Xau -I../lbx -I../Xprint Krb5Includes
- DEPEND_DEFINES = $(DBM_DEFINES) $(XDMCP_DEFINES) $(EXT_DEFINES) \
- $(TRANS_INCLUDES) $(CONNECTION_FLAGS) $(GETPEER_DEFINES) \
- DependDefines
- LINTLIBS = ../dix/llib-ldix.ln
-
-#ifdef NEED_ALLOCA_FROM_LIBPW
- PWLIB = /lib/libPW.a
-#endif /* NEED_ALLOCA_FROM_LIBPW */
-
-NormalLibraryObjectRule()
-NormalLibraryTarget(os,$(OBJS))
-LintLibraryTarget(os,$(SRCS))
-NormalLintTarget($(SRCS))
-
-#ifdef NEED_ALLOCA_FROM_LIBPW
-XCOMM
-XCOMM And this one is to get the version of alloca that lives in /lib/libPW.a
-XCOMM without getting all of the rest of the stuff in there.
-XCOMM
-alloca.o: $(PWLIB)
- rm -f alloca.o
- ar x $(PWLIB) alloca.o
-#endif /* NEED_ALLOCA_FROM_LIBPW */
-
-SpecialCObjectRule(access,$(ICONFIGFILES),$(XDMCP_DEFINES) $(SOCK_DEFINES) $(IFADDRS_DEFINES))
-SpecialCObjectRule(auth,$(ICONFIGFILES),$(XDMCP_DEFINES))
-SpecialCObjectRule(xdmauth,$(ICONFIGFILES),$(XDMCP_DEFINES))
-SpecialCObjectRule(xdmcp,$(ICONFIGFILES),$(SOCK_DEFINES) $(XDMCP_DEFINES))
-SpecialCObjectRule(connection,$(ICONFIGFILES),$(SOCK_DEFINES) $(XDMCP_DEFINES))
-SpecialCObjectRule(transport,$(ICONFIGFILES),$(TRANS_INCLUDES) $(CONN_DEFINES) $(SOCK_DEFINES))
-LinkSourceFile(transport.c,$(TRANSCOMMSRC))
-SpecialCObjectRule(osinit,$(ICONFIGFILES),$(ADM_DEFINES))
-SpecialCObjectRule(WaitFor,$(ICONFIGFILES),$(EXT_DEFINES))
-SpecialCObjectRule(io,$(ICONFIGFILES),$(EXT_DEFINES))
-#if BuildLBX
-SpecialCObjectRule(lbxio,$(ICONFIGFILES),$(EXT_DEFINES))
-#endif
-SpecialCObjectRule(utils,$(ICONFIGFILES),$(XDMCP_DEFINES) $(EXT_DEFINES) $(ERROR_DEFINES) $(PAM_DEFINES))
-SpecialCObjectRule(xalloc,$(ICONFIGFILES),$(XALLOC_DEFINES))
-#if defined(SparcArchitecture) && HasGcc && !HasGcc2
-oscolor.o: oscolor.c $(ICONFIGFILES)
- $(RM) $@
- cc -c $(DBM_DEFINES) $(CDEBUGFLAGS) $(ALLDEFINES) $*.c
-#else
-SpecialCObjectRule(oscolor,$(ICONFIGFILES),$(DBM_DEFINES))
-#endif
-
-#if HasKrb5
-LinkSourceFile(k5encode.c,$(XAUTHSRC))
-#endif
-
-#if !HasSnprintf
-LinkSourceFile(snprintf.c,$(LIBSRC)/misc)
-#endif
-
-#if !HasStrlcat
-LinkSourceFile(strlcat.c,$(LIBSRC)/misc)
-LinkSourceFile(strlcpy.c,$(LIBSRC)/misc)
-#endif
-
-#if DoLoadableServer
-AllTarget(libcwrapper.o)
-ObjectFromSpecialSource(libcwrapper,$(XF86OSSRC)/shared/libc_wrapper,-DSELF_CONTAINED_WRAPPER)
-#endif
-
-DependTarget()
diff --git a/nx-X11/programs/Xserver/os/WaitFor.c.NX.original b/nx-X11/programs/Xserver/os/WaitFor.c.NX.original
deleted file mode 100644
index 2ef474229..000000000
--- a/nx-X11/programs/Xserver/os/WaitFor.c.NX.original
+++ /dev/null
@@ -1,882 +0,0 @@
-/* $XFree86: xc/programs/Xserver/os/WaitFor.c,v 3.42 2003/10/16 01:33:35 dawes Exp $ */
-/***********************************************************
-
-Copyright 1987, 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 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.
-
-******************************************************************/
-
-/* $Xorg: WaitFor.c,v 1.4 2001/02/09 02:05:22 xorgcvs Exp $ */
-
-/**************************************************************************/
-/* */
-/* Copyright (c) 2001, 2011 NoMachine, http://www.nomachine.com/. */
-/* */
-/* NX-X11, NX protocol compression and NX extensions to this software */
-/* are copyright of NoMachine. Redistribution and use of the present */
-/* software is allowed according to terms specified in the file LICENSE */
-/* which comes in the source distribution. */
-/* */
-/* Check http://www.nomachine.com/licensing.html for applicability. */
-/* */
-/* NX and NoMachine are trademarks of Medialogic S.p.A. */
-/* */
-/* All rights reserved. */
-/* */
-/**************************************************************************/
-
-/*****************************************************************
- * OS Dependent input routines:
- *
- * WaitForSomething
- * TimerForce, TimerSet, TimerCheck, TimerFree
- *
- *****************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/Xos.h> /* for strings, fcntl, time */
-#include <errno.h>
-#include <stdio.h>
-#include <X11/X.h>
-#include "misc.h"
-
-#ifdef __UNIXOS2__
-#define select(n,r,w,x,t) os2PseudoSelect(n,r,w,x,t)
-#endif
-#include "osdep.h"
-#include <X11/Xpoll.h>
-#include "dixstruct.h"
-#include "opaque.h"
-#ifdef DPMSExtension
-#include "dpmsproc.h"
-#endif
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP)
-
-static unsigned long startTimeInMillis;
-
-#endif
-
-#ifdef WIN32
-/* Error codes from windows sockets differ from fileio error codes */
-#undef EINTR
-#define EINTR WSAEINTR
-#undef EINVAL
-#define EINVAL WSAEINVAL
-#undef EBADF
-#define EBADF WSAENOTSOCK
-/* Windows select does not set errno. Use GetErrno as wrapper for
- WSAGetLastError */
-#define GetErrno WSAGetLastError
-#else
-/* This is just a fallback to errno to hide the differences between unix and
- Windows in the code */
-#define GetErrno() errno
-#endif
-
-/* modifications by raphael */
-int
-mffs(fd_mask mask)
-{
- int i;
-
- if (!mask) return 0;
- i = 1;
- while (!(mask & 1))
- {
- i++;
- mask >>= 1;
- }
- return i;
-}
-
-#ifdef DPMSExtension
-#define DPMS_SERVER
-#include <X11/extensions/dpms.h>
-#endif
-
-#ifdef XTESTEXT1
-/*
- * defined in xtestext1dd.c
- */
-extern int playback_on;
-#endif /* XTESTEXT1 */
-
-struct _OsTimerRec {
- OsTimerPtr next;
- CARD32 expires;
- OsTimerCallback callback;
- pointer arg;
-};
-
-static void DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev);
-static OsTimerPtr timers = NULL;
-
-/*****************
- * WaitForSomething:
- * Make the server suspend until there is
- * 1. data from clients or
- * 2. input events available or
- * 3. ddx notices something of interest (graphics
- * queue ready, etc.) or
- * 4. clients that have buffered replies/events are ready
- *
- * If the time between INPUT events is
- * greater than ScreenSaverTime, the display is turned off (or
- * saved, depending on the hardware). So, WaitForSomething()
- * has to handle this also (that's why the select() has a timeout.
- * For more info on ClientsWithInput, see ReadRequestFromClient().
- * pClientsReady is an array to store ready client->index values into.
- *****************/
-
-int
-WaitForSomething(int *pClientsReady)
-{
- int i;
- struct timeval waittime, *wt;
- INT32 timeout = 0;
- fd_set clientsReadable;
- fd_set clientsWritable;
- int curclient;
- int selecterr;
- int nready;
- fd_set devicesReadable;
- CARD32 now = 0;
-#ifdef SMART_SCHEDULE
- Bool someReady = FALSE;
-#endif
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Got called.\n");
-#endif
-
- FD_ZERO(&clientsReadable);
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP)
-
- startTimeInMillis = GetTimeInMillis();
-
-#endif
-
- /* We need a while loop here to handle
- crashed connections and the screen saver timeout */
- while (1)
- {
- /* deal with any blocked jobs */
- if (workQueue)
- ProcessWorkQueue();
- if (XFD_ANYSET (&ClientsWithInput))
- {
-#ifdef SMART_SCHEDULE
- if (!SmartScheduleDisable)
- {
- someReady = TRUE;
- waittime.tv_sec = 0;
- waittime.tv_usec = 0;
- wt = &waittime;
- }
- else
-#endif
- {
- XFD_COPYSET (&ClientsWithInput, &clientsReadable);
- break;
- }
- }
-#ifdef SMART_SCHEDULE
- if (someReady)
- {
- XFD_COPYSET(&AllSockets, &LastSelectMask);
- XFD_UNSET(&LastSelectMask, &ClientsWithInput);
- }
- else
- {
-#endif
- wt = NULL;
- if (timers)
- {
- now = GetTimeInMillis();
- timeout = timers->expires - now;
- if (timeout < 0)
- timeout = 0;
- waittime.tv_sec = timeout / MILLI_PER_SECOND;
- waittime.tv_usec = (timeout % MILLI_PER_SECOND) *
- (1000000 / MILLI_PER_SECOND);
- wt = &waittime;
- }
- XFD_COPYSET(&AllSockets, &LastSelectMask);
-#ifdef SMART_SCHEDULE
- }
- SmartScheduleIdle = TRUE;
-#endif
- BlockHandler((pointer)&wt, (pointer)&LastSelectMask);
- if (NewOutputPending)
- FlushAllOutput();
-#ifdef XTESTEXT1
- /* XXX how does this interact with new write block handling? */
- if (playback_on) {
- wt = &waittime;
- XTestComputeWaitTime (&waittime);
- }
-#endif /* XTESTEXT1 */
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP)
-
- /*
- * If caller has marked the first element of pClientsReady[],
- * bail out of select after a short timeout. We need this to
- * let the NX agent remove the splash screen when the timeout
- * is expired. A better option would be to use the existing
- * screen-saver timeout but it can be modified by clients, so
- * we would need a special handling. This hack is trivial and
- * keeps WaitForSomething() backward compatible with the exis-
- * ting servers.
- */
-
- if (pClientsReady[0] == -1)
- {
- unsigned long timeoutInMillis;
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: pClientsReady[0] is [%d], pClientsReady[1] is [%d].\n",
- pClientsReady[0], pClientsReady[1]);
-#endif
-
- timeoutInMillis = GetTimeInMillis();
-
- if (timeoutInMillis - startTimeInMillis >= NX_TRANS_WAKEUP)
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Returning 0 because of wakeup timeout.\n");
-#endif
- return 0;
- }
-
- timeoutInMillis = NX_TRANS_WAKEUP - (timeoutInMillis - startTimeInMillis);
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Milliseconds to next wakeup are %ld.\n",
- timeoutInMillis);
-#endif
- if (wt == NULL || (wt -> tv_sec * MILLI_PER_SECOND +
- wt -> tv_usec / MILLI_PER_SECOND) > timeoutInMillis)
- {
- if ((waittime.tv_sec * MILLI_PER_SECOND +
- waittime.tv_usec / MILLI_PER_SECOND) > timeoutInMillis)
- {
- waittime.tv_sec = timeoutInMillis / MILLI_PER_SECOND;
- waittime.tv_usec = (timeoutInMillis * MILLI_PER_SECOND) %
- (MILLI_PER_SECOND * 1000);
- wt = &waittime;
- }
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Next wakeup timeout set to %ld milliseconds.\n",
- (waittime.tv_sec * MILLI_PER_SECOND) +
- (waittime.tv_usec / MILLI_PER_SECOND));
-#endif
- }
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_WAKEUP) && defined(NX_TRANS_DEBUG)
- else
- {
- fprintf(stderr, "WaitForSomething: Using existing timeout of %ld milliseconds.\n",
- (waittime.tv_sec * MILLI_PER_SECOND) +
- (waittime.tv_usec / MILLI_PER_SECOND));
- }
-#endif
- }
-#endif
-
- /* keep this check close to select() call to minimize race */
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- if (dispatchException)
- {
- i = -1;
-
- fprintf(stderr, "WaitForSomething: Value of dispatchException is true. Set i = -1.\n");
- }
-#else
- if (dispatchException)
- i = -1;
-#endif
- else if (AnyClientsWriteBlocked)
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- if (wt == NULL)
- {
- fprintf(stderr, "WaitForSomething: Executing select with LastSelectMask and "
- "clientsWritable and null timeout.\n");
- }
- else
- {
- fprintf(stderr, "WaitForSomething: Executing select with LastSelectMask, "
- "clientsWritable, %ld secs and %ld usecs.\n",
- wt -> tv_sec, wt -> tv_usec);
- }
-#endif
- XFD_COPYSET(&ClientsWriteBlocked, &clientsWritable);
- i = Select (MaxClients, &LastSelectMask, &clientsWritable, NULL, wt);
- }
- else
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- if (wt == NULL)
- {
- fprintf(stderr, "WaitForSomething: Executing select with LastSelectMask and null timeout.\n");
- }
- else
- {
- fprintf(stderr, "WaitForSomething: Executing select with LastSelectMask, %ld secs and %ld usecs.\n",
- wt -> tv_sec, wt -> tv_usec);
- }
-#endif
- i = Select (MaxClients, &LastSelectMask, NULL, NULL, wt);
- }
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Bailed out with i = [%d] and errno = [%d].\n", i, errno);
-
- if (i < 0)
- {
- fprintf(stderr, "WaitForSomething: Error is [%s].\n", strerror(errno));
- }
-#endif
- selecterr = GetErrno();
- WakeupHandler(i, (pointer)&LastSelectMask);
-#ifdef XTESTEXT1
- if (playback_on) {
- i = XTestProcessInputAction (i, &waittime);
- }
-#endif /* XTESTEXT1 */
-#ifdef SMART_SCHEDULE
- if (i >= 0)
- {
- SmartScheduleIdle = FALSE;
- SmartScheduleIdleCount = 0;
- if (SmartScheduleTimerStopped)
- (void) SmartScheduleStartTimer ();
- }
-#endif
- if (i <= 0) /* An error or timeout occurred */
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- if (dispatchException)
- {
- fprintf(stderr, "WaitForSomething: Returning 0 because of (dispatchException).\n");
- return 0;
- }
-#else
- if (dispatchException)
- return 0;
-#endif
- if (i < 0)
- {
- if (selecterr == EBADF) /* Some client disconnected */
- {
- CheckConnections ();
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- if (! XFD_ANYSET (&AllClients))
- {
- fprintf(stderr, "WaitForSomething: Returning 0 because of (! XFD_ANYSET (&AllClients)).\n");
- return 0;
- }
-#else
- if (! XFD_ANYSET (&AllClients))
- return 0;
-#endif
- }
- else if (selecterr == EINVAL)
- {
- FatalError("WaitForSomething(): select: errno=%d\n",
- selecterr);
- }
- else if (selecterr != EINTR)
- {
- ErrorF("WaitForSomething(): select: errno=%d\n",
- selecterr);
- }
- }
-#ifdef SMART_SCHEDULE
- else if (someReady)
- {
- /*
- * If no-one else is home, bail quickly
- */
- XFD_COPYSET(&ClientsWithInput, &LastSelectMask);
- XFD_COPYSET(&ClientsWithInput, &clientsReadable);
- break;
- }
-#endif
-#if defined(NX_TRANS_SOCKET)
- if (*checkForInput[0] != *checkForInput[1])
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Returning 0 because of (*checkForInput[0] != *checkForInput[1]).\n");
-#endif
- return 0;
- }
-#else
- if (*checkForInput[0] != *checkForInput[1])
- return 0;
-#endif
-
- if (timers)
- {
- int expired = 0;
- now = GetTimeInMillis();
- if ((int) (timers->expires - now) <= 0)
- expired = 1;
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-
- if (expired)
- return 0;
- }
- }
- else
- {
- fd_set tmp_set;
-
- if (*checkForInput[0] == *checkForInput[1]) {
- if (timers)
- {
- int expired = 0;
- now = GetTimeInMillis();
- if ((int) (timers->expires - now) <= 0)
- expired = 1;
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-
- if (expired)
- return 0;
- }
- }
-#ifdef SMART_SCHEDULE
- if (someReady)
- XFD_ORSET(&LastSelectMask, &ClientsWithInput, &LastSelectMask);
-#endif
- if (AnyClientsWriteBlocked && XFD_ANYSET (&clientsWritable))
- {
- NewOutputPending = TRUE;
- XFD_ORSET(&OutputPending, &clientsWritable, &OutputPending);
- XFD_UNSET(&ClientsWriteBlocked, &clientsWritable);
- if (! XFD_ANYSET(&ClientsWriteBlocked))
- AnyClientsWriteBlocked = FALSE;
- }
-
- XFD_ANDSET(&devicesReadable, &LastSelectMask, &EnabledDevices);
- XFD_ANDSET(&clientsReadable, &LastSelectMask, &AllClients);
- XFD_ANDSET(&tmp_set, &LastSelectMask, &WellKnownConnections);
- if (XFD_ANYSET(&tmp_set))
- QueueWorkProc(EstablishNewConnections, NULL,
- (pointer)&LastSelectMask);
-#ifdef DPMSExtension
- if (XFD_ANYSET (&devicesReadable) && (DPMSPowerLevel != DPMSModeOn))
- DPMSSet(DPMSModeOn);
-#endif
- if (XFD_ANYSET (&devicesReadable) || XFD_ANYSET (&clientsReadable))
- break;
-#ifdef WIN32
- /* Windows keyboard and mouse events are added to the input queue
- in Block- and WakupHandlers. There is no device to check if
- data is ready. So check here if new input is available */
-#if defined(NX_TRANS_SOCKET)
- if (*checkForInput[0] != *checkForInput[1])
- {
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Returning 0 because of (*checkForInput[0] != *checkForInput[1]).\n");
-#endif
- return 0;
- }
-#else
- if (*checkForInput[0] != *checkForInput[1])
- return 0;
-#endif
-#endif
- }
- }
-
- nready = 0;
- if (XFD_ANYSET (&clientsReadable))
- {
-#ifndef WIN32
- for (i=0; i<howmany(XFD_SETSIZE, NFDBITS); i++)
- {
- int highest_priority = 0;
-
- while (clientsReadable.fds_bits[i])
- {
- int client_priority, client_index;
-
- curclient = ffs (clientsReadable.fds_bits[i]) - 1;
- client_index = /* raphael: modified */
- ConnectionTranslation[curclient + (i * (sizeof(fd_mask) * 8))];
-#else
- int highest_priority = 0;
- fd_set savedClientsReadable;
- XFD_COPYSET(&clientsReadable, &savedClientsReadable);
- for (i = 0; i < XFD_SETCOUNT(&savedClientsReadable); i++)
- {
- int client_priority, client_index;
-
- curclient = XFD_FD(&savedClientsReadable, i);
- client_index = GetConnectionTranslation(curclient);
-#endif
-#ifdef XSYNC
- /* We implement "strict" priorities.
- * Only the highest priority client is returned to
- * dix. If multiple clients at the same priority are
- * ready, they are all returned. This means that an
- * aggressive client could take over the server.
- * This was not considered a big problem because
- * aggressive clients can hose the server in so many
- * other ways :)
- */
- client_priority = clients[client_index]->priority;
- if (nready == 0 || client_priority > highest_priority)
- {
- /* Either we found the first client, or we found
- * a client whose priority is greater than all others
- * that have been found so far. Either way, we want
- * to initialize the list of clients to contain just
- * this client.
- */
- pClientsReady[0] = client_index;
- highest_priority = client_priority;
- nready = 1;
- }
- /* the following if makes sure that multiple same-priority
- * clients get batched together
- */
- else if (client_priority == highest_priority)
-#endif
- {
- pClientsReady[nready++] = client_index;
- }
-#ifndef WIN32
- clientsReadable.fds_bits[i] &= ~(((fd_mask)1L) << curclient);
- }
-#else
- FD_CLR(curclient, &clientsReadable);
-#endif
- }
- }
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_DEBUG)
- fprintf(stderr, "WaitForSomething: Returning nready.\n");
-#endif
- return nready;
-}
-
-#if 0
-/*
- * This is not always a macro.
- */
-ANYSET(FdMask *src)
-{
- int i;
-
- for (i=0; i<mskcnt; i++)
- if (src[ i ])
- return (TRUE);
- return (FALSE);
-}
-#endif
-
-
-static void
-DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev)
-{
- CARD32 newTime;
-
- *prev = timer->next;
- timer->next = NULL;
- newTime = (*timer->callback)(timer, now, timer->arg);
- if (newTime)
- TimerSet(timer, 0, newTime, timer->callback, timer->arg);
-}
-
-OsTimerPtr
-TimerSet(OsTimerPtr timer, int flags, CARD32 millis,
- OsTimerCallback func, pointer arg)
-{
- register OsTimerPtr *prev;
- CARD32 now = GetTimeInMillis();
-
- if (!timer)
- {
- timer = (OsTimerPtr)xalloc(sizeof(struct _OsTimerRec));
- if (!timer)
- return NULL;
- }
- else
- {
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- *prev = timer->next;
- if (flags & TimerForceOld)
- (void)(*timer->callback)(timer, now, timer->arg);
- break;
- }
- }
- }
- if (!millis)
- return timer;
- if (!(flags & TimerAbsolute))
- millis += now;
- timer->expires = millis;
- timer->callback = func;
- timer->arg = arg;
- if ((int) (millis - now) <= 0)
- {
- timer->next = NULL;
- millis = (*timer->callback)(timer, now, timer->arg);
- if (!millis)
- return timer;
- }
- for (prev = &timers;
- *prev && (int) ((*prev)->expires - millis) <= 0;
- prev = &(*prev)->next)
- ;
- timer->next = *prev;
- *prev = timer;
- return timer;
-}
-
-Bool
-TimerForce(OsTimerPtr timer)
-{
- OsTimerPtr *prev;
-
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- DoTimer(timer, GetTimeInMillis(), prev);
- return TRUE;
- }
- }
- return FALSE;
-}
-
-
-void
-TimerCancel(OsTimerPtr timer)
-{
- OsTimerPtr *prev;
-
- if (!timer)
- return;
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- *prev = timer->next;
- break;
- }
- }
-}
-
-void
-TimerFree(OsTimerPtr timer)
-{
- if (!timer)
- return;
- TimerCancel(timer);
- xfree(timer);
-}
-
-void
-TimerCheck(void)
-{
- CARD32 now = GetTimeInMillis();
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-}
-
-void
-TimerInit(void)
-{
- OsTimerPtr timer;
-
- while ((timer = timers))
- {
- timers = timer->next;
- xfree(timer);
- }
-}
-
-static CARD32
-ScreenSaverTimeoutExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < ScreenSaverTime) {
- return ScreenSaverTime - timeout;
- }
-
- ResetOsBuffers(); /* not ideal, but better than nothing */
- SaveScreens(SCREEN_SAVER_ON, ScreenSaverActive);
-
-#ifdef DPMSExtension
- if (ScreenSaverInterval > 0 && DPMSPowerLevel == DPMSModeOn)
-#else
- if (ScreenSaverInterval > 0)
-#endif /* DPMSExtension */
- return ScreenSaverInterval;
-
- return 0;
-}
-
-static OsTimerPtr ScreenSaverTimer = NULL;
-
-void
-FreeScreenSaverTimer(void)
-{
- if (ScreenSaverTimer) {
- TimerFree(ScreenSaverTimer);
- ScreenSaverTimer = NULL;
- }
-}
-
-void
-SetScreenSaverTimer(void)
-{
- if (ScreenSaverTime > 0) {
- ScreenSaverTimer = TimerSet(ScreenSaverTimer, 0, ScreenSaverTime,
- ScreenSaverTimeoutExpire, NULL);
- } else if (ScreenSaverTimer) {
- FreeScreenSaverTimer();
- }
-}
-
-#ifdef DPMSExtension
-
-static OsTimerPtr DPMSStandbyTimer = NULL;
-static OsTimerPtr DPMSSuspendTimer = NULL;
-static OsTimerPtr DPMSOffTimer = NULL;
-
-static CARD32
-DPMSStandbyTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSStandbyTime) {
- return DPMSStandbyTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeStandby) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeStandby);
- }
- return DPMSStandbyTime;
-}
-
-static CARD32
-DPMSSuspendTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSSuspendTime) {
- return DPMSSuspendTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeSuspend) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeSuspend);
- }
- return DPMSSuspendTime;
-}
-
-static CARD32
-DPMSOffTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSOffTime) {
- return DPMSOffTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeOff) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeOff);
- }
- return DPMSOffTime;
-}
-
-void
-FreeDPMSTimers(void)
-{
- if (DPMSStandbyTimer) {
- TimerFree(DPMSStandbyTimer);
- DPMSStandbyTimer = NULL;
- }
- if (DPMSSuspendTimer) {
- TimerFree(DPMSSuspendTimer);
- DPMSSuspendTimer = NULL;
- }
- if (DPMSOffTimer) {
- TimerFree(DPMSOffTimer);
- DPMSOffTimer = NULL;
- }
-}
-
-void
-SetDPMSTimers(void)
-{
- if (!DPMSEnabled)
- return;
-
- DPMSStandbyTimer = TimerSet(DPMSStandbyTimer, 0, DPMSStandbyTime,
- DPMSStandbyTimerExpire, NULL);
- DPMSSuspendTimer = TimerSet(DPMSSuspendTimer, 0, DPMSSuspendTime,
- DPMSSuspendTimerExpire, NULL);
- DPMSOffTimer = TimerSet(DPMSOffTimer, 0, DPMSOffTime,
- DPMSOffTimerExpire, NULL);
-}
-#endif
diff --git a/nx-X11/programs/Xserver/os/WaitFor.c.X.original b/nx-X11/programs/Xserver/os/WaitFor.c.X.original
deleted file mode 100644
index 31e16210b..000000000
--- a/nx-X11/programs/Xserver/os/WaitFor.c.X.original
+++ /dev/null
@@ -1,701 +0,0 @@
-/* $XFree86: xc/programs/Xserver/os/WaitFor.c,v 3.42 2003/10/16 01:33:35 dawes Exp $ */
-/***********************************************************
-
-Copyright 1987, 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 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.
-
-******************************************************************/
-
-/* $Xorg: WaitFor.c,v 1.4 2001/02/09 02:05:22 xorgcvs Exp $ */
-
-/*****************************************************************
- * OS Dependent input routines:
- *
- * WaitForSomething
- * TimerForce, TimerSet, TimerCheck, TimerFree
- *
- *****************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/Xos.h> /* for strings, fcntl, time */
-#include <errno.h>
-#include <stdio.h>
-#include <X11/X.h>
-#include "misc.h"
-
-#ifdef __UNIXOS2__
-#define select(n,r,w,x,t) os2PseudoSelect(n,r,w,x,t)
-#endif
-#include "osdep.h"
-#include <X11/Xpoll.h>
-#include "dixstruct.h"
-#include "opaque.h"
-#ifdef DPMSExtension
-#include "dpmsproc.h"
-#endif
-
-#ifdef WIN32
-/* Error codes from windows sockets differ from fileio error codes */
-#undef EINTR
-#define EINTR WSAEINTR
-#undef EINVAL
-#define EINVAL WSAEINVAL
-#undef EBADF
-#define EBADF WSAENOTSOCK
-/* Windows select does not set errno. Use GetErrno as wrapper for
- WSAGetLastError */
-#define GetErrno WSAGetLastError
-#else
-/* This is just a fallback to errno to hide the differences between unix and
- Windows in the code */
-#define GetErrno() errno
-#endif
-
-/* modifications by raphael */
-int
-mffs(fd_mask mask)
-{
- int i;
-
- if (!mask) return 0;
- i = 1;
- while (!(mask & 1))
- {
- i++;
- mask >>= 1;
- }
- return i;
-}
-
-#ifdef DPMSExtension
-#define DPMS_SERVER
-#include <X11/extensions/dpms.h>
-#endif
-
-#ifdef XTESTEXT1
-/*
- * defined in xtestext1dd.c
- */
-extern int playback_on;
-#endif /* XTESTEXT1 */
-
-struct _OsTimerRec {
- OsTimerPtr next;
- CARD32 expires;
- OsTimerCallback callback;
- pointer arg;
-};
-
-static void DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev);
-static OsTimerPtr timers = NULL;
-
-/*****************
- * WaitForSomething:
- * Make the server suspend until there is
- * 1. data from clients or
- * 2. input events available or
- * 3. ddx notices something of interest (graphics
- * queue ready, etc.) or
- * 4. clients that have buffered replies/events are ready
- *
- * If the time between INPUT events is
- * greater than ScreenSaverTime, the display is turned off (or
- * saved, depending on the hardware). So, WaitForSomething()
- * has to handle this also (that's why the select() has a timeout.
- * For more info on ClientsWithInput, see ReadRequestFromClient().
- * pClientsReady is an array to store ready client->index values into.
- *****************/
-
-int
-WaitForSomething(int *pClientsReady)
-{
- int i;
- struct timeval waittime, *wt;
- INT32 timeout = 0;
- fd_set clientsReadable;
- fd_set clientsWritable;
- int curclient;
- int selecterr;
- int nready;
- fd_set devicesReadable;
- CARD32 now = 0;
-#ifdef SMART_SCHEDULE
- Bool someReady = FALSE;
-#endif
-
- FD_ZERO(&clientsReadable);
-
- /* We need a while loop here to handle
- crashed connections and the screen saver timeout */
- while (1)
- {
- /* deal with any blocked jobs */
- if (workQueue)
- ProcessWorkQueue();
- if (XFD_ANYSET (&ClientsWithInput))
- {
-#ifdef SMART_SCHEDULE
- if (!SmartScheduleDisable)
- {
- someReady = TRUE;
- waittime.tv_sec = 0;
- waittime.tv_usec = 0;
- wt = &waittime;
- }
- else
-#endif
- {
- XFD_COPYSET (&ClientsWithInput, &clientsReadable);
- break;
- }
- }
-#ifdef SMART_SCHEDULE
- if (someReady)
- {
- XFD_COPYSET(&AllSockets, &LastSelectMask);
- XFD_UNSET(&LastSelectMask, &ClientsWithInput);
- }
- else
- {
-#endif
- wt = NULL;
- if (timers)
- {
- now = GetTimeInMillis();
- timeout = timers->expires - now;
- if (timeout < 0)
- timeout = 0;
- waittime.tv_sec = timeout / MILLI_PER_SECOND;
- waittime.tv_usec = (timeout % MILLI_PER_SECOND) *
- (1000000 / MILLI_PER_SECOND);
- wt = &waittime;
- }
- XFD_COPYSET(&AllSockets, &LastSelectMask);
-#ifdef SMART_SCHEDULE
- }
- SmartScheduleIdle = TRUE;
-#endif
- BlockHandler((pointer)&wt, (pointer)&LastSelectMask);
- if (NewOutputPending)
- FlushAllOutput();
-#ifdef XTESTEXT1
- /* XXX how does this interact with new write block handling? */
- if (playback_on) {
- wt = &waittime;
- XTestComputeWaitTime (&waittime);
- }
-#endif /* XTESTEXT1 */
- /* keep this check close to select() call to minimize race */
- if (dispatchException)
- i = -1;
- else if (AnyClientsWriteBlocked)
- {
- XFD_COPYSET(&ClientsWriteBlocked, &clientsWritable);
- i = Select (MaxClients, &LastSelectMask, &clientsWritable, NULL, wt);
- }
- else
- {
- i = Select (MaxClients, &LastSelectMask, NULL, NULL, wt);
- }
- selecterr = GetErrno();
- WakeupHandler(i, (pointer)&LastSelectMask);
-#ifdef XTESTEXT1
- if (playback_on) {
- i = XTestProcessInputAction (i, &waittime);
- }
-#endif /* XTESTEXT1 */
-#ifdef SMART_SCHEDULE
- if (i >= 0)
- {
- SmartScheduleIdle = FALSE;
- SmartScheduleIdleCount = 0;
- if (SmartScheduleTimerStopped)
- (void) SmartScheduleStartTimer ();
- }
-#endif
- if (i <= 0) /* An error or timeout occurred */
- {
- if (dispatchException)
- return 0;
- if (i < 0)
- {
- if (selecterr == EBADF) /* Some client disconnected */
- {
- CheckConnections ();
- if (! XFD_ANYSET (&AllClients))
- return 0;
- }
- else if (selecterr == EINVAL)
- {
- FatalError("WaitForSomething(): select: errno=%d\n",
- selecterr);
- }
- else if (selecterr != EINTR)
- {
- ErrorF("WaitForSomething(): select: errno=%d\n",
- selecterr);
- }
- }
-#ifdef SMART_SCHEDULE
- else if (someReady)
- {
- /*
- * If no-one else is home, bail quickly
- */
- XFD_COPYSET(&ClientsWithInput, &LastSelectMask);
- XFD_COPYSET(&ClientsWithInput, &clientsReadable);
- break;
- }
-#endif
- if (*checkForInput[0] != *checkForInput[1])
- return 0;
-
- if (timers)
- {
- int expired = 0;
- now = GetTimeInMillis();
- if ((int) (timers->expires - now) <= 0)
- expired = 1;
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-
- if (expired)
- return 0;
- }
- }
- else
- {
- fd_set tmp_set;
-
- if (*checkForInput[0] == *checkForInput[1]) {
- if (timers)
- {
- int expired = 0;
- now = GetTimeInMillis();
- if ((int) (timers->expires - now) <= 0)
- expired = 1;
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-
- if (expired)
- return 0;
- }
- }
-#ifdef SMART_SCHEDULE
- if (someReady)
- XFD_ORSET(&LastSelectMask, &ClientsWithInput, &LastSelectMask);
-#endif
- if (AnyClientsWriteBlocked && XFD_ANYSET (&clientsWritable))
- {
- NewOutputPending = TRUE;
- XFD_ORSET(&OutputPending, &clientsWritable, &OutputPending);
- XFD_UNSET(&ClientsWriteBlocked, &clientsWritable);
- if (! XFD_ANYSET(&ClientsWriteBlocked))
- AnyClientsWriteBlocked = FALSE;
- }
-
- XFD_ANDSET(&devicesReadable, &LastSelectMask, &EnabledDevices);
- XFD_ANDSET(&clientsReadable, &LastSelectMask, &AllClients);
- XFD_ANDSET(&tmp_set, &LastSelectMask, &WellKnownConnections);
- if (XFD_ANYSET(&tmp_set))
- QueueWorkProc(EstablishNewConnections, NULL,
- (pointer)&LastSelectMask);
-#ifdef DPMSExtension
- if (XFD_ANYSET (&devicesReadable) && (DPMSPowerLevel != DPMSModeOn))
- DPMSSet(DPMSModeOn);
-#endif
- if (XFD_ANYSET (&devicesReadable) || XFD_ANYSET (&clientsReadable))
- break;
-#ifdef WIN32
- /* Windows keyboard and mouse events are added to the input queue
- in Block- and WakupHandlers. There is no device to check if
- data is ready. So check here if new input is available */
- if (*checkForInput[0] != *checkForInput[1])
- return 0;
-#endif
- }
- }
-
- nready = 0;
- if (XFD_ANYSET (&clientsReadable))
- {
-#ifndef WIN32
- for (i=0; i<howmany(XFD_SETSIZE, NFDBITS); i++)
- {
- int highest_priority = 0;
-
- while (clientsReadable.fds_bits[i])
- {
- int client_priority, client_index;
-
- curclient = ffs (clientsReadable.fds_bits[i]) - 1;
- client_index = /* raphael: modified */
- ConnectionTranslation[curclient + (i * (sizeof(fd_mask) * 8))];
-#else
- int highest_priority = 0;
- fd_set savedClientsReadable;
- XFD_COPYSET(&clientsReadable, &savedClientsReadable);
- for (i = 0; i < XFD_SETCOUNT(&savedClientsReadable); i++)
- {
- int client_priority, client_index;
-
- curclient = XFD_FD(&savedClientsReadable, i);
- client_index = GetConnectionTranslation(curclient);
-#endif
-#ifdef XSYNC
- /* We implement "strict" priorities.
- * Only the highest priority client is returned to
- * dix. If multiple clients at the same priority are
- * ready, they are all returned. This means that an
- * aggressive client could take over the server.
- * This was not considered a big problem because
- * aggressive clients can hose the server in so many
- * other ways :)
- */
- client_priority = clients[client_index]->priority;
- if (nready == 0 || client_priority > highest_priority)
- {
- /* Either we found the first client, or we found
- * a client whose priority is greater than all others
- * that have been found so far. Either way, we want
- * to initialize the list of clients to contain just
- * this client.
- */
- pClientsReady[0] = client_index;
- highest_priority = client_priority;
- nready = 1;
- }
- /* the following if makes sure that multiple same-priority
- * clients get batched together
- */
- else if (client_priority == highest_priority)
-#endif
- {
- pClientsReady[nready++] = client_index;
- }
-#ifndef WIN32
- clientsReadable.fds_bits[i] &= ~(((fd_mask)1L) << curclient);
- }
-#else
- FD_CLR(curclient, &clientsReadable);
-#endif
- }
- }
- return nready;
-}
-
-#if 0
-/*
- * This is not always a macro.
- */
-ANYSET(FdMask *src)
-{
- int i;
-
- for (i=0; i<mskcnt; i++)
- if (src[ i ])
- return (TRUE);
- return (FALSE);
-}
-#endif
-
-
-static void
-DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev)
-{
- CARD32 newTime;
-
- *prev = timer->next;
- timer->next = NULL;
- newTime = (*timer->callback)(timer, now, timer->arg);
- if (newTime)
- TimerSet(timer, 0, newTime, timer->callback, timer->arg);
-}
-
-OsTimerPtr
-TimerSet(OsTimerPtr timer, int flags, CARD32 millis,
- OsTimerCallback func, pointer arg)
-{
- register OsTimerPtr *prev;
- CARD32 now = GetTimeInMillis();
-
- if (!timer)
- {
- timer = (OsTimerPtr)xalloc(sizeof(struct _OsTimerRec));
- if (!timer)
- return NULL;
- }
- else
- {
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- *prev = timer->next;
- if (flags & TimerForceOld)
- (void)(*timer->callback)(timer, now, timer->arg);
- break;
- }
- }
- }
- if (!millis)
- return timer;
- if (!(flags & TimerAbsolute))
- millis += now;
- timer->expires = millis;
- timer->callback = func;
- timer->arg = arg;
- if ((int) (millis - now) <= 0)
- {
- timer->next = NULL;
- millis = (*timer->callback)(timer, now, timer->arg);
- if (!millis)
- return timer;
- }
- for (prev = &timers;
- *prev && (int) ((*prev)->expires - millis) <= 0;
- prev = &(*prev)->next)
- ;
- timer->next = *prev;
- *prev = timer;
- return timer;
-}
-
-Bool
-TimerForce(OsTimerPtr timer)
-{
- OsTimerPtr *prev;
-
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- DoTimer(timer, GetTimeInMillis(), prev);
- return TRUE;
- }
- }
- return FALSE;
-}
-
-
-void
-TimerCancel(OsTimerPtr timer)
-{
- OsTimerPtr *prev;
-
- if (!timer)
- return;
- for (prev = &timers; *prev; prev = &(*prev)->next)
- {
- if (*prev == timer)
- {
- *prev = timer->next;
- break;
- }
- }
-}
-
-void
-TimerFree(OsTimerPtr timer)
-{
- if (!timer)
- return;
- TimerCancel(timer);
- xfree(timer);
-}
-
-void
-TimerCheck(void)
-{
- CARD32 now = GetTimeInMillis();
-
- while (timers && (int) (timers->expires - now) <= 0)
- DoTimer(timers, now, &timers);
-}
-
-void
-TimerInit(void)
-{
- OsTimerPtr timer;
-
- while ((timer = timers))
- {
- timers = timer->next;
- xfree(timer);
- }
-}
-
-static CARD32
-ScreenSaverTimeoutExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < ScreenSaverTime) {
- return ScreenSaverTime - timeout;
- }
-
- ResetOsBuffers(); /* not ideal, but better than nothing */
- SaveScreens(SCREEN_SAVER_ON, ScreenSaverActive);
-
-#ifdef DPMSExtension
- if (ScreenSaverInterval > 0 && DPMSPowerLevel == DPMSModeOn)
-#else
- if (ScreenSaverInterval > 0)
-#endif /* DPMSExtension */
- return ScreenSaverInterval;
-
- return 0;
-}
-
-static OsTimerPtr ScreenSaverTimer = NULL;
-
-void
-FreeScreenSaverTimer(void)
-{
- if (ScreenSaverTimer) {
- TimerFree(ScreenSaverTimer);
- ScreenSaverTimer = NULL;
- }
-}
-
-void
-SetScreenSaverTimer(void)
-{
- if (ScreenSaverTime > 0) {
- ScreenSaverTimer = TimerSet(ScreenSaverTimer, 0, ScreenSaverTime,
- ScreenSaverTimeoutExpire, NULL);
- } else if (ScreenSaverTimer) {
- FreeScreenSaverTimer();
- }
-}
-
-#ifdef DPMSExtension
-
-static OsTimerPtr DPMSStandbyTimer = NULL;
-static OsTimerPtr DPMSSuspendTimer = NULL;
-static OsTimerPtr DPMSOffTimer = NULL;
-
-static CARD32
-DPMSStandbyTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSStandbyTime) {
- return DPMSStandbyTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeStandby) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeStandby);
- }
- return DPMSStandbyTime;
-}
-
-static CARD32
-DPMSSuspendTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSSuspendTime) {
- return DPMSSuspendTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeSuspend) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeSuspend);
- }
- return DPMSSuspendTime;
-}
-
-static CARD32
-DPMSOffTimerExpire(OsTimerPtr timer,CARD32 now,pointer arg)
-{
- INT32 timeout = now - lastDeviceEventTime.milliseconds;
-
- if (timeout < DPMSOffTime) {
- return DPMSOffTime - timeout;
- }
- if (DPMSPowerLevel < DPMSModeOff) {
- if (DPMSEnabled)
- DPMSSet(DPMSModeOff);
- }
- return DPMSOffTime;
-}
-
-void
-FreeDPMSTimers(void)
-{
- if (DPMSStandbyTimer) {
- TimerFree(DPMSStandbyTimer);
- DPMSStandbyTimer = NULL;
- }
- if (DPMSSuspendTimer) {
- TimerFree(DPMSSuspendTimer);
- DPMSSuspendTimer = NULL;
- }
- if (DPMSOffTimer) {
- TimerFree(DPMSOffTimer);
- DPMSOffTimer = NULL;
- }
-}
-
-void
-SetDPMSTimers(void)
-{
- if (!DPMSEnabled)
- return;
-
- DPMSStandbyTimer = TimerSet(DPMSStandbyTimer, 0, DPMSStandbyTime,
- DPMSStandbyTimerExpire, NULL);
- DPMSSuspendTimer = TimerSet(DPMSSuspendTimer, 0, DPMSSuspendTime,
- DPMSSuspendTimerExpire, NULL);
- DPMSOffTimer = TimerSet(DPMSOffTimer, 0, DPMSOffTime,
- DPMSOffTimerExpire, NULL);
-}
-#endif
diff --git a/nx-X11/programs/Xserver/os/auth.c.NX.original b/nx-X11/programs/Xserver/os/auth.c.NX.original
deleted file mode 100644
index dfb6f8899..000000000
--- a/nx-X11/programs/Xserver/os/auth.c.NX.original
+++ /dev/null
@@ -1,608 +0,0 @@
-/* $Xorg: auth.c,v 1.5 2001/02/09 02:05:23 xorgcvs Exp $ */
-/*
-
-Copyright 1988, 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.
-
-*/
-/* $XFree86: auth.c,v 1.13 2003/04/27 21:31:08 herrb Exp $ */
-
-/**************************************************************************/
-/* */
-/* Copyright (c) 2001, 2011 NoMachine, http://www.nomachine.com/. */
-/* */
-/* NX-X11, NX protocol compression and NX extensions to this software */
-/* are copyright of NoMachine. Redistribution and use of the present */
-/* software is allowed according to terms specified in the file LICENSE */
-/* which comes in the source distribution. */
-/* */
-/* Check http://www.nomachine.com/licensing.html for applicability. */
-/* */
-/* NX and NoMachine are trademarks of Medialogic S.p.A. */
-/* */
-/* All rights reserved. */
-/* */
-/**************************************************************************/
-
-/*
- * authorization hooks for the server
- * Author: Keith Packard, MIT X Consortium
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef K5AUTH
-# include <krb5/krb5.h>
-#endif
-# include <X11/X.h>
-# include <X11/Xauth.h>
-# include "misc.h"
-# include "osdep.h"
-# include "dixstruct.h"
-# include <sys/types.h>
-# include <sys/stat.h>
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-# include <X11/extensions/security.h>
-#endif
-#ifdef WIN32
-#include <X11/Xw32defs.h>
-#endif
-
-struct protocol {
- unsigned short name_length;
- char *name;
- AuthAddCFunc Add; /* new authorization data */
- AuthCheckFunc Check; /* verify client authorization data */
- AuthRstCFunc Reset; /* delete all authorization data entries */
- AuthToIDFunc ToID; /* convert cookie to ID */
- AuthFromIDFunc FromID; /* convert ID to cookie */
- AuthRemCFunc Remove; /* remove a specific cookie */
-#ifdef XCSECURITY
- AuthGenCFunc Generate;
-#endif
-};
-
-static struct protocol protocols[] = {
-{ (unsigned short) 18, "MIT-MAGIC-COOKIE-1",
- MitAddCookie, MitCheckCookie, MitResetCookie,
- MitToID, MitFromID, MitRemoveCookie,
-#ifdef XCSECURITY
- MitGenerateCookie
-#endif
-},
-#ifdef HASXDMAUTH
-{ (unsigned short) 19, "XDM-AUTHORIZATION-1",
- XdmAddCookie, XdmCheckCookie, XdmResetCookie,
- XdmToID, XdmFromID, XdmRemoveCookie,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef SECURE_RPC
-{ (unsigned short) 9, "SUN-DES-1",
- SecureRPCAdd, SecureRPCCheck, SecureRPCReset,
- SecureRPCToID, SecureRPCFromID,SecureRPCRemove,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef K5AUTH
-{ (unsigned short) 14, "MIT-KERBEROS-5",
- K5Add, K5Check, K5Reset,
- K5ToID, K5FromID, K5Remove,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef XCSECURITY
-{ (unsigned short) XSecurityAuthorizationNameLen,
- XSecurityAuthorizationName,
- NULL, AuthSecurityCheck, NULL,
- NULL, NULL, NULL,
- NULL
-},
-#endif
-};
-
-# define NUM_AUTHORIZATION (sizeof (protocols) /\
- sizeof (struct protocol))
-
-/*
- * Initialize all classes of authorization by reading the
- * specified authorization file
- */
-
-static char *authorization_file = (char *)NULL;
-
-static Bool ShouldLoadAuth = TRUE;
-
-void
-InitAuthorization (char *file_name)
-{
-#ifdef __sun
- char * envBuffer;
-#endif
- authorization_file = file_name;
-#ifdef NX_TRANS_AUTH
-#ifdef NX_TRANS_TEST
- fprintf(stderr, "InitAuthorization: Going to propagate auth file '%s' to the environment.\n",
- authorization_file);
-#endif
-#ifdef __sun
- envBuffer = malloc(15+strlen(authorization_file));
- sprintf(envBuffer,"NX_XAUTHORITY=%s",authorization_file);
- putenv(envBuffer);
-#else
- setenv("NX_XAUTHORITY", authorization_file, 1);
-#endif
-#endif
-
-}
-
-static int
-LoadAuthorization (void)
-{
- FILE *f;
- Xauth *auth;
- int i;
- int count = 0;
-
- ShouldLoadAuth = FALSE;
- if (!authorization_file)
- return 0;
-
-#ifdef NX_TRANS_AUTH
-
- /*
- * We think that the way LoadAuthorization() is working is wrong.
- * It doesn't reset the list of stored authorizations before reading
- * the new cookies. Our take is that if a new auth file is to be
- * read, the only cookies that are to be accepted are those that are
- * in the new file, not those in the file -plus- those that have
- * been in the file in the past. Furthermore, if the list can't be
- * read or it is empty, it should assume that it ignores which co-
- * okies are valid and thus it should disable any access. Your mile-
- * age can vary. A less draconian approach could be to leave the old
- * cookies if the file can't be read and remove them only if the
- * file is empty.
- *
- * Adding the cookies without removing the old values for the same
- * protocol has an important implication. If an user shares the co-
- * okie with somebody and later wants to revoke the access to the
- * display, changing the cookie will not work. This is especially
- * important with NX. For security reasons, after reconnecting the
- * session to a different display, it is advisable to generate a
- * new set of cookies, but doing that it is useless with the current
- * code, as the old cookies are going to be still accepted. On the
- * same topic, consider that once an user has got access to the X
- * server, he/she can freely enable host authentication from any
- * host, so the safe behaviour should be to reset the host based
- * authenthication at least at reconnection, and keep as valid only
- * the cookies that are actually in the file. This behaviour would
- * surely break many applications, among them a SSH connection run
- * inside a NX session, as ssh -X reads the cookie for the display
- * only at session startup and does not read the cookies again
- * when the auth file is changed.
- *
- * Another bug (or feature, depending on how you want to consider
- * it) is that if the authority file contains entries for different
- * displays (as it is the norm when the authority file is the default
- * .Xauthority in the user's home), the server will match -any- of
- * the cookies, even cookies that are not for its own display. This
- * means that you have be careful when passing an authority file to
- * nxagent or Xnest and maybe keep separate files for letting nxagent
- * find the cookie to be used to connect to the remote display and
- * for letting it find what cookies to accept. If the file is the
- * same, clients will be able to connect to nxagent with both the
- * cookies.
- */
-
-#ifdef NX_TRANS_AUTH_RESET
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "LoadAuthorization: Resetting authorization info.\n");
- #endif
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].Reset) {
- (*protocols[i].Reset) ();
- }
- }
-
-#endif
-
-#endif /* #ifdef NX_TRANS_AUTH */
-
- f = Fopen (authorization_file, "r");
- if (!f)
- return -1;
-
- while ((auth = XauReadAuth (f)) != 0) {
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == auth->name_length &&
- memcmp (protocols[i].name, auth->name, (int) auth->name_length) == 0 &&
- protocols[i].Add)
- {
-#ifdef NX_TRANS_AUTH
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "LoadAuthorization: Adding new record from file [%s].\n",
- authorization_file);
- #endif
-
-#endif
- ++count;
- (*protocols[i].Add) (auth->data_length, auth->data,
- FakeClientID(0));
- }
- }
- XauDisposeAuth (auth);
- }
-
-#ifdef NX_TRANS_AUTH
-
- if (count == 0)
- {
- fprintf(stderr, "Warning: No authorization record could be read from file '%s'.\n",
- authorization_file);
-
- fprintf(stderr, "Warning: Please, create a valid authorization cookie using the command\n"
- "Warning: 'xauth -f %s add <display> MIT-MAGIC-COOKIE-1 <cookie>'.\n",
- authorization_file);
- }
-
-#endif
-
-#ifdef NX_TRANS_AUTH
- if (Fclose (f) != 0)
- {
- /*
- * If the Fclose() fails, for example because of a signal,
- * it's advisable to return the number of protocols read,
- * if any, or otherwise the server would believe that no
- * cookie is valid and eventually fall back to host based
- * authentication. Note anyway that the new code in Check-
- * Authorization() doesn't care the return value and gives
- * a chance to the function to check the file at the next
- * connection.
- */
-
- if (count > 0)
- {
- return count;
- }
- else
- {
- return -1;
- }
- }
-#else
- Fclose (f);
-#endif
- return count;
-}
-
-#ifdef XDMCP
-/*
- * XdmcpInit calls this function to discover all authorization
- * schemes supported by the display
- */
-void
-RegisterAuthorizations (void)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++)
- XdmcpRegisterAuthorization (protocols[i].name,
- (int)protocols[i].name_length);
-}
-#endif
-
-XID
-CheckAuthorization (
- unsigned int name_length,
- char *name,
- unsigned int data_length,
- char *data,
- ClientPtr client,
- char **reason) /* failure message. NULL for default msg */
-{
- int i;
- struct stat buf;
- static time_t lastmod = 0;
-
- #ifndef NX_TRANS_AUTH
- static Bool loaded = FALSE;
- #endif
-
- if (!authorization_file || stat(authorization_file, &buf))
- {
- if (lastmod != 0) {
- lastmod = 0;
- ShouldLoadAuth = TRUE; /* stat lost, so force reload */
- }
- }
- else if (buf.st_mtime > lastmod)
- {
- lastmod = buf.st_mtime;
- ShouldLoadAuth = TRUE;
- }
- if (ShouldLoadAuth)
- {
- int loadauth = LoadAuthorization();
-
- /*
- * If the authorization file has at least one entry for this server,
- * disable local host access. (loadauth > 0)
- *
- * If there are zero entries (either initially or when the
- * authorization file is later reloaded), or if a valid
- * authorization file was never loaded, enable local host access.
- * (loadauth == 0 || !loaded)
- *
- * If the authorization file was loaded initially (with valid
- * entries for this server), and reloading it later fails, don't
- * change anything. (loadauth == -1 && loaded)
- */
-
-#ifdef NX_TRANS_AUTH
-
- /*
- * The implementation of CheckAuthorization() was changed. The way
- * the auth file was handled previously was questionable and could
- * open the way to a vast array of security problems. There might be
- * ways for an attacker to prevent the server from reading the file
- * and it was enough for the server to fail reading the file once
- * (because of a not blocked signal, for example) to leave the dis-
- * play open to all the users running a session on the same terminal
- * server.
- *
- * In NX we want to have only two cases: either we have to check an
- * authorization file or we don't. In the first case we need to do our
- * best to read the file at any new client access and never fall back
- * to host based authentication. Falling back to local host access has
- * no way back, as it will always take precedence over the auth cookie
- * (unless the user explicitly disables, one by one, all the rules
- * allowing local access, if and only if he/she becomes aware of the
- * problem). In the second case we assume that user doesn't care secu-
- * rity and so allow unrestricted access from the local machine.
- */
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "CheckAuthorization: Going to set authorization with loadauth [%d].\n",
- loadauth);
- #endif
-
- if (authorization_file)
- {
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "CheckAuthorization: Disabling local host access.\n");
- #endif
-
- DisableLocalHost();
- }
- else
- {
- /*
- * Enable host-based authentication only if
- * the authorization file was not specified
- * either on the command line or in the env-
- * ironment.
- */
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "CheckAuthorization: Enabling local host access.\n");
- #endif
-
- EnableLocalHost();
- }
-
- /*
- * Avoid the 'unused variable' warning.
- */
-
- loadauth = loadauth;
-
-#else /* #ifdef NX_TRANS_AUTH */
-
- if (loadauth > 0)
- {
- DisableLocalHost(); /* got at least one */
- loaded = TRUE;
- }
- else if (loadauth == 0 || !loaded)
- EnableLocalHost ();
-
-#endif /* #ifdef NX_TRANS_AUTH */
- }
- if (name_length) {
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0)
- {
- return (*protocols[i].Check) (data_length, data, client, reason);
- }
- *reason = "Protocol not supported by server\n";
- }
- } else *reason = "No protocol specified\n";
- return (XID) ~0L;
-}
-
-void
-ResetAuthorization (void)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++)
- if (protocols[i].Reset)
- (*protocols[i].Reset)();
- ShouldLoadAuth = TRUE;
-}
-
-XID
-AuthorizationToID (
- unsigned short name_length,
- char *name,
- unsigned short data_length,
- char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].ToID)
- {
- return (*protocols[i].ToID) (data_length, data);
- }
- }
- return (XID) ~0L;
-}
-
-int
-AuthorizationFromID (
- XID id,
- unsigned short *name_lenp,
- char **namep,
- unsigned short *data_lenp,
- char **datap)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].FromID &&
- (*protocols[i].FromID) (id, data_lenp, datap)) {
- *name_lenp = protocols[i].name_length;
- *namep = protocols[i].name;
- return 1;
- }
- }
- return 0;
-}
-
-int
-RemoveAuthorization (
- unsigned short name_length,
- char *name,
- unsigned short data_length,
- char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Remove)
- {
- return (*protocols[i].Remove) (data_length, data);
- }
- }
- return 0;
-}
-
-int
-AddAuthorization (unsigned name_length, char *name, unsigned data_length, char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Add)
- {
- return (*protocols[i].Add) (data_length, data, FakeClientID(0));
- }
- }
- return 0;
-}
-
-#ifdef XCSECURITY
-
-XID
-GenerateAuthorization(
- unsigned name_length,
- char *name,
- unsigned data_length,
- char *data,
- unsigned *data_length_return,
- char **data_return)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Generate)
- {
- return (*protocols[i].Generate) (data_length, data,
- FakeClientID(0), data_length_return, data_return);
- }
- }
- return -1;
-}
-
-/* A random number generator that is more unpredictable
- than that shipped with some systems.
- This code is taken from the C standard. */
-
-static unsigned long int next = 1;
-
-static int
-xdm_rand(void)
-{
- next = next * 1103515245 + 12345;
- return (unsigned int)(next/65536) % 32768;
-}
-
-static void
-xdm_srand(unsigned int seed)
-{
- next = seed;
-}
-
-void
-GenerateRandomData (int len, char *buf)
-{
- static int seed;
- int value;
- int i;
-
- seed += GetTimeInMillis();
- xdm_srand (seed);
- for (i = 0; i < len; i++)
- {
- value = xdm_rand ();
- buf[i] ^= (value & 0xff00) >> 8;
- }
-
- /* XXX add getrusage, popen("ps -ale") */
-}
-
-#endif /* XCSECURITY */
diff --git a/nx-X11/programs/Xserver/os/auth.c.X.original b/nx-X11/programs/Xserver/os/auth.c.X.original
deleted file mode 100644
index 19c5534d3..000000000
--- a/nx-X11/programs/Xserver/os/auth.c.X.original
+++ /dev/null
@@ -1,400 +0,0 @@
-/* $Xorg: auth.c,v 1.5 2001/02/09 02:05:23 xorgcvs Exp $ */
-/*
-
-Copyright 1988, 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.
-
-*/
-/* $XFree86: auth.c,v 1.13 2003/04/27 21:31:08 herrb Exp $ */
-
-/*
- * authorization hooks for the server
- * Author: Keith Packard, MIT X Consortium
- */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef K5AUTH
-# include <krb5/krb5.h>
-#endif
-# include <X11/X.h>
-# include <X11/Xauth.h>
-# include "misc.h"
-# include "osdep.h"
-# include "dixstruct.h"
-# include <sys/types.h>
-# include <sys/stat.h>
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-# include <X11/extensions/security.h>
-#endif
-#ifdef WIN32
-#include <X11/Xw32defs.h>
-#endif
-
-struct protocol {
- unsigned short name_length;
- char *name;
- AuthAddCFunc Add; /* new authorization data */
- AuthCheckFunc Check; /* verify client authorization data */
- AuthRstCFunc Reset; /* delete all authorization data entries */
- AuthToIDFunc ToID; /* convert cookie to ID */
- AuthFromIDFunc FromID; /* convert ID to cookie */
- AuthRemCFunc Remove; /* remove a specific cookie */
-#ifdef XCSECURITY
- AuthGenCFunc Generate;
-#endif
-};
-
-static struct protocol protocols[] = {
-{ (unsigned short) 18, "MIT-MAGIC-COOKIE-1",
- MitAddCookie, MitCheckCookie, MitResetCookie,
- MitToID, MitFromID, MitRemoveCookie,
-#ifdef XCSECURITY
- MitGenerateCookie
-#endif
-},
-#ifdef HASXDMAUTH
-{ (unsigned short) 19, "XDM-AUTHORIZATION-1",
- XdmAddCookie, XdmCheckCookie, XdmResetCookie,
- XdmToID, XdmFromID, XdmRemoveCookie,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef SECURE_RPC
-{ (unsigned short) 9, "SUN-DES-1",
- SecureRPCAdd, SecureRPCCheck, SecureRPCReset,
- SecureRPCToID, SecureRPCFromID,SecureRPCRemove,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef K5AUTH
-{ (unsigned short) 14, "MIT-KERBEROS-5",
- K5Add, K5Check, K5Reset,
- K5ToID, K5FromID, K5Remove,
-#ifdef XCSECURITY
- NULL
-#endif
-},
-#endif
-#ifdef XCSECURITY
-{ (unsigned short) XSecurityAuthorizationNameLen,
- XSecurityAuthorizationName,
- NULL, AuthSecurityCheck, NULL,
- NULL, NULL, NULL,
- NULL
-},
-#endif
-};
-
-# define NUM_AUTHORIZATION (sizeof (protocols) /\
- sizeof (struct protocol))
-
-/*
- * Initialize all classes of authorization by reading the
- * specified authorization file
- */
-
-static char *authorization_file = (char *)NULL;
-
-static Bool ShouldLoadAuth = TRUE;
-
-void
-InitAuthorization (char *file_name)
-{
- authorization_file = file_name;
-}
-
-static int
-LoadAuthorization (void)
-{
- FILE *f;
- Xauth *auth;
- int i;
- int count = 0;
-
- ShouldLoadAuth = FALSE;
- if (!authorization_file)
- return 0;
-
- f = Fopen (authorization_file, "r");
- if (!f)
- return -1;
-
- while ((auth = XauReadAuth (f)) != 0) {
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == auth->name_length &&
- memcmp (protocols[i].name, auth->name, (int) auth->name_length) == 0 &&
- protocols[i].Add)
- {
- ++count;
- (*protocols[i].Add) (auth->data_length, auth->data,
- FakeClientID(0));
- }
- }
- XauDisposeAuth (auth);
- }
-
- Fclose (f);
- return count;
-}
-
-#ifdef XDMCP
-/*
- * XdmcpInit calls this function to discover all authorization
- * schemes supported by the display
- */
-void
-RegisterAuthorizations (void)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++)
- XdmcpRegisterAuthorization (protocols[i].name,
- (int)protocols[i].name_length);
-}
-#endif
-
-XID
-CheckAuthorization (
- unsigned int name_length,
- char *name,
- unsigned int data_length,
- char *data,
- ClientPtr client,
- char **reason) /* failure message. NULL for default msg */
-{
- int i;
- struct stat buf;
- static time_t lastmod = 0;
- static Bool loaded = FALSE;
-
- if (!authorization_file || stat(authorization_file, &buf))
- {
- if (lastmod != 0) {
- lastmod = 0;
- ShouldLoadAuth = TRUE; /* stat lost, so force reload */
- }
- }
- else if (buf.st_mtime > lastmod)
- {
- lastmod = buf.st_mtime;
- ShouldLoadAuth = TRUE;
- }
- if (ShouldLoadAuth)
- {
- int loadauth = LoadAuthorization();
-
- /*
- * If the authorization file has at least one entry for this server,
- * disable local host access. (loadauth > 0)
- *
- * If there are zero entries (either initially or when the
- * authorization file is later reloaded), or if a valid
- * authorization file was never loaded, enable local host access.
- * (loadauth == 0 || !loaded)
- *
- * If the authorization file was loaded initially (with valid
- * entries for this server), and reloading it later fails, don't
- * change anything. (loadauth == -1 && loaded)
- */
-
- if (loadauth > 0)
- {
- DisableLocalHost(); /* got at least one */
- loaded = TRUE;
- }
- else if (loadauth == 0 || !loaded)
- EnableLocalHost ();
- }
- if (name_length) {
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0)
- {
- return (*protocols[i].Check) (data_length, data, client, reason);
- }
- *reason = "Protocol not supported by server\n";
- }
- } else *reason = "No protocol specified\n";
- return (XID) ~0L;
-}
-
-void
-ResetAuthorization (void)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++)
- if (protocols[i].Reset)
- (*protocols[i].Reset)();
- ShouldLoadAuth = TRUE;
-}
-
-XID
-AuthorizationToID (
- unsigned short name_length,
- char *name,
- unsigned short data_length,
- char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].ToID)
- {
- return (*protocols[i].ToID) (data_length, data);
- }
- }
- return (XID) ~0L;
-}
-
-int
-AuthorizationFromID (
- XID id,
- unsigned short *name_lenp,
- char **namep,
- unsigned short *data_lenp,
- char **datap)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].FromID &&
- (*protocols[i].FromID) (id, data_lenp, datap)) {
- *name_lenp = protocols[i].name_length;
- *namep = protocols[i].name;
- return 1;
- }
- }
- return 0;
-}
-
-int
-RemoveAuthorization (
- unsigned short name_length,
- char *name,
- unsigned short data_length,
- char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Remove)
- {
- return (*protocols[i].Remove) (data_length, data);
- }
- }
- return 0;
-}
-
-int
-AddAuthorization (unsigned name_length, char *name, unsigned data_length, char *data)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Add)
- {
- return (*protocols[i].Add) (data_length, data, FakeClientID(0));
- }
- }
- return 0;
-}
-
-#ifdef XCSECURITY
-
-XID
-GenerateAuthorization(
- unsigned name_length,
- char *name,
- unsigned data_length,
- char *data,
- unsigned *data_length_return,
- char **data_return)
-{
- int i;
-
- for (i = 0; i < NUM_AUTHORIZATION; i++) {
- if (protocols[i].name_length == name_length &&
- memcmp (protocols[i].name, name, (int) name_length) == 0 &&
- protocols[i].Generate)
- {
- return (*protocols[i].Generate) (data_length, data,
- FakeClientID(0), data_length_return, data_return);
- }
- }
- return -1;
-}
-
-/* A random number generator that is more unpredictable
- than that shipped with some systems.
- This code is taken from the C standard. */
-
-static unsigned long int next = 1;
-
-static int
-xdm_rand(void)
-{
- next = next * 1103515245 + 12345;
- return (unsigned int)(next/65536) % 32768;
-}
-
-static void
-xdm_srand(unsigned int seed)
-{
- next = seed;
-}
-
-void
-GenerateRandomData (int len, char *buf)
-{
- static int seed;
- int value;
- int i;
-
- seed += GetTimeInMillis();
- xdm_srand (seed);
- for (i = 0; i < len; i++)
- {
- value = xdm_rand ();
- buf[i] ^= (value & 0xff00) >> 8;
- }
-
- /* XXX add getrusage, popen("ps -ale") */
-}
-
-#endif /* XCSECURITY */
diff --git a/nx-X11/programs/Xserver/os/connection.c.NX.original b/nx-X11/programs/Xserver/os/connection.c.NX.original
deleted file mode 100644
index e3319b338..000000000
--- a/nx-X11/programs/Xserver/os/connection.c.NX.original
+++ /dev/null
@@ -1,1424 +0,0 @@
-/* $Xorg: connection.c,v 1.6 2001/02/09 02:05:23 xorgcvs Exp $ */
-/***********************************************************
-
-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.
-
-******************************************************************/
-/* $XFree86: xc/programs/Xserver/os/connection.c,v 3.64 2003/10/07 22:50:42 herrb Exp $ */
-/*****************************************************************
- * Stuff to create connections --- OS dependent
- *
- * EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets,
- * CloseDownConnection, CheckConnections, AddEnabledDevice,
- * RemoveEnabledDevice, 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
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#define XSERV_t
-#define TRANS_SERVER
-#define TRANS_REOPEN
-#include <X11/Xtrans/Xtrans.h>
-#include <errno.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#ifndef WIN32
-#if defined(Lynx)
-#include <socket.h>
-#else
-#include <sys/socket.h>
-#endif
-
-#ifdef hpux
-#include <sys/utsname.h>
-#include <sys/ioctl.h>
-#endif
-
-#if defined(DGUX)
-#include <sys/ioctl.h>
-#include <sys/utsname.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <sys/param.h>
-#include <unistd.h>
-#endif
-
-
-#ifdef AIXV3
-#include <sys/ioctl.h>
-#endif
-
-#ifdef __UNIXOS2__
-#define select(n,r,w,x,t) os2PseudoSelect(n,r,w,x,t)
-extern __const__ int _nfiles;
-#endif
-
-#if defined(TCPCONN) || defined(STREAMSCONN)
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# if !defined(hpux)
-# ifdef apollo
-# ifndef NO_TCP_H
-# include <netinet/tcp.h>
-# endif
-# else
-# ifdef CSRG_BASED
-# include <sys/param.h>
-# endif
-# ifndef __UNIXOS2__
-# include <netinet/tcp.h>
-# endif
-# endif
-# endif
-# include <arpa/inet.h>
-#endif
-
-#if !defined(__UNIXOS2__)
-#ifndef Lynx
-#include <sys/uio.h>
-#else
-#include <uio.h>
-#endif
-#endif
-#endif /* WIN32 */
-#include "misc.h" /* for typedef of pointer */
-#include "osdep.h"
-#include <X11/Xpoll.h>
-#include "opaque.h"
-#include "dixstruct.h"
-#ifdef XAPPGROUP
-#include <X11/extensions/Xagsrv.h>
-#endif
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-#include <X11/extensions/security.h>
-#endif
-#ifdef LBX
-#include "colormapst.h"
-#include "propertyst.h"
-#include "lbxserve.h"
-#include "osdep.h"
-#endif
-
-#ifdef X_NOT_POSIX
-#define Pid_t int
-#else
-#define Pid_t pid_t
-#endif
-
-#ifdef DNETCONN
-#include <netdnet/dn.h>
-#endif /* DNETCONN */
-
-int lastfdesc; /* maximum file descriptor */
-
-fd_set WellKnownConnections; /* Listener mask */
-fd_set EnabledDevices; /* mask for input devices that are on */
-fd_set AllSockets; /* select on this */
-fd_set AllClients; /* available clients */
-fd_set LastSelectMask; /* 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;
-Bool NewOutputPending; /* not yet attempted to write some new output */
-Bool AnyClientsWriteBlocked; /* true if some client blocked on write */
-
-Bool RunFromSmartParent; /* send SIGUSR1 to parent process */
-Bool PartialNetwork; /* continue even if unable to bind all addrs */
-static Pid_t ParentProcess;
-#ifdef __UNIXOS2__
-Pid_t GetPPID(Pid_t pid);
-#endif
-
-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;
-
-#if !defined(WIN32)
-int *ConnectionTranslation = NULL;
-#else
-/*
- * On NT fds are not between 0 and MAXSOCKS, they are unrelated, and there is
- * not even a known maximum value, so use something quite arbitrary for now.
- * Do storage is a hash table of size 256. Collisions are handled in a linked
- * list.
- */
-
-#undef MAXSOCKS
-#define MAXSOCKS 500
-#undef MAXSELECT
-#define MAXSELECT 500
-#define MAXFD 500
-
-struct _ct_node {
- struct _ct_node *next;
- int key;
- int value;
-};
-
-struct _ct_node *ct_head[256];
-
-void InitConnectionTranslation(void)
-{
- bzero(ct_head, sizeof(ct_head));
-}
-
-int GetConnectionTranslation(int conn)
-{
- struct _ct_node *node = ct_head[conn & 0xff];
- while (node != NULL)
- {
- if (node->key == conn)
- return node->value;
- node = node->next;
- }
- return 0;
-}
-
-void SetConnectionTranslation(int conn, int client)
-{
- struct _ct_node **node = ct_head + (conn & 0xff);
- if (client == 0) /* remove entry */
- {
- while (*node != NULL)
- {
- if ((*node)->key == conn)
- {
- struct _ct_node *temp = *node;
- *node = (*node)->next;
- free(temp);
- return;
- }
- node = &((*node)->next);
- }
- return;
- } else
- {
- while (*node != NULL)
- {
- if ((*node)->key == conn)
- {
- (*node)->value = client;
- return;
- }
- node = &((*node)->next);
- }
- *node = (struct _ct_node*)xalloc(sizeof(struct _ct_node));
- (*node)->next = NULL;
- (*node)->key = conn;
- (*node)->value = client;
- return;
- }
-}
-
-void ClearConnectionTranslation(void)
-{
- unsigned i;
- for (i = 0; i < 256; i++)
- {
- struct _ct_node *node = ct_head[i];
- while (node != NULL)
- {
- struct _ct_node *temp = node;
- node = node->next;
- xfree(temp);
- }
- }
-}
-#endif
-
-XtransConnInfo *ListenTransConns = NULL;
-int *ListenTransFds = NULL;
-int ListenTransCount;
-
-static void ErrorConnMax(XtransConnInfo /* trans_conn */);
-
-#ifndef LBX
-static
-void CloseDownFileDescriptor(
- OsCommPtr /*oc*/
-);
-#endif
-
-
-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__
-
-#ifndef __UNIXOS2__
-
-#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
-
-#else /* __UNIXOS2__ */
- lastfdesc = _nfiles - 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
-
-#if !defined(WIN32)
- ConnectionTranslation = (int *)xnfalloc(sizeof(int)*(lastfdesc + 1));
-#else
- InitConnectionTranslation();
-#endif
-}
-
-
-/*****************
- * CreateWellKnownSockets
- * At initialization, create the sockets to listen on for new clients.
- *****************/
-
-void
-CreateWellKnownSockets(void)
-{
- int i;
- int partial;
- char port[20];
- OsSigHandlerPtr handler;
-
- FD_ZERO(&AllSockets);
- FD_ZERO(&AllClients);
- FD_ZERO(&LastSelectMask);
- FD_ZERO(&ClientsWithInput);
-
-#if !defined(WIN32)
- for (i=0; i<MaxClients; i++) ConnectionTranslation[i] = 0;
-#else
- ClearConnectionTranslation();
-#endif
-
- FD_ZERO (&WellKnownConnections);
-
- sprintf (port, "%d", atoi (display));
-
- if ((_XSERVTransMakeAllCOTSServerListeners (port, &partial,
- &ListenTransCount, &ListenTransConns) >= 0) &&
- (ListenTransCount >= 1))
- {
- if (!PartialNetwork && partial)
- {
- FatalError ("Failed to establish all listening sockets");
- }
- else
- {
- ListenTransFds = (int *) xalloc (ListenTransCount * sizeof (int));
-
- for (i = 0; i < ListenTransCount; i++)
- {
- int fd = _XSERVTransGetConnectionNumber (ListenTransConns[i]);
-
- ListenTransFds[i] = fd;
- FD_SET (fd, &WellKnownConnections);
-
- if (!_XSERVTransIsLocal (ListenTransConns[i]))
- {
- DefineSelf (fd);
- }
- }
- }
- }
-
- if (!XFD_ANYSET (&WellKnownConnections))
- FatalError ("Cannot establish any listening sockets - Make sure an X server isn't already running");
-#if !defined(WIN32)
- OsSignal (SIGPIPE, SIG_IGN);
- OsSignal (SIGHUP, AutoResetServer);
-#endif
- OsSignal (SIGINT, GiveUp);
- OsSignal (SIGTERM, GiveUp);
- XFD_COPYSET (&WellKnownConnections, &AllSockets);
- ResetHosts(display);
- /*
- * Magic: 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
- */
-#if !defined(WIN32)
- 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__ */
- if (RunFromSmartParent) {
- if (ParentProcess > 1) {
- kill (ParentProcess, SIGUSR1);
- }
- }
-#endif
-#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.
- */
-
- FD_CLR (ListenTransFds[i], &WellKnownConnections);
- 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]);
-
- FD_CLR (ListenTransFds[i], &WellKnownConnections);
- ListenTransFds[i] = newfd;
- FD_SET(newfd, &WellKnownConnections);
- }
- }
- }
-
- ResetAuthorization ();
- ResetHosts(display);
- /*
- * See above in CreateWellKnownSockets about SIGUSR1
- */
-#if !defined(WIN32)
- if (RunFromSmartParent) {
- if (ParentProcess > 1) {
- kill (ParentProcess, SIGUSR1);
- }
- }
-#endif
- /*
- * restart XDMCP
- */
-#ifdef XDMCP
- XdmcpReset ();
-#endif
-}
-
-void
-CloseWellKnownConnections(void)
-{
- int i;
-
- for (i = 0; i < ListenTransCount; i++)
- _XSERVTransClose (ListenTransConns[i]);
-}
-
-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;
-
- if (!((OsCommPtr)client->osPrivate)->trans_conn) {
- strcpy(addr, "LBX proxy at ");
- out += strlen(addr);
- }
- if (!len)
- strcpy(out, "local host");
- else
- switch (saddr->sa_family)
- {
- case AF_UNSPEC:
-#if defined(UNIXCONN) || defined(LOCALCONN) || defined(OS2PIPECONN)
- case AF_UNIX:
-#endif
- strcpy(out, "local host");
- break;
-#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_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
-#ifdef DNETCONN
- case AF_DECnet:
- sprintf(out, "DN %s",
- dnet_ntoa(&((struct sockaddr_dn *) saddr)->sdn_add));
- break;
-#endif
- default:
- strcpy(out, "unknown address");
- }
-
- if (proto_n)
- AuditF("client %d %s from %s\n Auth name: %.*s ID: %d\n",
- client->index, letin ? "connected" : "rejected", addr,
- (int)proto_n, auth_proto, auth_id);
- else
- AuditF("client %d %s from %s\n",
- client->index, letin ? "connected" : "rejected", addr);
-}
-
-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;
- int restore_trans_conn = 0;
- ClientPtr lbxpc = NULL;
-
- priv = (OsCommPtr)client->osPrivate;
- trans_conn = priv->trans_conn;
-
-#ifdef LBX
- if (!trans_conn) {
- /*
- * Since trans_conn is NULL, this must be a proxy's client for
- * which we have NO address. Therefore, we will temporarily
- * set the client's trans_conn to the proxy's trans_conn and
- * after CheckAuthorization the client's trans_conn will be
- * restored.
- *
- * If XDM-AUTHORIZATION-1 is being used, CheckAuthorization
- * will eventually call XdmAuthorizationValidate and this
- * later function may use the client's trans_conn to get the
- * client's address. Since a XDM-AUTH-1 auth string includes
- * the client's address, this address is compared to the address
- * in the client's trans_conn. If the proxy and client are
- * on the same host, the comparison will fail; otherwise the
- * comparison will fail and the client will not be authorized
- * to connect to the server.
- *
- * The basis for this additional code is to prevent a
- * NULL pointer dereference of the client's trans_conn.
- * The fundamental problem - the fact that the client's
- * trans_conn is NULL - is because the NewClient
- * request in version 1.0 of the LBX protocol does not
- * send the client's address to the server. When the
- * spec is changed and the client's address is sent to
- * server in the NewClient request, this additional code
- * should be removed.
- *
- * See defect number XWSog08218 for more information.
- */
- lbxpc = LbxProxyClient(priv->proxy);
- trans_conn = ((OsCommPtr)lbxpc->osPrivate)->trans_conn;
- priv->trans_conn = trans_conn;
- restore_trans_conn = 1;
- }
-#endif
-
- auth_id = CheckAuthorization (proto_n, auth_proto,
- string_n, auth_string, client, &reason);
-
-#ifdef LBX
- if (! priv->trans_conn) {
- if (auth_id == (XID) ~0L && !GetAccessControl())
- auth_id = ((OsCommPtr)lbxpc->osPrivate)->auth_id;
-#ifdef XCSECURITY
- else if (auth_id != (XID) ~0L && !SecuritySameLevel(lbxpc, auth_id)) {
- auth_id = (XID) ~0L;
- reason = "Client trust level differs from that of LBX Proxy";
- }
-#endif
- }
-#endif
- 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 (
-#ifdef LBX
- !trans_conn ||
-#endif
- 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);
- }
-
- xfree ((char *) from);
- }
-
- if (auth_id == (XID) ~0L) {
-#ifdef LBX
- /*
- * Restore client's trans_conn state
- */
- if (restore_trans_conn) {
- priv->trans_conn = NULL;
- }
-#endif
- 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);
-
- xfree ((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 */
-#ifdef XAPPGROUP
- if (ClientStateCallback)
- XagCallClientStateChange (client);
-#endif
- /* 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.
- */
-#ifdef LBX
- if (restore_trans_conn) {
- priv->trans_conn = NULL;
- }
-#endif
- return((char *)NULL);
-}
-
-static ClientPtr
-#ifdef LBX
-AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time,
- int (*Flush)(
- ClientPtr /*who*/, OsCommPtr /*oc*/,
- char * /*extraBuf*/, int /*extraCount*/),
- void (*Close)(
- ClientPtr /*client*/),
- LbxProxyPtr proxy)
-#else
-AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time)
-#endif
-{
- OsCommPtr oc;
- ClientPtr client;
-
- if (
-#ifdef LBX
- trans_conn &&
-#endif
-#ifndef WIN32
- fd >= lastfdesc
-#else
- XFD_SETCOUNT(&AllClients) >= MaxClients
-#endif
- )
- return NullClient;
- oc = (OsCommPtr)xalloc(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;
-#ifdef LBX
- oc->proxy = proxy;
- oc->Flush = Flush;
- oc->Close = Close;
- oc->largereq = (ConnectionInputPtr) NULL;
-#endif
- if (!(client = NextAvailableClient((pointer)oc)))
- {
- xfree (oc);
- return NullClient;
- }
-#ifdef LBX
- if (trans_conn)
-#endif
- {
-#if !defined(WIN32)
- ConnectionTranslation[fd] = client->index;
-#else
- SetConnectionTranslation(fd, client->index);
-#endif
- 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;
-}
-
-#ifdef LBX
-
-int
-ClientConnectionNumber (ClientPtr client)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- return oc->fd;
-}
-
-ClientPtr
-AllocLbxClientConnection (ClientPtr client, LbxProxyPtr proxy)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- return AllocNewConnection ((XtransConnInfo)NULL, oc->fd, GetTimeInMillis(),
- LbxFlushClient, LbxCloseClient, proxy);
-}
-
-void
-LbxProxyConnection (ClientPtr client, LbxProxyPtr proxy)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- FlushClient(client, oc, (char *)NULL, 0);
- oc->proxy = proxy;
- oc->Flush = LbxFlushClient;
- oc->Close = LbxCloseClient;
- LbxPrimeInput(client, proxy);
-}
-
-#endif
-
-/*****************
- * EstablishNewConnections
- * If anyone is waiting on listened sockets, accept them.
- * Returns a mask with indices of new clients. Updates AllClients
- * and AllSockets.
- *****************/
-
-/*ARGSUSED*/
-Bool
-EstablishNewConnections(ClientPtr clientUnused, pointer closure)
-{
- fd_set readyconnections; /* set of listeners that are ready */
- int curconn; /* fd of listener that's ready */
- register int newconn; /* fd of new client */
- CARD32 connect_time;
- register int i;
- register ClientPtr client;
- register OsCommPtr oc;
- fd_set tmask;
-
- XFD_ANDSET (&tmask, (fd_set*)closure, &WellKnownConnections);
- XFD_COPYSET(&tmask, &readyconnections);
- if (!XFD_ANYSET(&readyconnections))
- return TRUE;
- 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);
- }
- }
-#ifndef WIN32
- for (i = 0; i < howmany(XFD_SETSIZE, NFDBITS); i++)
- {
- while (readyconnections.fds_bits[i])
-#else
- for (i = 0; i < XFD_SETCOUNT(&readyconnections); i++)
-#endif
- {
- XtransConnInfo trans_conn, new_trans_conn;
- int status;
-
-#ifndef WIN32
- curconn = ffs (readyconnections.fds_bits[i]) - 1;
- readyconnections.fds_bits[i] &= ~((fd_mask)1 << curconn);
- curconn += (i * (sizeof(fd_mask)*8));
-#else
- curconn = XFD_FD(&readyconnections, i);
-#endif
-
- if ((trans_conn = lookup_trans_conn (curconn)) == NULL)
- continue;
-
- if ((new_trans_conn = _XSERVTransAccept (trans_conn, &status)) == NULL)
- continue;
-
- newconn = _XSERVTransGetConnectionNumber (new_trans_conn);
-
- if (newconn < lastfdesc)
- {
- int clientid;
-#if !defined(WIN32)
- clientid = ConnectionTranslation[newconn];
-#else
- clientid = GetConnectionTranslation(newconn);
-#endif
- if(clientid && (client = clients[clientid]))
- CloseDownClient(client);
- }
-
- _XSERVTransSetOption(new_trans_conn, TRANS_NONBLOCKING, 1);
-
- if (!AllocNewConnection (new_trans_conn, newconn, connect_time
-#ifdef LBX
- , StandardFlushClient,
- CloseDownFileDescriptor, (LbxProxyPtr)NULL
-#endif
- ))
- {
- ErrorConnMax(new_trans_conn);
- _XSERVTransClose(new_trans_conn);
- }
- }
-#ifndef WIN32
- }
-#endif
- return TRUE;
-}
-
-#define NOROOM "Maximum number of clients reached"
-
-/************
- * ErrorConnMax
- * Fail a connection due to lack of client or file descriptor space
- ************/
-
-static void
-ErrorConnMax(XtransConnInfo trans_conn)
-{
- int fd = _XSERVTransGetConnectionNumber (trans_conn);
- xConnSetupPrefix csp;
- char pad[3];
- struct iovec iov[3];
- char byteOrder = 0;
- int whichbyte = 1;
- struct timeval waittime;
- fd_set mask;
-
- /* if these seems like a lot of trouble to go to, it probably is */
- waittime.tv_sec = BOTIMEOUT / MILLI_PER_SECOND;
- waittime.tv_usec = (BOTIMEOUT % MILLI_PER_SECOND) *
- (1000000 / MILLI_PER_SECOND);
- FD_ZERO(&mask);
- FD_SET(fd, &mask);
- (void)Select(fd + 1, &mask, NULL, NULL, &waittime);
- /* try to read the byte-order of the connection */
- (void)_XSERVTransRead(trans_conn, &byteOrder, 1);
- if ((byteOrder == 'l') || (byteOrder == 'B'))
- {
- 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) && (byteOrder == 'B')) ||
- (!(*(char *) &whichbyte) && (byteOrder == 'l')))
- {
- swaps(&csp.majorVersion, whichbyte);
- swaps(&csp.minorVersion, whichbyte);
- swaps(&csp.length, whichbyte);
- }
- 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);
- }
-}
-
-/************
- * CloseDownFileDescriptor:
- * Remove this file descriptor and it's I/O buffers, etc.
- ************/
-
-#ifdef LBX
-void
-CloseDownFileDescriptor(ClientPtr client)
-#else
-static void
-CloseDownFileDescriptor(OsCommPtr oc)
-#endif
-{
-#ifdef LBX
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-#endif
- int connection = oc->fd;
-
- if (oc->trans_conn) {
- _XSERVTransDisconnect(oc->trans_conn);
- _XSERVTransClose(oc->trans_conn);
- }
-#ifndef LBX
- FreeOsBuffers(oc);
- xfree(oc);
-#endif
-#ifndef WIN32
- ConnectionTranslation[connection] = 0;
-#else
- SetConnectionTranslation(connection, 0);
-#endif
- 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))
- AnyClientsWriteBlocked = 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)
-{
-#ifndef WIN32
- fd_mask mask;
-#endif
- fd_set tmask;
- int curclient, curoff;
- int i;
- struct timeval notime;
- int r;
-#ifdef WIN32
- fd_set savedAllClients;
-#endif
-
- notime.tv_sec = 0;
- notime.tv_usec = 0;
-
-#ifndef WIN32
- 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);
- }
- }
-#else
- XFD_COPYSET(&AllClients, &savedAllClients);
- for (i = 0; i < XFD_SETCOUNT(&savedAllClients); i++)
- {
- curclient = XFD_FD(&savedAllClients, i);
- FD_ZERO(&tmask);
- FD_SET(curclient, &tmask);
- r = Select (curclient + 1, &tmask, NULL, NULL, &notime);
- if (r < 0)
- CloseDownClient(clients[GetConnectionTranslation(curclient)]);
- }
-#endif
-}
-
-
-/*****************
- * CloseDownConnection
- * Delete client from AllClients and free resources
- *****************/
-
-void
-CloseDownConnection(ClientPtr client)
-{
- OsCommPtr oc = (OsCommPtr)client->osPrivate;
-
- if (oc->output && oc->output->count)
- FlushClient(client, oc, (char *)NULL, 0);
-#ifdef XDMCP
- XdmcpCloseDisplay(oc->fd);
-#endif
-#ifndef LBX
- CloseDownFileDescriptor(oc);
-#else
- (*oc->Close) (client);
- FreeOsBuffers(oc);
- xfree(oc);
-#endif
- client->osPrivate = (pointer)NULL;
- if (auditTrailLevel > 1)
- AuditF("client %d disconnected\n", client->index);
-}
-
-void
-AddEnabledDevice(int fd)
-{
- FD_SET(fd, &EnabledDevices);
- FD_SET(fd, &AllSockets);
- if (GrabInProgress)
- FD_SET(fd, &SavedAllSockets);
-}
-
-void
-RemoveEnabledDevice(int fd)
-{
- FD_CLR(fd, &EnabledDevices);
- FD_CLR(fd, &AllSockets);
- if (GrabInProgress)
- FD_CLR(fd, &SavedAllSockets);
-}
-
-/*****************
- * 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;
-#ifdef LBX
- LbxClientPtr lbxClient = LbxClient(client);
-#endif
-
- isItTimeToYield = TRUE;
-#ifdef LBX
- if (lbxClient) {
- lbxClient->ignored = TRUE;
- return;
- }
-#endif
- 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;
-#ifdef LBX
- LbxClientPtr lbxClient = LbxClient(client);
-
- if (lbxClient) {
- lbxClient->ignored = FALSE;
- return;
- }
-#endif
- 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);
- }
-}
-
diff --git a/nx-X11/programs/Xserver/os/connection.c.X.original b/nx-X11/programs/Xserver/os/connection.c.X.original
deleted file mode 100644
index 0a12c655d..000000000
--- a/nx-X11/programs/Xserver/os/connection.c.X.original
+++ /dev/null
@@ -1,1385 +0,0 @@
-/* $Xorg: connection.c,v 1.6 2001/02/09 02:05:23 xorgcvs Exp $ */
-/***********************************************************
-
-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.
-
-******************************************************************/
-/* $XFree86: xc/programs/Xserver/os/connection.c,v 3.64 2003/10/07 22:50:42 herrb Exp $ */
-/*****************************************************************
- * Stuff to create connections --- OS dependent
- *
- * EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets,
- * CloseDownConnection, CheckConnections, AddEnabledDevice,
- * RemoveEnabledDevice, 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
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#define XSERV_t
-#define TRANS_SERVER
-#define TRANS_REOPEN
-#include <X11/Xtrans/Xtrans.h>
-#include <errno.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#ifndef WIN32
-#if defined(Lynx)
-#include <socket.h>
-#else
-#include <sys/socket.h>
-#endif
-
-#ifdef hpux
-#include <sys/utsname.h>
-#include <sys/ioctl.h>
-#endif
-
-#if defined(DGUX)
-#include <sys/ioctl.h>
-#include <sys/utsname.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <sys/param.h>
-#include <unistd.h>
-#endif
-
-
-#ifdef AIXV3
-#include <sys/ioctl.h>
-#endif
-
-#ifdef __UNIXOS2__
-#define select(n,r,w,x,t) os2PseudoSelect(n,r,w,x,t)
-extern __const__ int _nfiles;
-#endif
-
-#if defined(TCPCONN) || defined(STREAMSCONN)
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# if !defined(hpux)
-# ifdef apollo
-# ifndef NO_TCP_H
-# include <netinet/tcp.h>
-# endif
-# else
-# ifdef CSRG_BASED
-# include <sys/param.h>
-# endif
-# ifndef __UNIXOS2__
-# include <netinet/tcp.h>
-# endif
-# endif
-# endif
-# include <arpa/inet.h>
-#endif
-
-#if !defined(__UNIXOS2__)
-#ifndef Lynx
-#include <sys/uio.h>
-#else
-#include <uio.h>
-#endif
-#endif
-#endif /* WIN32 */
-#include "misc.h" /* for typedef of pointer */
-#include "osdep.h"
-#include <X11/Xpoll.h>
-#include "opaque.h"
-#include "dixstruct.h"
-#ifdef XAPPGROUP
-#include <X11/extensions/Xagsrv.h>
-#endif
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-#include <X11/extensions/security.h>
-#endif
-#ifdef LBX
-#include "colormapst.h"
-#include "propertyst.h"
-#include "lbxserve.h"
-#include "osdep.h"
-#endif
-
-#ifdef X_NOT_POSIX
-#define Pid_t int
-#else
-#define Pid_t pid_t
-#endif
-
-#ifdef DNETCONN
-#include <netdnet/dn.h>
-#endif /* DNETCONN */
-
-int lastfdesc; /* maximum file descriptor */
-
-fd_set WellKnownConnections; /* Listener mask */
-fd_set EnabledDevices; /* mask for input devices that are on */
-fd_set AllSockets; /* select on this */
-fd_set AllClients; /* available clients */
-fd_set LastSelectMask; /* 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;
-Bool NewOutputPending; /* not yet attempted to write some new output */
-Bool AnyClientsWriteBlocked; /* true if some client blocked on write */
-
-Bool RunFromSmartParent; /* send SIGUSR1 to parent process */
-Bool PartialNetwork; /* continue even if unable to bind all addrs */
-static Pid_t ParentProcess;
-#ifdef __UNIXOS2__
-Pid_t GetPPID(Pid_t pid);
-#endif
-
-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;
-
-#if !defined(WIN32)
-int *ConnectionTranslation = NULL;
-#else
-/*
- * On NT fds are not between 0 and MAXSOCKS, they are unrelated, and there is
- * not even a known maximum value, so use something quite arbitrary for now.
- * Do storage is a hash table of size 256. Collisions are handled in a linked
- * list.
- */
-
-#undef MAXSOCKS
-#define MAXSOCKS 500
-#undef MAXSELECT
-#define MAXSELECT 500
-#define MAXFD 500
-
-struct _ct_node {
- struct _ct_node *next;
- int key;
- int value;
-};
-
-struct _ct_node *ct_head[256];
-
-void InitConnectionTranslation(void)
-{
- bzero(ct_head, sizeof(ct_head));
-}
-
-int GetConnectionTranslation(int conn)
-{
- struct _ct_node *node = ct_head[conn & 0xff];
- while (node != NULL)
- {
- if (node->key == conn)
- return node->value;
- node = node->next;
- }
- return 0;
-}
-
-void SetConnectionTranslation(int conn, int client)
-{
- struct _ct_node **node = ct_head + (conn & 0xff);
- if (client == 0) /* remove entry */
- {
- while (*node != NULL)
- {
- if ((*node)->key == conn)
- {
- struct _ct_node *temp = *node;
- *node = (*node)->next;
- free(temp);
- return;
- }
- node = &((*node)->next);
- }
- return;
- } else
- {
- while (*node != NULL)
- {
- if ((*node)->key == conn)
- {
- (*node)->value = client;
- return;
- }
- node = &((*node)->next);
- }
- *node = (struct _ct_node*)xalloc(sizeof(struct _ct_node));
- (*node)->next = NULL;
- (*node)->key = conn;
- (*node)->value = client;
- return;
- }
-}
-
-void ClearConnectionTranslation(void)
-{
- unsigned i;
- for (i = 0; i < 256; i++)
- {
- struct _ct_node *node = ct_head[i];
- while (node != NULL)
- {
- struct _ct_node *temp = node;
- node = node->next;
- xfree(temp);
- }
- }
-}
-#endif
-
-XtransConnInfo *ListenTransConns = NULL;
-int *ListenTransFds = NULL;
-int ListenTransCount;
-
-static void ErrorConnMax(XtransConnInfo /* trans_conn */);
-
-#ifndef LBX
-static
-void CloseDownFileDescriptor(
- OsCommPtr /*oc*/
-);
-#endif
-
-
-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__
-
-#ifndef __UNIXOS2__
-
-#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
-
-#else /* __UNIXOS2__ */
- lastfdesc = _nfiles - 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
-
-#if !defined(WIN32)
- ConnectionTranslation = (int *)xnfalloc(sizeof(int)*(lastfdesc + 1));
-#else
- InitConnectionTranslation();
-#endif
-}
-
-
-/*****************
- * CreateWellKnownSockets
- * At initialization, create the sockets to listen on for new clients.
- *****************/
-
-void
-CreateWellKnownSockets(void)
-{
- int i;
- int partial;
- char port[20];
- OsSigHandlerPtr handler;
-
- FD_ZERO(&AllSockets);
- FD_ZERO(&AllClients);
- FD_ZERO(&LastSelectMask);
- FD_ZERO(&ClientsWithInput);
-
-#if !defined(WIN32)
- for (i=0; i<MaxClients; i++) ConnectionTranslation[i] = 0;
-#else
- ClearConnectionTranslation();
-#endif
-
- FD_ZERO (&WellKnownConnections);
-
- sprintf (port, "%d", atoi (display));
-
- if ((_XSERVTransMakeAllCOTSServerListeners (port, &partial,
- &ListenTransCount, &ListenTransConns) >= 0) &&
- (ListenTransCount >= 1))
- {
- if (!PartialNetwork && partial)
- {
- FatalError ("Failed to establish all listening sockets");
- }
- else
- {
- ListenTransFds = (int *) xalloc (ListenTransCount * sizeof (int));
-
- for (i = 0; i < ListenTransCount; i++)
- {
- int fd = _XSERVTransGetConnectionNumber (ListenTransConns[i]);
-
- ListenTransFds[i] = fd;
- FD_SET (fd, &WellKnownConnections);
-
- if (!_XSERVTransIsLocal (ListenTransConns[i]))
- {
- DefineSelf (fd);
- }
- }
- }
- }
-
- if (!XFD_ANYSET (&WellKnownConnections))
- FatalError ("Cannot establish any listening sockets - Make sure an X server isn't already running");
-#if !defined(WIN32)
- OsSignal (SIGPIPE, SIG_IGN);
- OsSignal (SIGHUP, AutoResetServer);
-#endif
- OsSignal (SIGINT, GiveUp);
- OsSignal (SIGTERM, GiveUp);
- XFD_COPYSET (&WellKnownConnections, &AllSockets);
- ResetHosts(display);
- /*
- * Magic: 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
- */
-#if !defined(WIN32)
- 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__ */
- if (RunFromSmartParent) {
- if (ParentProcess > 1) {
- kill (ParentProcess, SIGUSR1);
- }
- }
-#endif
-#ifdef XDMCP
- XdmcpInit ();
-#endif
-}
-
-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.
- */
-
- FD_CLR (ListenTransFds[i], &WellKnownConnections);
- 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]);
-
- FD_CLR (ListenTransFds[i], &WellKnownConnections);
- ListenTransFds[i] = newfd;
- FD_SET(newfd, &WellKnownConnections);
- }
- }
- }
-
- ResetAuthorization ();
- ResetHosts(display);
- /*
- * See above in CreateWellKnownSockets about SIGUSR1
- */
-#if !defined(WIN32)
- if (RunFromSmartParent) {
- if (ParentProcess > 1) {
- kill (ParentProcess, SIGUSR1);
- }
- }
-#endif
- /*
- * restart XDMCP
- */
-#ifdef XDMCP
- XdmcpReset ();
-#endif
-}
-
-void
-CloseWellKnownConnections(void)
-{
- int i;
-
- for (i = 0; i < ListenTransCount; i++)
- _XSERVTransClose (ListenTransConns[i]);
-}
-
-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;
-
- if (!((OsCommPtr)client->osPrivate)->trans_conn) {
- strcpy(addr, "LBX proxy at ");
- out += strlen(addr);
- }
- if (!len)
- strcpy(out, "local host");
- else
- switch (saddr->sa_family)
- {
- case AF_UNSPEC:
-#if defined(UNIXCONN) || defined(LOCALCONN) || defined(OS2PIPECONN)
- case AF_UNIX:
-#endif
- strcpy(out, "local host");
- break;
-#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_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
-#ifdef DNETCONN
- case AF_DECnet:
- sprintf(out, "DN %s",
- dnet_ntoa(&((struct sockaddr_dn *) saddr)->sdn_add));
- break;
-#endif
- default:
- strcpy(out, "unknown address");
- }
-
- if (proto_n)
- AuditF("client %d %s from %s\n Auth name: %.*s ID: %d\n",
- client->index, letin ? "connected" : "rejected", addr,
- (int)proto_n, auth_proto, auth_id);
- else
- AuditF("client %d %s from %s\n",
- client->index, letin ? "connected" : "rejected", addr);
-}
-
-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;
- int restore_trans_conn = 0;
- ClientPtr lbxpc = NULL;
-
- priv = (OsCommPtr)client->osPrivate;
- trans_conn = priv->trans_conn;
-
-#ifdef LBX
- if (!trans_conn) {
- /*
- * Since trans_conn is NULL, this must be a proxy's client for
- * which we have NO address. Therefore, we will temporarily
- * set the client's trans_conn to the proxy's trans_conn and
- * after CheckAuthorization the client's trans_conn will be
- * restored.
- *
- * If XDM-AUTHORIZATION-1 is being used, CheckAuthorization
- * will eventually call XdmAuthorizationValidate and this
- * later function may use the client's trans_conn to get the
- * client's address. Since a XDM-AUTH-1 auth string includes
- * the client's address, this address is compared to the address
- * in the client's trans_conn. If the proxy and client are
- * on the same host, the comparison will fail; otherwise the
- * comparison will fail and the client will not be authorized
- * to connect to the server.
- *
- * The basis for this additional code is to prevent a
- * NULL pointer dereference of the client's trans_conn.
- * The fundamental problem - the fact that the client's
- * trans_conn is NULL - is because the NewClient
- * request in version 1.0 of the LBX protocol does not
- * send the client's address to the server. When the
- * spec is changed and the client's address is sent to
- * server in the NewClient request, this additional code
- * should be removed.
- *
- * See defect number XWSog08218 for more information.
- */
- lbxpc = LbxProxyClient(priv->proxy);
- trans_conn = ((OsCommPtr)lbxpc->osPrivate)->trans_conn;
- priv->trans_conn = trans_conn;
- restore_trans_conn = 1;
- }
-#endif
-
- auth_id = CheckAuthorization (proto_n, auth_proto,
- string_n, auth_string, client, &reason);
-
-#ifdef LBX
- if (! priv->trans_conn) {
- if (auth_id == (XID) ~0L && !GetAccessControl())
- auth_id = ((OsCommPtr)lbxpc->osPrivate)->auth_id;
-#ifdef XCSECURITY
- else if (auth_id != (XID) ~0L && !SecuritySameLevel(lbxpc, auth_id)) {
- auth_id = (XID) ~0L;
- reason = "Client trust level differs from that of LBX Proxy";
- }
-#endif
- }
-#endif
- 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 (
-#ifdef LBX
- !trans_conn ||
-#endif
- 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);
- }
-
- xfree ((char *) from);
- }
-
- if (auth_id == (XID) ~0L) {
-#ifdef LBX
- /*
- * Restore client's trans_conn state
- */
- if (restore_trans_conn) {
- priv->trans_conn = NULL;
- }
-#endif
- 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);
-
- xfree ((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 */
-#ifdef XAPPGROUP
- if (ClientStateCallback)
- XagCallClientStateChange (client);
-#endif
- /* 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.
- */
-#ifdef LBX
- if (restore_trans_conn) {
- priv->trans_conn = NULL;
- }
-#endif
- return((char *)NULL);
-}
-
-static ClientPtr
-#ifdef LBX
-AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time,
- int (*Flush)(
- ClientPtr /*who*/, OsCommPtr /*oc*/,
- char * /*extraBuf*/, int /*extraCount*/),
- void (*Close)(
- ClientPtr /*client*/),
- LbxProxyPtr proxy)
-#else
-AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time)
-#endif
-{
- OsCommPtr oc;
- ClientPtr client;
-
- if (
-#ifdef LBX
- trans_conn &&
-#endif
-#ifndef WIN32
- fd >= lastfdesc
-#else
- XFD_SETCOUNT(&AllClients) >= MaxClients
-#endif
- )
- return NullClient;
- oc = (OsCommPtr)xalloc(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;
-#ifdef LBX
- oc->proxy = proxy;
- oc->Flush = Flush;
- oc->Close = Close;
- oc->largereq = (ConnectionInputPtr) NULL;
-#endif
- if (!(client = NextAvailableClient((pointer)oc)))
- {
- xfree (oc);
- return NullClient;
- }
-#ifdef LBX
- if (trans_conn)
-#endif
- {
-#if !defined(WIN32)
- ConnectionTranslation[fd] = client->index;
-#else
- SetConnectionTranslation(fd, client->index);
-#endif
- 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;
-}
-
-#ifdef LBX
-
-int
-ClientConnectionNumber (ClientPtr client)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- return oc->fd;
-}
-
-ClientPtr
-AllocLbxClientConnection (ClientPtr client, LbxProxyPtr proxy)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- return AllocNewConnection ((XtransConnInfo)NULL, oc->fd, GetTimeInMillis(),
- LbxFlushClient, LbxCloseClient, proxy);
-}
-
-void
-LbxProxyConnection (ClientPtr client, LbxProxyPtr proxy)
-{
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-
- FlushClient(client, oc, (char *)NULL, 0);
- oc->proxy = proxy;
- oc->Flush = LbxFlushClient;
- oc->Close = LbxCloseClient;
- LbxPrimeInput(client, proxy);
-}
-
-#endif
-
-/*****************
- * EstablishNewConnections
- * If anyone is waiting on listened sockets, accept them.
- * Returns a mask with indices of new clients. Updates AllClients
- * and AllSockets.
- *****************/
-
-/*ARGSUSED*/
-Bool
-EstablishNewConnections(ClientPtr clientUnused, pointer closure)
-{
- fd_set readyconnections; /* set of listeners that are ready */
- int curconn; /* fd of listener that's ready */
- register int newconn; /* fd of new client */
- CARD32 connect_time;
- register int i;
- register ClientPtr client;
- register OsCommPtr oc;
- fd_set tmask;
-
- XFD_ANDSET (&tmask, (fd_set*)closure, &WellKnownConnections);
- XFD_COPYSET(&tmask, &readyconnections);
- if (!XFD_ANYSET(&readyconnections))
- return TRUE;
- 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);
- }
- }
-#ifndef WIN32
- for (i = 0; i < howmany(XFD_SETSIZE, NFDBITS); i++)
- {
- while (readyconnections.fds_bits[i])
-#else
- for (i = 0; i < XFD_SETCOUNT(&readyconnections); i++)
-#endif
- {
- XtransConnInfo trans_conn, new_trans_conn;
- int status;
-
-#ifndef WIN32
- curconn = ffs (readyconnections.fds_bits[i]) - 1;
- readyconnections.fds_bits[i] &= ~((fd_mask)1 << curconn);
- curconn += (i * (sizeof(fd_mask)*8));
-#else
- curconn = XFD_FD(&readyconnections, i);
-#endif
-
- if ((trans_conn = lookup_trans_conn (curconn)) == NULL)
- continue;
-
- if ((new_trans_conn = _XSERVTransAccept (trans_conn, &status)) == NULL)
- continue;
-
- newconn = _XSERVTransGetConnectionNumber (new_trans_conn);
-
- if (newconn < lastfdesc)
- {
- int clientid;
-#if !defined(WIN32)
- clientid = ConnectionTranslation[newconn];
-#else
- clientid = GetConnectionTranslation(newconn);
-#endif
- if(clientid && (client = clients[clientid]))
- CloseDownClient(client);
- }
-
- _XSERVTransSetOption(new_trans_conn, TRANS_NONBLOCKING, 1);
-
- if (!AllocNewConnection (new_trans_conn, newconn, connect_time
-#ifdef LBX
- , StandardFlushClient,
- CloseDownFileDescriptor, (LbxProxyPtr)NULL
-#endif
- ))
- {
- ErrorConnMax(new_trans_conn);
- _XSERVTransClose(new_trans_conn);
- }
- }
-#ifndef WIN32
- }
-#endif
- return TRUE;
-}
-
-#define NOROOM "Maximum number of clients reached"
-
-/************
- * ErrorConnMax
- * Fail a connection due to lack of client or file descriptor space
- ************/
-
-static void
-ErrorConnMax(XtransConnInfo trans_conn)
-{
- int fd = _XSERVTransGetConnectionNumber (trans_conn);
- xConnSetupPrefix csp;
- char pad[3];
- struct iovec iov[3];
- char byteOrder = 0;
- int whichbyte = 1;
- struct timeval waittime;
- fd_set mask;
-
- /* if these seems like a lot of trouble to go to, it probably is */
- waittime.tv_sec = BOTIMEOUT / MILLI_PER_SECOND;
- waittime.tv_usec = (BOTIMEOUT % MILLI_PER_SECOND) *
- (1000000 / MILLI_PER_SECOND);
- FD_ZERO(&mask);
- FD_SET(fd, &mask);
- (void)Select(fd + 1, &mask, NULL, NULL, &waittime);
- /* try to read the byte-order of the connection */
- (void)_XSERVTransRead(trans_conn, &byteOrder, 1);
- if ((byteOrder == 'l') || (byteOrder == 'B'))
- {
- 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) && (byteOrder == 'B')) ||
- (!(*(char *) &whichbyte) && (byteOrder == 'l')))
- {
- swaps(&csp.majorVersion, whichbyte);
- swaps(&csp.minorVersion, whichbyte);
- swaps(&csp.length, whichbyte);
- }
- 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);
- }
-}
-
-/************
- * CloseDownFileDescriptor:
- * Remove this file descriptor and it's I/O buffers, etc.
- ************/
-
-#ifdef LBX
-void
-CloseDownFileDescriptor(ClientPtr client)
-#else
-static void
-CloseDownFileDescriptor(OsCommPtr oc)
-#endif
-{
-#ifdef LBX
- OsCommPtr oc = (OsCommPtr) client->osPrivate;
-#endif
- int connection = oc->fd;
-
- if (oc->trans_conn) {
- _XSERVTransDisconnect(oc->trans_conn);
- _XSERVTransClose(oc->trans_conn);
- }
-#ifndef LBX
- FreeOsBuffers(oc);
- xfree(oc);
-#endif
-#ifndef WIN32
- ConnectionTranslation[connection] = 0;
-#else
- SetConnectionTranslation(connection, 0);
-#endif
- 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))
- AnyClientsWriteBlocked = 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)
-{
-#ifndef WIN32
- fd_mask mask;
-#endif
- fd_set tmask;
- int curclient, curoff;
- int i;
- struct timeval notime;
- int r;
-#ifdef WIN32
- fd_set savedAllClients;
-#endif
-
- notime.tv_sec = 0;
- notime.tv_usec = 0;
-
-#ifndef WIN32
- 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);
- }
- }
-#else
- XFD_COPYSET(&AllClients, &savedAllClients);
- for (i = 0; i < XFD_SETCOUNT(&savedAllClients); i++)
- {
- curclient = XFD_FD(&savedAllClients, i);
- FD_ZERO(&tmask);
- FD_SET(curclient, &tmask);
- r = Select (curclient + 1, &tmask, NULL, NULL, &notime);
- if (r < 0)
- CloseDownClient(clients[GetConnectionTranslation(curclient)]);
- }
-#endif
-}
-
-
-/*****************
- * CloseDownConnection
- * Delete client from AllClients and free resources
- *****************/
-
-void
-CloseDownConnection(ClientPtr client)
-{
- OsCommPtr oc = (OsCommPtr)client->osPrivate;
-
- if (oc->output && oc->output->count)
- FlushClient(client, oc, (char *)NULL, 0);
-#ifdef XDMCP
- XdmcpCloseDisplay(oc->fd);
-#endif
-#ifndef LBX
- CloseDownFileDescriptor(oc);
-#else
- (*oc->Close) (client);
- FreeOsBuffers(oc);
- xfree(oc);
-#endif
- client->osPrivate = (pointer)NULL;
- if (auditTrailLevel > 1)
- AuditF("client %d disconnected\n", client->index);
-}
-
-void
-AddEnabledDevice(int fd)
-{
- FD_SET(fd, &EnabledDevices);
- FD_SET(fd, &AllSockets);
- if (GrabInProgress)
- FD_SET(fd, &SavedAllSockets);
-}
-
-void
-RemoveEnabledDevice(int fd)
-{
- FD_CLR(fd, &EnabledDevices);
- FD_CLR(fd, &AllSockets);
- if (GrabInProgress)
- FD_CLR(fd, &SavedAllSockets);
-}
-
-/*****************
- * 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;
-#ifdef LBX
- LbxClientPtr lbxClient = LbxClient(client);
-#endif
-
- isItTimeToYield = TRUE;
-#ifdef LBX
- if (lbxClient) {
- lbxClient->ignored = TRUE;
- return;
- }
-#endif
- 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;
-#ifdef LBX
- LbxClientPtr lbxClient = LbxClient(client);
-
- if (lbxClient) {
- lbxClient->ignored = FALSE;
- return;
- }
-#endif
- 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);
- }
-}
-
diff --git a/nx-X11/programs/Xserver/os/log.c.NX.original b/nx-X11/programs/Xserver/os/log.c.NX.original
deleted file mode 100644
index 04e24b8df..000000000
--- a/nx-X11/programs/Xserver/os/log.c.NX.original
+++ /dev/null
@@ -1,716 +0,0 @@
-/*
-
-Copyright 1987, 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 by Digital Equipment Corporation, Maynard, Massachusetts,
-Copyright 1994 Quarterdeck Office Systems.
-
- 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 names of Digital and
-Quarterdeck not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-DIGITAL AND QUARTERDECK DISCLAIM 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.
-
-*/
-
-/*
- * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/* $XFree86: xc/programs/Xserver/os/log.c,v 1.6 2003/11/07 13:45:27 tsi Exp $ */
-
-/**************************************************************************/
-/* */
-/* Copyright (c) 2001, 2011 NoMachine, http://www.nomachine.com/. */
-/* */
-/* NX-X11, NX protocol compression and NX extensions to this software */
-/* are copyright of NoMachine. Redistribution and use of the present */
-/* software is allowed according to terms specified in the file LICENSE */
-/* which comes in the source distribution. */
-/* */
-/* Check http://www.nomachine.com/licensing.html for applicability. */
-/* */
-/* NX and NoMachine are trademarks of Medialogic S.p.A. */
-/* */
-/* All rights reserved. */
-/* */
-/**************************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xos.h>
-#include <stdio.h>
-#include <time.h>
-#include <sys/stat.h>
-#include <stdarg.h>
-#include <stdlib.h> /* for malloc() */
-#include <errno.h>
-
-#include "site.h"
-#include "opaque.h"
-
-#ifdef WIN32
-#include <process.h>
-#define getpid(x) _getpid(x)
-#endif
-
-#ifdef NX_TRANS_SOCKET
-
-#include "NX.h"
-
-#endif
-
-#ifdef DDXOSVERRORF
-void (*OsVendorVErrorFProc)(const char *, va_list args) = NULL;
-#ifdef NX_TRANS_EXIT
-int OsVendorVErrorFFatal = 0;
-#endif
-#endif
-
-static FILE *logFile = NULL;
-static Bool logFlush = FALSE;
-static Bool logSync = FALSE;
-static int logVerbosity = DEFAULT_LOG_VERBOSITY;
-static int logFileVerbosity = DEFAULT_LOG_FILE_VERBOSITY;
-
-/* Buffer to information logged before the log file is opened. */
-static char *saveBuffer = NULL;
-static int bufferSize = 0, bufferUnused = 0, bufferPos = 0;
-static Bool needBuffer = TRUE;
-
-/* Prefix strings for log messages. */
-#ifndef X_UNKNOWN_STRING
-#define X_UNKNOWN_STRING "(\?\?)"
-#endif
-#ifndef X_PROBE_STRING
-#define X_PROBE_STRING "(--)"
-#endif
-#ifndef X_CONFIG_STRING
-#define X_CONFIG_STRING "(**)"
-#endif
-#ifndef X_DEFAULT_STRING
-#define X_DEFAULT_STRING "(==)"
-#endif
-#ifndef X_CMDLINE_STRING
-#define X_CMDLINE_STRING "(++)"
-#endif
-#ifndef X_NOTICE_STRING
-#define X_NOTICE_STRING "(!!)"
-#endif
-#ifndef X_ERROR_STRING
-#define X_ERROR_STRING "(EE)"
-#endif
-#ifndef X_WARNING_STRING
-#define X_WARNING_STRING "(WW)"
-#endif
-#ifndef X_INFO_STRING
-#define X_INFO_STRING "(II)"
-#endif
-#ifndef X_NOT_IMPLEMENTED_STRING
-#define X_NOT_IMPLEMENTED_STRING "(NI)"
-#endif
-
-/*
- * LogInit is called to start logging to a file. It is also called (with
- * NULL arguments) when logging to a file is not wanted. It must always be
- * called, otherwise log messages will continue to accumulate in a buffer.
- *
- * %s, if present in the fname or backup strings, is expanded to the display
- * string.
- */
-
-const char *
-LogInit(const char *fname, const char *backup)
-{
- char *logFileName = NULL;
-
- if (fname && *fname) {
- /* xalloc() can't be used yet. */
- logFileName = malloc(strlen(fname) + strlen(display) + 1);
- if (!logFileName)
- FatalError("Cannot allocate space for the log file name\n");
- sprintf(logFileName, fname, display);
-
- if (backup && *backup) {
- struct stat buf;
-
- if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) {
- char *suffix;
- char *oldLog;
-
- oldLog = malloc(strlen(logFileName) + strlen(backup) +
- strlen(display) + 1);
- suffix = malloc(strlen(backup) + strlen(display) + 1);
- if (!oldLog || !suffix)
- FatalError("Cannot allocate space for the log file name\n");
- sprintf(suffix, backup, display);
- sprintf(oldLog, "%s%s", logFileName, suffix);
- free(suffix);
-#ifdef __UNIXOS2__
- remove(oldLog);
-#endif
- if (rename(logFileName, oldLog) == -1) {
- FatalError("Cannot move old log file (\"%s\" to \"%s\"\n",
- logFileName, oldLog);
- }
- free(oldLog);
- }
- }
- if ((logFile = fopen(logFileName, "w")) == NULL)
- FatalError("Cannot open log file \"%s\"\n", logFileName);
- setvbuf(logFile, NULL, _IONBF, 0);
-
- /* Flush saved log information. */
- if (saveBuffer && bufferSize > 0) {
- fwrite(saveBuffer, bufferPos, 1, logFile);
- fflush(logFile);
-#ifndef WIN32
- fsync(fileno(logFile));
-#endif
- }
- }
-
- /*
- * Unconditionally free the buffer, and flag that the buffer is no longer
- * needed.
- */
- if (saveBuffer && bufferSize > 0) {
- free(saveBuffer); /* Must be free(), not xfree() */
- saveBuffer = NULL;
- bufferSize = 0;
- }
- needBuffer = FALSE;
-
- return logFileName;
-}
-
-void
-LogClose()
-{
- if (logFile) {
- fclose(logFile);
- logFile = NULL;
- }
-}
-
-Bool
-LogSetParameter(LogParameter param, int value)
-{
- switch (param) {
- case XLOG_FLUSH:
- logFlush = value ? TRUE : FALSE;
- return TRUE;
- case XLOG_SYNC:
- logSync = value ? TRUE : FALSE;
- return TRUE;
- case XLOG_VERBOSITY:
- logVerbosity = value;
- return TRUE;
- case XLOG_FILE_VERBOSITY:
- logFileVerbosity = value;
- return TRUE;
- default:
- return FALSE;
- }
-}
-
-/* This function does the actual log message writes. */
-
-void
-LogVWrite(int verb, const char *f, va_list args)
-{
- static char tmpBuffer[1024];
- int len = 0;
-
- /*
- * Since a va_list can only be processed once, write the string to a
- * buffer, and then write the buffer out to the appropriate output
- * stream(s).
- */
- if (verb < 0 || logFileVerbosity >= verb || logVerbosity >= verb) {
- vsnprintf(tmpBuffer, sizeof(tmpBuffer), f, args);
-#ifdef NX_TRANS_EXIT
- /*
- * Beautify the message. Make the
- * first letter uppercase.
- */
-
- *tmpBuffer = toupper(*tmpBuffer);
-
- /*
- * Remove the trailing newline.
- */
-
- if (strlen(tmpBuffer) > 0 &&
- *(tmpBuffer + strlen(tmpBuffer) - 1) == '\n') {
- *(tmpBuffer + strlen(tmpBuffer) - 1) = '\0';
- }
-
- /*
- * Remove the trailing full-stop.
- */
-
- if (strlen(tmpBuffer) > 0 &&
- *(tmpBuffer + strlen(tmpBuffer) - 1) == '.') {
- *(tmpBuffer + strlen(tmpBuffer) - 1) = '\0';
- }
-#endif /* #ifdef NX_TRANS_EXIT */
- len = strlen(tmpBuffer);
- }
- if ((verb < 0 || logVerbosity >= verb) && len > 0)
- fwrite(tmpBuffer, len, 1, stderr);
- if ((verb < 0 || logFileVerbosity >= verb) && len > 0) {
- if (logFile) {
- fwrite(tmpBuffer, len, 1, logFile);
- if (logFlush) {
- fflush(logFile);
-#ifndef WIN32
- if (logSync)
- fsync(fileno(logFile));
-#endif
- }
- } else if (needBuffer) {
- /*
- * Note, this code is used before OsInit() has been called, so
- * xalloc() and friends can't be used.
- */
- if (len > bufferUnused) {
- bufferSize += 1024;
- bufferUnused += 1024;
- if (saveBuffer)
- saveBuffer = realloc(saveBuffer, bufferSize);
- else
- saveBuffer = malloc(bufferSize);
- if (!saveBuffer)
- FatalError("realloc() failed while saving log messages\n");
- }
- bufferUnused -= len;
- memcpy(saveBuffer + bufferPos, tmpBuffer, len);
- bufferPos += len;
- }
- }
-}
-
-void
-LogWrite(int verb, const char *f, ...)
-{
- va_list args;
-
- va_start(args, f);
- LogVWrite(verb, f, args);
- va_end(args);
-}
-
-void
-LogVMessageVerb(MessageType type, int verb, const char *format, va_list args)
-{
- const char *s = X_UNKNOWN_STRING;
- char *tmpBuf = NULL;
-
- /* Ignore verbosity for X_ERROR */
- if (logVerbosity >= verb || logFileVerbosity >= verb || type == X_ERROR) {
- switch (type) {
- case X_PROBED:
- s = X_PROBE_STRING;
- break;
- case X_CONFIG:
- s = X_CONFIG_STRING;
- break;
- case X_DEFAULT:
- s = X_DEFAULT_STRING;
- break;
- case X_CMDLINE:
- s = X_CMDLINE_STRING;
- break;
- case X_NOTICE:
- s = X_NOTICE_STRING;
- break;
- case X_ERROR:
- s = X_ERROR_STRING;
- if (verb > 0)
- verb = 0;
- break;
- case X_WARNING:
- s = X_WARNING_STRING;
- break;
- case X_INFO:
- s = X_INFO_STRING;
- break;
- case X_NOT_IMPLEMENTED:
- s = X_NOT_IMPLEMENTED_STRING;
- break;
- case X_UNKNOWN:
- s = X_UNKNOWN_STRING;
- break;
- case X_NONE:
- s = NULL;
- break;
- }
-
- /*
- * Prefix the format string with the message type. We do it this way
- * so that LogVWrite() is only called once per message.
- */
- if (s) {
- tmpBuf = malloc(strlen(format) + strlen(s) + 1 + 1);
- /* Silently return if malloc fails here. */
- if (!tmpBuf)
- return;
- sprintf(tmpBuf, "%s ", s);
- strcat(tmpBuf, format);
- LogVWrite(verb, tmpBuf, args);
- free(tmpBuf);
- } else
- LogVWrite(verb, format, args);
- }
-}
-
-/* Log message with verbosity level specified. */
-void
-LogMessageVerb(MessageType type, int verb, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, verb, format, ap);
- va_end(ap);
-}
-
-/* Log a message with the standard verbosity level of 1. */
-void
-LogMessage(MessageType type, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, 1, format, ap);
- va_end(ap);
-}
-
-#ifdef __GNUC__
-void AbortServer(void) __attribute__((noreturn));
-#endif
-
-void
-AbortServer(void)
-{
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
- fprintf(stderr, "AbortServer: Going to abort the current server.\n");
-#endif
- OsCleanup(TRUE);
- AbortDDX();
- fflush(stderr);
- if (CoreDump)
- abort();
-#ifdef NX_TRANS_EXIT
-#ifdef NX_TRANS_TEST
- fprintf(stderr, "AbortServer: Going to clean up NX resources and exit.\n");
-#endif
- NXTransExit(1);
-#else /* #ifdef NX_TRANS_EXIT */
- exit (1);
-#endif
-}
-
-#ifndef AUDIT_PREFIX
-#define AUDIT_PREFIX "AUDIT: %s: %ld %s: "
-#endif
-#ifndef AUDIT_TIMEOUT
-#define AUDIT_TIMEOUT ((CARD32)(120 * 1000)) /* 2 mn */
-#endif
-
-static int nrepeat = 0;
-static int oldlen = -1;
-static OsTimerPtr auditTimer = NULL;
-
-void
-FreeAuditTimer(void)
-{
- if (auditTimer != NULL) {
- /* Force output of pending messages */
- TimerForce(auditTimer);
- TimerFree(auditTimer);
- auditTimer = NULL;
- }
-}
-
-static char *
-AuditPrefix(void)
-{
- time_t tm;
- char *autime, *s;
- char *tmpBuf;
- int len;
-
- time(&tm);
- autime = ctime(&tm);
- if ((s = strchr(autime, '\n')))
- *s = '\0';
- if ((s = strrchr(argvGlobal[0], '/')))
- s++;
- else
- s = argvGlobal[0];
- len = strlen(AUDIT_PREFIX) + strlen(autime) + 10 + strlen(s) + 1;
- tmpBuf = malloc(len);
- if (!tmpBuf)
- return NULL;
- snprintf(tmpBuf, len, AUDIT_PREFIX, autime, (unsigned long)getpid(), s);
- return tmpBuf;
-}
-
-void
-AuditF(const char * f, ...)
-{
- va_list args;
-
- va_start(args, f);
-
- VAuditF(f, args);
- va_end(args);
-}
-
-static CARD32
-AuditFlush(OsTimerPtr timer, CARD32 now, pointer arg)
-{
- char *prefix;
-
- if (nrepeat > 0) {
- prefix = AuditPrefix();
- ErrorF("%slast message repeated %d times\n",
- prefix != NULL ? prefix : "", nrepeat);
- nrepeat = 0;
- if (prefix != NULL)
- free(prefix);
- return AUDIT_TIMEOUT;
- } else {
- /* if the timer expires without anything to print, flush the message */
- oldlen = -1;
- return 0;
- }
-}
-
-void
-VAuditF(const char *f, va_list args)
-{
- char *prefix;
- char buf[1024];
- int len;
- static char oldbuf[1024];
-
- prefix = AuditPrefix();
- len = vsnprintf(buf, sizeof(buf), f, args);
-
-#if 1
- /* XXX Compressing duplicated messages is temporarily disabled to
- * work around bugzilla 964:
- * https://freedesktop.org/bugzilla/show_bug.cgi?id=964
- */
- ErrorF("%s%s", prefix != NULL ? prefix : "", buf);
- oldlen = -1;
- nrepeat = 0;
-#else
- if (len == oldlen && strcmp(buf, oldbuf) == 0) {
- /* Message already seen */
- nrepeat++;
- } else {
- /* new message */
- if (auditTimer != NULL)
- TimerForce(auditTimer);
- ErrorF("%s%s", prefix != NULL ? prefix : "", buf);
- strlcpy(oldbuf, buf, sizeof(oldbuf));
- oldlen = len;
- nrepeat = 0;
- auditTimer = TimerSet(auditTimer, 0, AUDIT_TIMEOUT, AuditFlush, NULL);
- }
-#endif
- if (prefix != NULL)
- free(prefix);
-}
-
-void
-FatalError(const char *f, ...)
-{
- va_list args;
- static Bool beenhere = FALSE;
-
-#ifdef NX_TRANS_EXIT
- if (beenhere) {
- fprintf(stderr, "Error: Aborting session with fatal error function reentered.\n");
- }
- else {
- /*
- * Tell to the log function that this
- * is a fatal error.
- */
-
- OsVendorVErrorFFatal = 1;
-
- fprintf(stderr, "Error: Aborting session with '");
-
- va_start(args, f);
- VErrorF(f, args);
- va_end(args);
-
- fprintf(stderr, "'.\n");
- }
-#else /* #ifdef NX_TRANS_EXIT */
- if (beenhere)
- ErrorF("\nFatalError re-entered, aborting\n");
- else
- ErrorF("\nFatal server error:\n");
-
- va_start(args, f);
- VErrorF(f, args);
- va_end(args);
- ErrorF("\n");
-#endif /* #ifdef NX_TRANS_EXIT */
-#ifdef DDXOSFATALERROR
- if (!beenhere)
- OsVendorFatalError();
-#endif
-#ifdef ABORTONFATALERROR
- abort();
-#endif
- if (!beenhere) {
- beenhere = TRUE;
- AbortServer();
- } else
- abort();
- /*NOTREACHED*/
-}
-
-void
-VErrorF(const char *f, va_list args)
-{
-#ifdef DDXOSVERRORF
- if (OsVendorVErrorFProc)
- OsVendorVErrorFProc(f, args);
- else
- LogVWrite(-1, f, args);
-#else
- LogVWrite(-1, f, args);
-#endif
-}
-
-void
-ErrorF(const char * f, ...)
-{
- va_list args;
-
- va_start(args, f);
- VErrorF(f, args);
- va_end(args);
-}
-
-/* A perror() workalike. */
-
-#ifndef NEED_STRERROR
-#ifdef SYSV
-#if !defined(ISC) || defined(ISC202) || defined(ISC22)
-#define NEED_STRERROR
-#endif
-#endif
-#endif
-
-#if defined(NEED_STRERROR) && !defined(strerror)
-extern char *sys_errlist[];
-extern int sys_nerr;
-#define strerror(n) \
- ((n) >= 0 && (n) < sys_nerr) ? sys_errlist[(n)] : "unknown error"
-#endif
-
-void
-Error(char *str)
-{
- char *err = NULL;
- int saveErrno = errno;
-
- if (str) {
- err = malloc(strlen(strerror(saveErrno)) + strlen(str) + 2 + 1);
- if (!err)
- return;
- sprintf(err, "%s: ", str);
- strcat(err, strerror(saveErrno));
- LogWrite(-1, err);
- } else
- LogWrite(-1, strerror(saveErrno));
-}
-
-void
-LogPrintMarkers()
-{
- /* Show what the message marker symbols mean. */
- ErrorF("Markers: ");
- LogMessageVerb(X_PROBED, -1, "probed, ");
- LogMessageVerb(X_CONFIG, -1, "from config file, ");
- LogMessageVerb(X_DEFAULT, -1, "default setting,\n\t");
- LogMessageVerb(X_CMDLINE, -1, "from command line, ");
- LogMessageVerb(X_NOTICE, -1, "notice, ");
- LogMessageVerb(X_INFO, -1, "informational,\n\t");
- LogMessageVerb(X_WARNING, -1, "warning, ");
- LogMessageVerb(X_ERROR, -1, "error, ");
- LogMessageVerb(X_NOT_IMPLEMENTED, -1, "not implemented, ");
- LogMessageVerb(X_UNKNOWN, -1, "unknown.\n");
-}
-
diff --git a/nx-X11/programs/Xserver/os/log.c.X.original b/nx-X11/programs/Xserver/os/log.c.X.original
deleted file mode 100644
index 4bebbe784..000000000
--- a/nx-X11/programs/Xserver/os/log.c.X.original
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
-
-Copyright 1987, 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 by Digital Equipment Corporation, Maynard, Massachusetts,
-Copyright 1994 Quarterdeck Office Systems.
-
- 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 names of Digital and
-Quarterdeck not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-DIGITAL AND QUARTERDECK DISCLAIM 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.
-
-*/
-
-/*
- * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/* $XFree86: xc/programs/Xserver/os/log.c,v 1.6 2003/11/07 13:45:27 tsi Exp $ */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xos.h>
-#include <stdio.h>
-#include <time.h>
-#include <sys/stat.h>
-#include <stdarg.h>
-#include <stdlib.h> /* for malloc() */
-#include <errno.h>
-
-#include "site.h"
-#include "opaque.h"
-
-#ifdef WIN32
-#include <process.h>
-#define getpid(x) _getpid(x)
-#endif
-
-
-#ifdef DDXOSVERRORF
-void (*OsVendorVErrorFProc)(const char *, va_list args) = NULL;
-#endif
-
-static FILE *logFile = NULL;
-static Bool logFlush = FALSE;
-static Bool logSync = FALSE;
-static int logVerbosity = DEFAULT_LOG_VERBOSITY;
-static int logFileVerbosity = DEFAULT_LOG_FILE_VERBOSITY;
-
-/* Buffer to information logged before the log file is opened. */
-static char *saveBuffer = NULL;
-static int bufferSize = 0, bufferUnused = 0, bufferPos = 0;
-static Bool needBuffer = TRUE;
-
-/* Prefix strings for log messages. */
-#ifndef X_UNKNOWN_STRING
-#define X_UNKNOWN_STRING "(\?\?)"
-#endif
-#ifndef X_PROBE_STRING
-#define X_PROBE_STRING "(--)"
-#endif
-#ifndef X_CONFIG_STRING
-#define X_CONFIG_STRING "(**)"
-#endif
-#ifndef X_DEFAULT_STRING
-#define X_DEFAULT_STRING "(==)"
-#endif
-#ifndef X_CMDLINE_STRING
-#define X_CMDLINE_STRING "(++)"
-#endif
-#ifndef X_NOTICE_STRING
-#define X_NOTICE_STRING "(!!)"
-#endif
-#ifndef X_ERROR_STRING
-#define X_ERROR_STRING "(EE)"
-#endif
-#ifndef X_WARNING_STRING
-#define X_WARNING_STRING "(WW)"
-#endif
-#ifndef X_INFO_STRING
-#define X_INFO_STRING "(II)"
-#endif
-#ifndef X_NOT_IMPLEMENTED_STRING
-#define X_NOT_IMPLEMENTED_STRING "(NI)"
-#endif
-
-/*
- * LogInit is called to start logging to a file. It is also called (with
- * NULL arguments) when logging to a file is not wanted. It must always be
- * called, otherwise log messages will continue to accumulate in a buffer.
- *
- * %s, if present in the fname or backup strings, is expanded to the display
- * string.
- */
-
-const char *
-LogInit(const char *fname, const char *backup)
-{
- char *logFileName = NULL;
-
- if (fname && *fname) {
- /* xalloc() can't be used yet. */
- logFileName = malloc(strlen(fname) + strlen(display) + 1);
- if (!logFileName)
- FatalError("Cannot allocate space for the log file name\n");
- sprintf(logFileName, fname, display);
-
- if (backup && *backup) {
- struct stat buf;
-
- if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) {
- char *suffix;
- char *oldLog;
-
- oldLog = malloc(strlen(logFileName) + strlen(backup) +
- strlen(display) + 1);
- suffix = malloc(strlen(backup) + strlen(display) + 1);
- if (!oldLog || !suffix)
- FatalError("Cannot allocate space for the log file name\n");
- sprintf(suffix, backup, display);
- sprintf(oldLog, "%s%s", logFileName, suffix);
- free(suffix);
-#ifdef __UNIXOS2__
- remove(oldLog);
-#endif
- if (rename(logFileName, oldLog) == -1) {
- FatalError("Cannot move old log file (\"%s\" to \"%s\"\n",
- logFileName, oldLog);
- }
- free(oldLog);
- }
- }
- if ((logFile = fopen(logFileName, "w")) == NULL)
- FatalError("Cannot open log file \"%s\"\n", logFileName);
- setvbuf(logFile, NULL, _IONBF, 0);
-
- /* Flush saved log information. */
- if (saveBuffer && bufferSize > 0) {
- fwrite(saveBuffer, bufferPos, 1, logFile);
- fflush(logFile);
-#ifndef WIN32
- fsync(fileno(logFile));
-#endif
- }
- }
-
- /*
- * Unconditionally free the buffer, and flag that the buffer is no longer
- * needed.
- */
- if (saveBuffer && bufferSize > 0) {
- free(saveBuffer); /* Must be free(), not xfree() */
- saveBuffer = NULL;
- bufferSize = 0;
- }
- needBuffer = FALSE;
-
- return logFileName;
-}
-
-void
-LogClose()
-{
- if (logFile) {
- fclose(logFile);
- logFile = NULL;
- }
-}
-
-Bool
-LogSetParameter(LogParameter param, int value)
-{
- switch (param) {
- case XLOG_FLUSH:
- logFlush = value ? TRUE : FALSE;
- return TRUE;
- case XLOG_SYNC:
- logSync = value ? TRUE : FALSE;
- return TRUE;
- case XLOG_VERBOSITY:
- logVerbosity = value;
- return TRUE;
- case XLOG_FILE_VERBOSITY:
- logFileVerbosity = value;
- return TRUE;
- default:
- return FALSE;
- }
-}
-
-/* This function does the actual log message writes. */
-
-void
-LogVWrite(int verb, const char *f, va_list args)
-{
- static char tmpBuffer[1024];
- int len = 0;
-
- /*
- * Since a va_list can only be processed once, write the string to a
- * buffer, and then write the buffer out to the appropriate output
- * stream(s).
- */
- if (verb < 0 || logFileVerbosity >= verb || logVerbosity >= verb) {
- vsnprintf(tmpBuffer, sizeof(tmpBuffer), f, args);
- len = strlen(tmpBuffer);
- }
- if ((verb < 0 || logVerbosity >= verb) && len > 0)
- fwrite(tmpBuffer, len, 1, stderr);
- if ((verb < 0 || logFileVerbosity >= verb) && len > 0) {
- if (logFile) {
- fwrite(tmpBuffer, len, 1, logFile);
- if (logFlush) {
- fflush(logFile);
-#ifndef WIN32
- if (logSync)
- fsync(fileno(logFile));
-#endif
- }
- } else if (needBuffer) {
- /*
- * Note, this code is used before OsInit() has been called, so
- * xalloc() and friends can't be used.
- */
- if (len > bufferUnused) {
- bufferSize += 1024;
- bufferUnused += 1024;
- if (saveBuffer)
- saveBuffer = realloc(saveBuffer, bufferSize);
- else
- saveBuffer = malloc(bufferSize);
- if (!saveBuffer)
- FatalError("realloc() failed while saving log messages\n");
- }
- bufferUnused -= len;
- memcpy(saveBuffer + bufferPos, tmpBuffer, len);
- bufferPos += len;
- }
- }
-}
-
-void
-LogWrite(int verb, const char *f, ...)
-{
- va_list args;
-
- va_start(args, f);
- LogVWrite(verb, f, args);
- va_end(args);
-}
-
-void
-LogVMessageVerb(MessageType type, int verb, const char *format, va_list args)
-{
- const char *s = X_UNKNOWN_STRING;
- char *tmpBuf = NULL;
-
- /* Ignore verbosity for X_ERROR */
- if (logVerbosity >= verb || logFileVerbosity >= verb || type == X_ERROR) {
- switch (type) {
- case X_PROBED:
- s = X_PROBE_STRING;
- break;
- case X_CONFIG:
- s = X_CONFIG_STRING;
- break;
- case X_DEFAULT:
- s = X_DEFAULT_STRING;
- break;
- case X_CMDLINE:
- s = X_CMDLINE_STRING;
- break;
- case X_NOTICE:
- s = X_NOTICE_STRING;
- break;
- case X_ERROR:
- s = X_ERROR_STRING;
- if (verb > 0)
- verb = 0;
- break;
- case X_WARNING:
- s = X_WARNING_STRING;
- break;
- case X_INFO:
- s = X_INFO_STRING;
- break;
- case X_NOT_IMPLEMENTED:
- s = X_NOT_IMPLEMENTED_STRING;
- break;
- case X_UNKNOWN:
- s = X_UNKNOWN_STRING;
- break;
- case X_NONE:
- s = NULL;
- break;
- }
-
- /*
- * Prefix the format string with the message type. We do it this way
- * so that LogVWrite() is only called once per message.
- */
- if (s) {
- tmpBuf = malloc(strlen(format) + strlen(s) + 1 + 1);
- /* Silently return if malloc fails here. */
- if (!tmpBuf)
- return;
- sprintf(tmpBuf, "%s ", s);
- strcat(tmpBuf, format);
- LogVWrite(verb, tmpBuf, args);
- free(tmpBuf);
- } else
- LogVWrite(verb, format, args);
- }
-}
-
-/* Log message with verbosity level specified. */
-void
-LogMessageVerb(MessageType type, int verb, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, verb, format, ap);
- va_end(ap);
-}
-
-/* Log a message with the standard verbosity level of 1. */
-void
-LogMessage(MessageType type, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, 1, format, ap);
- va_end(ap);
-}
-
-#ifdef __GNUC__
-void AbortServer(void) __attribute__((noreturn));
-#endif
-
-void
-AbortServer(void)
-{
- OsCleanup(TRUE);
- AbortDDX();
- fflush(stderr);
- if (CoreDump)
- abort();
- exit (1);
-}
-
-#ifndef AUDIT_PREFIX
-#define AUDIT_PREFIX "AUDIT: %s: %ld %s: "
-#endif
-#ifndef AUDIT_TIMEOUT
-#define AUDIT_TIMEOUT ((CARD32)(120 * 1000)) /* 2 mn */
-#endif
-
-static int nrepeat = 0;
-static int oldlen = -1;
-static OsTimerPtr auditTimer = NULL;
-
-void
-FreeAuditTimer(void)
-{
- if (auditTimer != NULL) {
- /* Force output of pending messages */
- TimerForce(auditTimer);
- TimerFree(auditTimer);
- auditTimer = NULL;
- }
-}
-
-static char *
-AuditPrefix(void)
-{
- time_t tm;
- char *autime, *s;
- char *tmpBuf;
- int len;
-
- time(&tm);
- autime = ctime(&tm);
- if ((s = strchr(autime, '\n')))
- *s = '\0';
- if ((s = strrchr(argvGlobal[0], '/')))
- s++;
- else
- s = argvGlobal[0];
- len = strlen(AUDIT_PREFIX) + strlen(autime) + 10 + strlen(s) + 1;
- tmpBuf = malloc(len);
- if (!tmpBuf)
- return NULL;
- snprintf(tmpBuf, len, AUDIT_PREFIX, autime, (unsigned long)getpid(), s);
- return tmpBuf;
-}
-
-void
-AuditF(const char * f, ...)
-{
- va_list args;
-
- va_start(args, f);
-
- VAuditF(f, args);
- va_end(args);
-}
-
-static CARD32
-AuditFlush(OsTimerPtr timer, CARD32 now, pointer arg)
-{
- char *prefix;
-
- if (nrepeat > 0) {
- prefix = AuditPrefix();
- ErrorF("%slast message repeated %d times\n",
- prefix != NULL ? prefix : "", nrepeat);
- nrepeat = 0;
- if (prefix != NULL)
- free(prefix);
- return AUDIT_TIMEOUT;
- } else {
- /* if the timer expires without anything to print, flush the message */
- oldlen = -1;
- return 0;
- }
-}
-
-void
-VAuditF(const char *f, va_list args)
-{
- char *prefix;
- char buf[1024];
- int len;
- static char oldbuf[1024];
-
- prefix = AuditPrefix();
- len = vsnprintf(buf, sizeof(buf), f, args);
-
-#if 1
- /* XXX Compressing duplicated messages is temporarily disabled to
- * work around bugzilla 964:
- * https://freedesktop.org/bugzilla/show_bug.cgi?id=964
- */
- ErrorF("%s%s", prefix != NULL ? prefix : "", buf);
- oldlen = -1;
- nrepeat = 0;
-#else
- if (len == oldlen && strcmp(buf, oldbuf) == 0) {
- /* Message already seen */
- nrepeat++;
- } else {
- /* new message */
- if (auditTimer != NULL)
- TimerForce(auditTimer);
- ErrorF("%s%s", prefix != NULL ? prefix : "", buf);
- strlcpy(oldbuf, buf, sizeof(oldbuf));
- oldlen = len;
- nrepeat = 0;
- auditTimer = TimerSet(auditTimer, 0, AUDIT_TIMEOUT, AuditFlush, NULL);
- }
-#endif
- if (prefix != NULL)
- free(prefix);
-}
-
-void
-FatalError(const char *f, ...)
-{
- va_list args;
- static Bool beenhere = FALSE;
-
- if (beenhere)
- ErrorF("\nFatalError re-entered, aborting\n");
- else
- ErrorF("\nFatal server error:\n");
-
- va_start(args, f);
- VErrorF(f, args);
- va_end(args);
- ErrorF("\n");
-#ifdef DDXOSFATALERROR
- if (!beenhere)
- OsVendorFatalError();
-#endif
-#ifdef ABORTONFATALERROR
- abort();
-#endif
- if (!beenhere) {
- beenhere = TRUE;
- AbortServer();
- } else
- abort();
- /*NOTREACHED*/
-}
-
-void
-VErrorF(const char *f, va_list args)
-{
-#ifdef DDXOSVERRORF
- if (OsVendorVErrorFProc)
- OsVendorVErrorFProc(f, args);
- else
- LogVWrite(-1, f, args);
-#else
- LogVWrite(-1, f, args);
-#endif
-}
-
-void
-ErrorF(const char * f, ...)
-{
- va_list args;
-
- va_start(args, f);
- VErrorF(f, args);
- va_end(args);
-}
-
-/* A perror() workalike. */
-
-#ifndef NEED_STRERROR
-#ifdef SYSV
-#if !defined(ISC) || defined(ISC202) || defined(ISC22)
-#define NEED_STRERROR
-#endif
-#endif
-#endif
-
-#if defined(NEED_STRERROR) && !defined(strerror)
-extern char *sys_errlist[];
-extern int sys_nerr;
-#define strerror(n) \
- ((n) >= 0 && (n) < sys_nerr) ? sys_errlist[(n)] : "unknown error"
-#endif
-
-void
-Error(char *str)
-{
- char *err = NULL;
- int saveErrno = errno;
-
- if (str) {
- err = malloc(strlen(strerror(saveErrno)) + strlen(str) + 2 + 1);
- if (!err)
- return;
- sprintf(err, "%s: ", str);
- strcat(err, strerror(saveErrno));
- LogWrite(-1, err);
- } else
- LogWrite(-1, strerror(saveErrno));
-}
-
-void
-LogPrintMarkers()
-{
- /* Show what the message marker symbols mean. */
- ErrorF("Markers: ");
- LogMessageVerb(X_PROBED, -1, "probed, ");
- LogMessageVerb(X_CONFIG, -1, "from config file, ");
- LogMessageVerb(X_DEFAULT, -1, "default setting,\n\t");
- LogMessageVerb(X_CMDLINE, -1, "from command line, ");
- LogMessageVerb(X_NOTICE, -1, "notice, ");
- LogMessageVerb(X_INFO, -1, "informational,\n\t");
- LogMessageVerb(X_WARNING, -1, "warning, ");
- LogMessageVerb(X_ERROR, -1, "error, ");
- LogMessageVerb(X_NOT_IMPLEMENTED, -1, "not implemented, ");
- LogMessageVerb(X_UNKNOWN, -1, "unknown.\n");
-}
-
diff --git a/nx-X11/programs/Xserver/os/oscolor.c.NX.original b/nx-X11/programs/Xserver/os/oscolor.c.NX.original
deleted file mode 100644
index cf79857f4..000000000
--- a/nx-X11/programs/Xserver/os/oscolor.c.NX.original
+++ /dev/null
@@ -1,483 +0,0 @@
-/* $XFree86: xc/programs/Xserver/os/oscolor.c,v 3.10 2003/07/16 01:39:03 dawes Exp $ */
-/***********************************************************
-
-Copyright 1987, 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 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.
-
-******************************************************************/
-/* $Xorg: oscolor.c,v 1.4 2001/02/09 02:05:23 xorgcvs Exp $ */
-
-#ifdef NX_TRANS_SOCKET
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-static char* nxAltRgbPaths[] = {"/usr/NX/share/rgb", "/usr/share/X11/rgb", "/etc/X11/rgb"};
-static char _NXRgbPath[1024];
-
-#endif
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef USE_RGB_TXT
-
-#ifdef NDBM
-#include <ndbm.h>
-#else
-#ifdef SVR4
-#include <rpcsvc/dbm.h>
-#else
-#include <dbm.h>
-#endif
-#endif
-#include "rgb.h"
-#include "os.h"
-#include "opaque.h"
-
-/* Note that we are assuming there is only one database for all the screens. */
-
-#ifdef NDBM
-DBM *rgb_dbm = (DBM *)NULL;
-#else
-int rgb_dbm = 0;
-#endif
-
-extern void CopyISOLatin1Lowered(
- unsigned char * /*dest*/,
- unsigned char * /*source*/,
- int /*length*/);
-
-int
-OsInitColors(void)
-{
- if (!rgb_dbm)
- {
-#ifdef NDBM
- rgb_dbm = dbm_open(rgbPath, 0, 0);
-#else
- if (dbminit(rgbPath) == 0)
- rgb_dbm = 1;
-#endif
- if (!rgb_dbm) {
- ErrorF( "Couldn't open RGB_DB '%s'\n", rgbPath );
- return FALSE;
- }
- }
- return TRUE;
-}
-
-/*ARGSUSED*/
-int
-OsLookupColor(int screen, char *name, unsigned int len,
- unsigned short *pred, unsigned short *pgreen, unsigned short *pblue)
-{
- datum dbent;
- RGB rgb;
- char buf[64];
- char *lowername;
-
- if(!rgb_dbm)
- return(0);
-
- /* we use xalloc here so that we can compile with cc without alloca
- * when otherwise using gcc */
- if (len < sizeof(buf))
- lowername = buf;
- else if (!(lowername = (char *)xalloc(len + 1)))
- return(0);
- CopyISOLatin1Lowered ((unsigned char *) lowername, (unsigned char *) name,
- (int)len);
-
- dbent.dptr = lowername;
- dbent.dsize = len;
-#ifdef NDBM
- dbent = dbm_fetch(rgb_dbm, dbent);
-#else
- dbent = fetch (dbent);
-#endif
-
- if (len >= sizeof(buf))
- xfree(lowername);
-
- if(dbent.dptr)
- {
- memmove((char *) &rgb, dbent.dptr, sizeof (RGB));
- *pred = rgb.red;
- *pgreen = rgb.green;
- *pblue = rgb.blue;
- return (1);
- }
- return(0);
-}
-
-#else /* USE_RGB_TXT */
-
-
-/*
- * The dbm routines are a porting hassle. This implementation will do
- * the same thing by reading the rgb.txt file directly, which is much
- * more portable.
- */
-
-#include <stdio.h>
-#include "os.h"
-#include "opaque.h"
-
-#define HASHSIZE 511
-
-typedef struct _dbEntry * dbEntryPtr;
-typedef struct _dbEntry {
- dbEntryPtr link;
- unsigned short red;
- unsigned short green;
- unsigned short blue;
- char name[1]; /* some compilers complain if [0] */
-} dbEntry;
-
-
-extern void CopyISOLatin1Lowered(
- unsigned char * /*dest*/,
- unsigned char * /*source*/,
- int /*length*/);
-
-static dbEntryPtr hashTab[HASHSIZE];
-
-#ifdef NX_TRANS_SOCKET
-
-static int NXVerifyRgbPath(char *path)
-{
- int size;
- char *rgbPath;
- struct stat rgbFileStat;
-
- /*
- * Check if rgb file is present.
- */
-
- size = strlen(path) + strlen(".txt") + 1;
-
- rgbPath = (char *) ALLOCATE_LOCAL(size + 1);
-
- strcpy(rgbPath, path);
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "NXVerifyRgbPath: Looking for [%s] file.\n",
- rgbPath);
- #endif
-
- if (stat(rgbPath, &rgbFileStat) != 0)
- {
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "NXVerifyRgbPath: Can't find the rgb file [%s].\n",
- rgbPath);
- #endif
-
- strcat(rgbPath, ".txt");
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "NXVerifyRgbPath: Looking for [%s] file.\n",
- rgbPath);
- #endif
-
- if (stat(rgbPath, &rgbFileStat) != 0)
- {
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "NXVerifyRgbPath: Can't find the rgb file [%s].\n",
- rgbPath);
- #endif
-
- DEALLOCATE_LOCAL(rgbPath);
-
- return 0;
- }
- }
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "NXVerifyRgbPath: rgb path [%s] is valid.\n",
- path);
- #endif
-
- DEALLOCATE_LOCAL(rgbPath);
-
- return 1;
-}
-
-static const char *_NXGetRgbPath(const char *path)
-{
- const char *systemEnv;
- char rgbPath[1024];
- int numAltRgbPaths;
- int i;
-
- /*
- * Check the environment only once.
- */
-
- if (*_NXRgbPath != '\0')
- {
- return _NXRgbPath;
- }
-
- systemEnv = getenv("NX_SYSTEM");
-
- if (systemEnv != NULL && *systemEnv != '\0')
- {
- if (strlen(systemEnv) + strlen("/share/rgb") + 1 > 1024)
- {
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "_NXGetRgbPath: WARNING! Maximum length of rgb file path exceeded.\n");
- #endif
-
- goto _NXGetRgbPathError;
- }
-
- strcpy(rgbPath, systemEnv);
- strcat(rgbPath, "/share/rgb");
-
- if (NXVerifyRgbPath(rgbPath) == 1)
- {
- strcpy(_NXRgbPath, systemEnv);
- strcat(_NXRgbPath, "/share/rgb");
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "_NXGetRgbPath: Using rgb file path [%s].\n",
- _NXRgbPath);
- #endif
-
- return _NXRgbPath;
- }
- }
-
- numAltRgbPaths = sizeof(nxAltRgbPaths) / sizeof(*nxAltRgbPaths);
-
- for (i = 0; i < numAltRgbPaths; i++)
- {
- if (NXVerifyRgbPath(nxAltRgbPaths[i]) == 1)
- {
- if (strlen(nxAltRgbPaths[i]) + 1 > 1024)
- {
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "_NXGetRgbPath: WARNING! Maximum length of rgb file path exceeded.\n");
- #endif
-
- goto _NXGetRgbPathError;
- }
-
- strcpy(_NXRgbPath, nxAltRgbPaths[i]);
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "_NXGetRgbPath: Using rgb file path [%s].\n",
- _NXRgbPath);
- #endif
-
- return _NXRgbPath;
- }
- }
-
-_NXGetRgbPathError:
-
- strcpy(_NXRgbPath, path);
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "_NXGetRgbPath: Using default rgb file path [%s].\n",
- _NXRgbPath);
- #endif
-
- return _NXRgbPath;
-}
-
-#endif
-
-static dbEntryPtr
-lookup(char *name, int len, Bool create)
-{
- unsigned int h = 0, g;
- dbEntryPtr entry, *prev = NULL;
- char *str = name;
-
- if (!(name = (char*)ALLOCATE_LOCAL(len +1))) return NULL;
- CopyISOLatin1Lowered((unsigned char *)name, (unsigned char *)str, len);
- name[len] = '\0';
-
- for(str = name; *str; str++) {
- h = (h << 4) + *str;
- if ((g = h) & 0xf0000000) h ^= (g >> 24);
- h &= g;
- }
- h %= HASHSIZE;
-
- if ( (entry = hashTab[h]) )
- {
- for( ; entry; prev = (dbEntryPtr*)entry, entry = entry->link )
- if (! strcmp(name, entry->name) ) break;
- }
- else
- prev = &(hashTab[h]);
-
- if (!entry && create && (entry = (dbEntryPtr)xalloc(sizeof(dbEntry) +len)))
- {
- *prev = entry;
- entry->link = NULL;
- strcpy( entry->name, name );
- }
-
- DEALLOCATE_LOCAL(name);
-
- return entry;
-}
-
-
-Bool
-OsInitColors(void)
-{
- FILE *rgb;
- char *path;
- char line[BUFSIZ];
- char name[BUFSIZ];
- int red, green, blue, lineno = 0;
- dbEntryPtr entry;
-
- static Bool was_here = FALSE;
-
- if (!was_here)
- {
-#ifndef __UNIXOS2__
-#ifdef NX_TRANS_SOCKET
- /*
- * Add the trailing '.txt' if a
- * 'rgb' file is not found.
- */
-
- struct stat statbuf;
-
- path = (char*)ALLOCATE_LOCAL(strlen(_NXGetRgbPath(rgbPath)) + 5);
- strcpy(path, _NXGetRgbPath(rgbPath));
-
- if (stat(path, &statbuf) != 0)
- {
- strcat(path, ".txt");
- }
-#else
- path = (char*)ALLOCATE_LOCAL(strlen(rgbPath) +5);
- strcpy(path, rgbPath);
- strcat(path, ".txt");
-#endif
-#else
- char *tmp = (char*)__XOS2RedirRoot(rgbPath);
- path = (char*)ALLOCATE_LOCAL(strlen(tmp) +5);
- strcpy(path, tmp);
- strcat(path, ".txt");
-#endif
- if (!(rgb = fopen(path, "r")))
- {
-#ifdef NX_TRANS_SOCKET
- ErrorF( "Couldn't open RGB_DB '%s'\n", _NXGetRgbPath(rgbPath));
-#else
- ErrorF( "Couldn't open RGB_DB '%s'\n", rgbPath );
-#endif
- DEALLOCATE_LOCAL(path);
- return FALSE;
- }
-
- while(fgets(line, sizeof(line), rgb))
- {
- lineno++;
-#ifndef __UNIXOS2__
- if (sscanf(line,"%d %d %d %[^\n]\n", &red, &green, &blue, name) == 4)
-#else
- if (sscanf(line,"%d %d %d %[^\n\r]\n", &red, &green, &blue, name) == 4)
-#endif
- {
- if (red >= 0 && red <= 0xff &&
- green >= 0 && green <= 0xff &&
- blue >= 0 && blue <= 0xff)
- {
- if ((entry = lookup(name, strlen(name), TRUE)))
- {
- entry->red = (red * 65535) / 255;
- entry->green = (green * 65535) / 255;
- entry->blue = (blue * 65535) / 255;
- }
- }
- else
- ErrorF("Value out of range: %s:%d\n", path, lineno);
- }
- else if (*line && *line != '#' && *line != '!')
- ErrorF("Syntax Error: %s:%d\n", path, lineno);
- }
-
- fclose(rgb);
- DEALLOCATE_LOCAL(path);
-
- was_here = TRUE;
- }
-
- return TRUE;
-}
-
-
-
-Bool
-OsLookupColor(int screen, char *name, unsigned int len,
- unsigned short *pred, unsigned short *pgreen, unsigned short *pblue)
-{
- dbEntryPtr entry;
-
- if ((entry = lookup(name, len, FALSE)))
- {
- *pred = entry->red;
- *pgreen = entry->green;
- *pblue = entry->blue;
- return TRUE;
- }
-
- return FALSE;
-}
-
-#endif /* USE_RGB_TXT */
diff --git a/nx-X11/programs/Xserver/os/oscolor.c.X.original b/nx-X11/programs/Xserver/os/oscolor.c.X.original
deleted file mode 100644
index fdbde7906..000000000
--- a/nx-X11/programs/Xserver/os/oscolor.c.X.original
+++ /dev/null
@@ -1,303 +0,0 @@
-/* $XFree86: xc/programs/Xserver/os/oscolor.c,v 3.10 2003/07/16 01:39:03 dawes Exp $ */
-/***********************************************************
-
-Copyright 1987, 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 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.
-
-******************************************************************/
-/* $Xorg: oscolor.c,v 1.4 2001/02/09 02:05:23 xorgcvs Exp $ */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifndef USE_RGB_TXT
-
-#ifdef NDBM
-#include <ndbm.h>
-#else
-#ifdef SVR4
-#include <rpcsvc/dbm.h>
-#else
-#include <dbm.h>
-#endif
-#endif
-#include "rgb.h"
-#include "os.h"
-#include "opaque.h"
-
-/* Note that we are assuming there is only one database for all the screens. */
-
-#ifdef NDBM
-DBM *rgb_dbm = (DBM *)NULL;
-#else
-int rgb_dbm = 0;
-#endif
-
-extern void CopyISOLatin1Lowered(
- unsigned char * /*dest*/,
- unsigned char * /*source*/,
- int /*length*/);
-
-int
-OsInitColors(void)
-{
- if (!rgb_dbm)
- {
-#ifdef NDBM
- rgb_dbm = dbm_open(rgbPath, 0, 0);
-#else
- if (dbminit(rgbPath) == 0)
- rgb_dbm = 1;
-#endif
- if (!rgb_dbm) {
- ErrorF( "Couldn't open RGB_DB '%s'\n", rgbPath );
- return FALSE;
- }
- }
- return TRUE;
-}
-
-/*ARGSUSED*/
-int
-OsLookupColor(int screen, char *name, unsigned int len,
- unsigned short *pred, unsigned short *pgreen, unsigned short *pblue)
-{
- datum dbent;
- RGB rgb;
- char buf[64];
- char *lowername;
-
- if(!rgb_dbm)
- return(0);
-
- /* we use xalloc here so that we can compile with cc without alloca
- * when otherwise using gcc */
- if (len < sizeof(buf))
- lowername = buf;
- else if (!(lowername = (char *)xalloc(len + 1)))
- return(0);
- CopyISOLatin1Lowered ((unsigned char *) lowername, (unsigned char *) name,
- (int)len);
-
- dbent.dptr = lowername;
- dbent.dsize = len;
-#ifdef NDBM
- dbent = dbm_fetch(rgb_dbm, dbent);
-#else
- dbent = fetch (dbent);
-#endif
-
- if (len >= sizeof(buf))
- xfree(lowername);
-
- if(dbent.dptr)
- {
- memmove((char *) &rgb, dbent.dptr, sizeof (RGB));
- *pred = rgb.red;
- *pgreen = rgb.green;
- *pblue = rgb.blue;
- return (1);
- }
- return(0);
-}
-
-#else /* USE_RGB_TXT */
-
-
-/*
- * The dbm routines are a porting hassle. This implementation will do
- * the same thing by reading the rgb.txt file directly, which is much
- * more portable.
- */
-
-#include <stdio.h>
-#include "os.h"
-#include "opaque.h"
-
-#define HASHSIZE 511
-
-typedef struct _dbEntry * dbEntryPtr;
-typedef struct _dbEntry {
- dbEntryPtr link;
- unsigned short red;
- unsigned short green;
- unsigned short blue;
- char name[1]; /* some compilers complain if [0] */
-} dbEntry;
-
-
-extern void CopyISOLatin1Lowered(
- unsigned char * /*dest*/,
- unsigned char * /*source*/,
- int /*length*/);
-
-static dbEntryPtr hashTab[HASHSIZE];
-
-
-static dbEntryPtr
-lookup(char *name, int len, Bool create)
-{
- unsigned int h = 0, g;
- dbEntryPtr entry, *prev = NULL;
- char *str = name;
-
- if (!(name = (char*)ALLOCATE_LOCAL(len +1))) return NULL;
- CopyISOLatin1Lowered((unsigned char *)name, (unsigned char *)str, len);
- name[len] = '\0';
-
- for(str = name; *str; str++) {
- h = (h << 4) + *str;
- if ((g = h) & 0xf0000000) h ^= (g >> 24);
- h &= g;
- }
- h %= HASHSIZE;
-
- if ( (entry = hashTab[h]) )
- {
- for( ; entry; prev = (dbEntryPtr*)entry, entry = entry->link )
- if (! strcmp(name, entry->name) ) break;
- }
- else
- prev = &(hashTab[h]);
-
- if (!entry && create && (entry = (dbEntryPtr)xalloc(sizeof(dbEntry) +len)))
- {
- *prev = entry;
- entry->link = NULL;
- strcpy( entry->name, name );
- }
-
- DEALLOCATE_LOCAL(name);
-
- return entry;
-}
-
-
-Bool
-OsInitColors(void)
-{
- FILE *rgb;
- char *path;
- char line[BUFSIZ];
- char name[BUFSIZ];
- int red, green, blue, lineno = 0;
- dbEntryPtr entry;
-
- static Bool was_here = FALSE;
-
- if (!was_here)
- {
-#ifndef __UNIXOS2__
- path = (char*)ALLOCATE_LOCAL(strlen(rgbPath) +5);
- strcpy(path, rgbPath);
- strcat(path, ".txt");
-#else
- char *tmp = (char*)__XOS2RedirRoot(rgbPath);
- path = (char*)ALLOCATE_LOCAL(strlen(tmp) +5);
- strcpy(path, tmp);
- strcat(path, ".txt");
-#endif
- if (!(rgb = fopen(path, "r")))
- {
- ErrorF( "Couldn't open RGB_DB '%s'\n", rgbPath );
- DEALLOCATE_LOCAL(path);
- return FALSE;
- }
-
- while(fgets(line, sizeof(line), rgb))
- {
- lineno++;
-#ifndef __UNIXOS2__
- if (sscanf(line,"%d %d %d %[^\n]\n", &red, &green, &blue, name) == 4)
-#else
- if (sscanf(line,"%d %d %d %[^\n\r]\n", &red, &green, &blue, name) == 4)
-#endif
- {
- if (red >= 0 && red <= 0xff &&
- green >= 0 && green <= 0xff &&
- blue >= 0 && blue <= 0xff)
- {
- if ((entry = lookup(name, strlen(name), TRUE)))
- {
- entry->red = (red * 65535) / 255;
- entry->green = (green * 65535) / 255;
- entry->blue = (blue * 65535) / 255;
- }
- }
- else
- ErrorF("Value out of range: %s:%d\n", path, lineno);
- }
- else if (*line && *line != '#' && *line != '!')
- ErrorF("Syntax Error: %s:%d\n", path, lineno);
- }
-
- fclose(rgb);
- DEALLOCATE_LOCAL(path);
-
- was_here = TRUE;
- }
-
- return TRUE;
-}
-
-
-
-Bool
-OsLookupColor(int screen, char *name, unsigned int len,
- unsigned short *pred, unsigned short *pgreen, unsigned short *pblue)
-{
- dbEntryPtr entry;
-
- if ((entry = lookup(name, len, FALSE)))
- {
- *pred = entry->red;
- *pgreen = entry->green;
- *pblue = entry->blue;
- return TRUE;
- }
-
- return FALSE;
-}
-
-#endif /* USE_RGB_TXT */
diff --git a/nx-X11/programs/Xserver/os/utils.c.NX.original b/nx-X11/programs/Xserver/os/utils.c.NX.original
deleted file mode 100644
index 7e626542e..000000000
--- a/nx-X11/programs/Xserver/os/utils.c.NX.original
+++ /dev/null
@@ -1,2440 +0,0 @@
-/* $XdotOrg: xc/programs/Xserver/os/utils.c,v 1.21 2005/11/08 06:33:30 jkj Exp $ */
-/* $Xorg: utils.c,v 1.5 2001/02/09 02:05:24 xorgcvs Exp $ */
-/*
-
-Copyright 1987, 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 by Digital Equipment Corporation, Maynard, Massachusetts,
-Copyright 1994 Quarterdeck Office Systems.
-
- 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 names of Digital and
-Quarterdeck not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-DIGITAL AND QUARTERDECK DISCLAIM 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.
-
-*/
-/* $XFree86: xc/programs/Xserver/os/utils.c,v 3.96 2004/01/07 04:16:37 dawes Exp $ */
-
-/**************************************************************************/
-/* */
-/* Copyright (c) 2001, 2011 NoMachine, http://www.nomachine.com/. */
-/* */
-/* NX-X11, NX protocol compression and NX extensions to this software */
-/* are copyright of NoMachine. Redistribution and use of the present */
-/* software is allowed according to terms specified in the file LICENSE */
-/* which comes in the source distribution. */
-/* */
-/* Check http://www.nomachine.com/licensing.html for applicability. */
-/* */
-/* NX and NoMachine are trademarks of Medialogic S.p.A. */
-/* */
-/* All rights reserved. */
-/* */
-/**************************************************************************/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef __CYGWIN__
-#include <stdlib.h>
-#include <signal.h>
-#endif
-
-#if defined(WIN32) && !defined(__CYGWIN__)
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/Xos.h>
-#include <stdio.h>
-#include "misc.h"
-#include <X11/X.h>
-#include <X11/Xtrans/Xtrans.h>
-#include "input.h"
-#include "dixfont.h"
-#include "osdep.h"
-#ifdef X_POSIX_C_SOURCE
-#define _POSIX_C_SOURCE X_POSIX_C_SOURCE
-#include <signal.h>
-#undef _POSIX_C_SOURCE
-#else
-#if defined(X_NOT_POSIX) || defined(_POSIX_SOURCE)
-#include <signal.h>
-#else
-#define _POSIX_SOURCE
-#include <signal.h>
-#undef _POSIX_SOURCE
-#endif
-#endif
-#ifndef WIN32
-#include <sys/wait.h>
-#endif
-#if !defined(SYSV) && !defined(WIN32) && !defined(Lynx) && !defined(QNX4)
-#include <sys/resource.h>
-#endif
-#include <time.h>
-#include <sys/stat.h>
-#include <ctype.h> /* for isspace */
-#include <stdarg.h>
-
-#if defined(DGUX)
-#include <sys/resource.h>
-#include <netdb.h>
-#endif
-
-#include <stdlib.h> /* for malloc() */
-
-#if defined(TCPCONN) || defined(STREAMSCONN)
-# ifndef WIN32
-# include <netdb.h>
-# endif
-#endif
-
-#include "opaque.h"
-
-#ifdef SMART_SCHEDULE
-#include "dixstruct.h"
-#endif
-
-#ifdef XKB
-#include <X11/extensions/XKBsrv.h>
-#endif
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-#include <X11/extensions/security.h>
-#endif
-
-#ifdef RENDER
-#include "picture.h"
-#endif
-
-#ifdef XPRINT
-#include "DiPrint.h"
-#endif
-
-Bool noTestExtensions;
-#ifdef BIGREQS
-Bool noBigReqExtension = FALSE;
-#endif
-#ifdef COMPOSITE
-/* COMPOSITE is disabled by default for now until the
- * interface is stable */
-Bool noCompositeExtension = TRUE;
-#endif
-#ifdef DAMAGE
-Bool noDamageExtension = FALSE;
-#endif
-#ifdef DBE
-Bool noDbeExtension = FALSE;
-#endif
-#ifdef DPSEXT
-Bool noDPSExtension = FALSE;
-#endif
-#ifdef DPMSExtension
-Bool noDPMSExtension = FALSE;
-#endif
-#ifdef EVI
-Bool noEVIExtension = FALSE;
-#endif
-#ifdef FONTCACHE
-Bool noFontCacheExtension = FALSE;
-#endif
-#ifdef GLXEXT
-Bool noGlxExtension = FALSE;
-#endif
-#ifdef LBX
-Bool noLbxExtension = FALSE;
-#endif
-#ifdef SCREENSAVER
-Bool noScreenSaverExtension = FALSE;
-#endif
-#ifdef MITSHM
-Bool noMITShmExtension = FALSE;
-#endif
-#ifdef MITMISC
-Bool noMITMiscExtension = FALSE;
-#endif
-#ifdef MULTIBUFFER
-Bool noMultibufferExtension = FALSE;
-#endif
-#ifdef RANDR
-Bool noRRExtension = FALSE;
-#endif
-#ifdef RENDER
-Bool noRenderExtension = FALSE;
-#endif
-#ifdef SHAPE
-Bool noShapeExtension = FALSE;
-#endif
-#ifdef XCSECURITY
-Bool noSecurityExtension = FALSE;
-#endif
-#ifdef XSYNC
-Bool noSyncExtension = FALSE;
-#endif
-#ifdef TOGCUP
-Bool noXcupExtension = FALSE;
-#endif
-#ifdef RES
-Bool noResExtension = FALSE;
-#endif
-#ifdef XAPPGROUP
-Bool noXagExtension = FALSE;
-#endif
-#ifdef XCMISC
-Bool noXCMiscExtension = FALSE;
-#endif
-#ifdef XEVIE
-/* Xevie is disabled by default for now until the
- * interface is stable */
-Bool noXevieExtension = TRUE;
-#endif
-#ifdef XF86BIGFONT
-Bool noXFree86BigfontExtension = FALSE;
-#endif
-#ifdef XFreeXDGA
-Bool noXFree86DGAExtension = FALSE;
-#endif
-#ifdef XF86DRI
-Bool noXFree86DRIExtension = FALSE;
-#endif
-#ifdef XF86MISC
-Bool noXFree86MiscExtension = FALSE;
-#endif
-#ifdef XF86VIDMODE
-Bool noXFree86VidModeExtension = FALSE;
-#endif
-#ifdef XFIXES
-Bool noXFixesExtension = FALSE;
-#endif
-/* |noXkbExtension| is defined in xc/programs/Xserver/xkb/xkbInit.c */
-#ifdef PANORAMIX
-/* Xinerama is disabled by default unless enabled via +xinerama */
-Bool noPanoramiXExtension = TRUE;
-#endif
-#ifdef XINPUT
-Bool noXInputExtension = FALSE;
-#endif
-#ifdef XIDLE
-Bool noXIdleExtension = FALSE;
-#endif
-#ifdef XV
-Bool noXvExtension = FALSE;
-#endif
-
-#define X_INCLUDE_NETDB_H
-#include <X11/Xos_r.h>
-
-#include <errno.h>
-
-#ifdef NX_TRANS_SOCKET
-
-#include "NX.h"
-#include "NXvars.h"
-
-#endif
-
-#ifdef NX_TRANS_EXIT
-
-void (*OsVendorStartRedirectErrorFProc)() = NULL;
-void (*OsVendorEndRedirectErrorFProc)() = NULL;
-
-#endif
-
-Bool CoreDump;
-
-#ifdef PANORAMIX
-Bool PanoramiXVisibilityNotifySent = FALSE;
-Bool PanoramiXMapped = FALSE;
-Bool PanoramiXWindowExposureSent = FALSE;
-Bool PanoramiXOneExposeRequest = FALSE;
-Bool PanoramiXExtensionDisabledHack = FALSE;
-#endif
-
-int auditTrailLevel = 1;
-
-Bool Must_have_memory = FALSE;
-
-#ifdef AIXV3
-int SyncOn = 0;
-extern int SelectWaitTime;
-#endif
-
-#ifdef DEBUG
-#ifndef SPECIAL_MALLOC
-#define MEMBUG
-#endif
-#endif
-
-#if defined(SVR4) || defined(__linux__) || defined(CSRG_BASED)
-#define HAS_SAVED_IDS_AND_SETEUID
-#endif
-
-#ifdef MEMBUG
-#define MEM_FAIL_SCALE 100000
-long Memory_fail = 0;
-#include <stdlib.h> /* for random() */
-#endif
-
-#ifdef sgi
-int userdefinedfontpath = 0;
-#endif /* sgi */
-
-char *dev_tty_from_init = NULL; /* since we need to parse it anyway */
-
-extern char dispatchExceptionAtReset;
-
-/* Extension enable/disable in miinitext.c */
-extern Bool EnableDisableExtension(char *name, Bool enable);
-extern void EnableDisableExtensionError(char *name, Bool enable);
-
-OsSigHandlerPtr
-OsSignal(sig, handler)
- int sig;
- OsSigHandlerPtr handler;
-{
-#ifdef X_NOT_POSIX
- return signal(sig, handler);
-#else
- struct sigaction act, oact;
-
- sigemptyset(&act.sa_mask);
- if (handler != SIG_IGN)
- sigaddset(&act.sa_mask, sig);
- act.sa_flags = 0;
- act.sa_handler = handler;
- sigaction(sig, &act, &oact);
- return oact.sa_handler;
-#endif
-}
-
-#ifdef SERVER_LOCK
-/*
- * Explicit support for a server lock file like the ones used for UUCP.
- * For architectures with virtual terminals that can run more than one
- * server at a time. This keeps the servers from stomping on each other
- * if the user forgets to give them different display numbers.
- */
-#ifndef __UNIXOS2__
-#define LOCK_DIR "/tmp"
-#endif
-#define LOCK_TMP_PREFIX "/.tX"
-#define LOCK_PREFIX "/.X"
-#define LOCK_SUFFIX "-lock"
-
-#if defined(DGUX)
-#include <limits.h>
-#include <sys/param.h>
-#endif
-
-#ifdef __UNIXOS2__
-#define link rename
-#endif
-
-#ifndef PATH_MAX
-#ifndef Lynx
-#include <sys/param.h>
-#else
-#include <param.h>
-#endif
-#ifndef PATH_MAX
-#ifdef MAXPATHLEN
-#define PATH_MAX MAXPATHLEN
-#else
-#define PATH_MAX 1024
-#endif
-#endif
-#endif
-
-static Bool StillLocking = FALSE;
-static char LockFile[PATH_MAX];
-static Bool nolock = FALSE;
-
-/*
- * LockServer --
- * Check if the server lock file exists. If so, check if the PID
- * contained inside is valid. If so, then die. Otherwise, create
- * the lock file containing the PID.
- */
-void
-LockServer(void)
-{
- char tmp[PATH_MAX], pid_str[12];
- int lfd, i, haslock, l_pid, t;
- char *tmppath = NULL;
- int len;
- char port[20];
-
- if (nolock) return;
- /*
- * Path names
- */
-#ifndef __UNIXOS2__
- tmppath = LOCK_DIR;
-#else
- /* OS/2 uses TMP directory, must also prepare for 8.3 names */
- tmppath = getenv("TMP");
- if (!tmppath)
- FatalError("No TMP dir found\n");
-#endif
-
- sprintf(port, "%d", atoi(display));
- len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
- strlen(LOCK_TMP_PREFIX);
- len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
- if (len > sizeof(LockFile))
- FatalError("Display name `%s' is too long\n", port);
- (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
- (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
-
- /*
- * Create a temporary file containing our PID. Attempt three times
- * to create the file.
- */
- StillLocking = TRUE;
- i = 0;
- do {
- i++;
- lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
- if (lfd < 0)
- sleep(2);
- else
- break;
- } while (i < 3);
- if (lfd < 0) {
- unlink(tmp);
- i = 0;
- do {
- i++;
- lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
- if (lfd < 0)
- sleep(2);
- else
- break;
- } while (i < 3);
- }
- if (lfd < 0)
- FatalError("Could not create lock file in %s\n", tmp);
- (void) sprintf(pid_str, "%10ld\n", (long)getpid());
- (void) write(lfd, pid_str, 11);
-#ifndef __UNIXOS2__
-#ifndef USE_CHMOD
- (void) fchmod(lfd, 0444);
-#else
- (void) chmod(tmp, 0444);
-#endif
-#endif
- (void) close(lfd);
-
- /*
- * OK. Now the tmp file exists. Try three times to move it in place
- * for the lock.
- */
- i = 0;
- haslock = 0;
- while ((!haslock) && (i++ < 3)) {
- haslock = (link(tmp,LockFile) == 0);
- if (haslock) {
- /*
- * We're done.
- */
- break;
- }
- else {
- /*
- * Read the pid from the existing file
- */
- lfd = open(LockFile, O_RDONLY);
- if (lfd < 0) {
- unlink(tmp);
- FatalError("Can't read lock file %s\n", LockFile);
- }
- pid_str[0] = '\0';
- if (read(lfd, pid_str, 11) != 11) {
- /*
- * Bogus lock file.
- */
- unlink(LockFile);
- close(lfd);
- continue;
- }
- pid_str[11] = '\0';
- sscanf(pid_str, "%d", &l_pid);
- close(lfd);
-
- /*
- * Now try to kill the PID to see if it exists.
- */
- errno = 0;
- t = kill(l_pid, 0);
- if ((t< 0) && (errno == ESRCH)) {
- /*
- * Stale lock file.
- */
- unlink(LockFile);
- continue;
- }
- else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
- /*
- * Process is still active.
- */
- unlink(tmp);
- FatalError("Server is already active for display %s\n%s %s\n%s\n",
- port, "\tIf this server is no longer running, remove",
- LockFile, "\tand start again.");
- }
- }
- }
- unlink(tmp);
- if (!haslock)
- FatalError("Could not create server lock file: %s\n", LockFile);
- StillLocking = FALSE;
-}
-
-/*
- * UnlockServer --
- * Remove the server lock file.
- */
-void
-UnlockServer(void)
-{
- if (nolock) return;
-
- if (!StillLocking){
-
-#ifdef __UNIXOS2__
- (void) chmod(LockFile,S_IREAD|S_IWRITE);
-#endif /* __UNIXOS2__ */
- (void) unlink(LockFile);
- }
-}
-#endif /* SERVER_LOCK */
-
-/* Force connections to close on SIGHUP from init */
-
-/*ARGSUSED*/
-SIGVAL
-AutoResetServer (int sig)
-{
- int olderrno = errno;
-
- dispatchException |= DE_RESET;
- isItTimeToYield = TRUE;
-#ifdef GPROF
- chdir ("/tmp");
- exit (0);
-#endif
-#if defined(SYSV) && defined(X_NOT_POSIX)
- OsSignal (SIGHUP, AutoResetServer);
-#endif
- errno = olderrno;
-}
-
-/* Force connections to close and then exit on SIGTERM, SIGINT */
-
-/*ARGSUSED*/
-SIGVAL
-GiveUp(int sig)
-{
- int olderrno = errno;
-
-#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
- fprintf(stderr, "GiveUp: Called with signal [%d].\n", sig);
-#endif
-
- dispatchException |= DE_TERMINATE;
- isItTimeToYield = TRUE;
-#if defined(SYSV) && defined(X_NOT_POSIX)
- if (sig)
- OsSignal(sig, SIG_IGN);
-#endif
- errno = olderrno;
-}
-
-#ifndef DDXTIME
-CARD32
-GetTimeInMillis(void)
-{
- struct timeval tp;
-
- X_GETTIMEOFDAY(&tp);
- return(tp.tv_sec * 1000) + (tp.tv_usec / 1000);
-}
-#endif
-
-void
-AdjustWaitForDelay (pointer waitTime, unsigned long newdelay)
-{
- static struct timeval delay_val;
- struct timeval **wt = (struct timeval **) waitTime;
- unsigned long olddelay;
-
- if (*wt == NULL)
- {
- delay_val.tv_sec = newdelay / 1000;
- delay_val.tv_usec = 1000 * (newdelay % 1000);
- *wt = &delay_val;
- }
- else
- {
- olddelay = (*wt)->tv_sec * 1000 + (*wt)->tv_usec / 1000;
- if (newdelay < olddelay)
- {
- (*wt)->tv_sec = newdelay / 1000;
- (*wt)->tv_usec = 1000 * (newdelay % 1000);
- }
- }
-}
-
-void UseMsg(void)
-{
-#if !defined(AIXrt) && !defined(AIX386)
- ErrorF("use: X [:<display>] [option]\n");
- ErrorF("-a # mouse acceleration (pixels)\n");
- ErrorF("-ac disable access control restrictions\n");
-#ifdef MEMBUG
- ErrorF("-alloc int chance alloc should fail\n");
-#endif
- ErrorF("-audit int set audit trail level\n");
- ErrorF("-auth file select authorization file\n");
- ErrorF("bc enable bug compatibility\n");
- ErrorF("-br create root window with black background\n");
- ErrorF("+bs enable any backing store support\n");
- ErrorF("-bs disable any backing store support\n");
- ErrorF("-c turns off key-click\n");
- ErrorF("c # key-click volume (0-100)\n");
- ErrorF("-cc int default color visual class\n");
- ErrorF("-co file color database file\n");
-#ifdef COMMANDLINE_CHALLENGED_OPERATING_SYSTEMS
- ErrorF("-config file read options from file\n");
-#endif
- ErrorF("-core generate core dump on fatal error\n");
- ErrorF("-dpi int screen resolution in dots per inch\n");
-#ifdef DPMSExtension
- ErrorF("dpms enables VESA DPMS monitor control\n");
- ErrorF("-dpms disables VESA DPMS monitor control\n");
-#endif
- ErrorF("-deferglyphs [none|all|16] defer loading of [no|all|16-bit] glyphs\n");
- ErrorF("-f # bell base (0-100)\n");
- ErrorF("-fc string cursor font\n");
- ErrorF("-fn string default font name\n");
- ErrorF("-fp string default font path\n");
- ErrorF("-help prints message with these options\n");
- ErrorF("-I ignore all remaining arguments\n");
-#ifdef RLIMIT_DATA
- ErrorF("-ld int limit data space to N Kb\n");
-#endif
-#ifdef RLIMIT_NOFILE
- ErrorF("-lf int limit number of open files to N\n");
-#endif
-#ifdef RLIMIT_STACK
- ErrorF("-ls int limit stack space to N Kb\n");
-#endif
-#ifdef SERVER_LOCK
- ErrorF("-nolock disable the locking mechanism\n");
-#endif
-#ifndef NOLOGOHACK
- ErrorF("-logo enable logo in screen saver\n");
- ErrorF("nologo disable logo in screen saver\n");
-#endif
- ErrorF("-nolisten string don't listen on protocol\n");
- ErrorF("-noreset don't reset after last client exists\n");
- ErrorF("-reset reset after last client exists\n");
- ErrorF("-p # screen-saver pattern duration (minutes)\n");
- ErrorF("-pn accept failure to listen on all ports\n");
- ErrorF("-nopn reject failure to listen on all ports\n");
- ErrorF("-r turns off auto-repeat\n");
- ErrorF("r turns on auto-repeat \n");
-#ifdef RENDER
- ErrorF("-render [default|mono|gray|color] set render color alloc policy\n");
-#endif
- ErrorF("-s # screen-saver timeout (minutes)\n");
-#ifdef XCSECURITY
- ErrorF("-sp file security policy file\n");
-#endif
-#ifdef XPRINT
- PrinterUseMsg();
-#endif
- ErrorF("-su disable any save under support\n");
- ErrorF("-t # mouse threshold (pixels)\n");
- ErrorF("-terminate terminate at server reset\n");
- ErrorF("-to # connection time out\n");
- ErrorF("-tst disable testing extensions\n");
- ErrorF("ttyxx server started from init on /dev/ttyxx\n");
- ErrorF("v video blanking for screen-saver\n");
- ErrorF("-v screen-saver without video blanking\n");
- ErrorF("-wm WhenMapped default backing-store\n");
- ErrorF("-x string loads named extension at init time \n");
- ErrorF("-maxbigreqsize set maximal bigrequest size \n");
-#ifdef PANORAMIX
- ErrorF("+xinerama Enable XINERAMA extension\n");
- ErrorF("-xinerama Disable XINERAMA extension\n");
-#endif
-#ifdef SMART_SCHEDULE
- ErrorF("-dumbSched Disable smart scheduling, enable old behavior\n");
- ErrorF("-schedInterval int Set scheduler interval in msec\n");
-#endif
- ErrorF("+extension name Enable extension\n");
- ErrorF("-extension name Disable extension\n");
-#ifdef XDMCP
- XdmcpUseMsg();
-#endif
-#endif /* !AIXrt && ! AIX386 */
-#ifdef XKB
- XkbUseMsg();
-#endif
- ddxUseMsg();
-}
-
-/* This function performs a rudimentary sanity check
- * on the display name passed in on the command-line,
- * since this string is used to generate filenames.
- * It is especially important that the display name
- * not contain a "/" and not start with a "-".
- * --kvajk
- */
-static int
-VerifyDisplayName(const char *d)
-{
- if ( d == (char *)0 ) return( 0 ); /* null */
- if ( *d == '\0' ) return( 0 ); /* empty */
- if ( *d == '-' ) return( 0 ); /* could be confused for an option */
- if ( *d == '.' ) return( 0 ); /* must not equal "." or ".." */
- if ( strchr(d, '/') != (char *)0 ) return( 0 ); /* very important!!! */
- return( 1 );
-}
-
-/*
- * This function is responsible for doing initalisation of any global
- * variables at an very early point of server startup (even before
- * |ProcessCommandLine()|.
- */
-void InitGlobals(void)
-{
- ddxInitGlobals();
-}
-
-
-/*
- * This function parses the command line. Handles device-independent fields
- * and allows ddx to handle additional fields. It is not allowed to modify
- * argc or any of the strings pointed to by argv.
- */
-void
-ProcessCommandLine(int argc, char *argv[])
-{
- int i, skip;
-
- defaultKeyboardControl.autoRepeat = TRUE;
-
-#ifdef NO_PART_NET
- PartialNetwork = FALSE;
-#else
- PartialNetwork = TRUE;
-#endif
-
- for ( i = 1; i < argc; i++ )
- {
- /* call ddx first, so it can peek/override if it wants */
- if((skip = ddxProcessArgument(argc, argv, i)))
- {
- i += (skip - 1);
- }
- else if(argv[i][0] == ':')
- {
- /* initialize display */
- display = argv[i];
- display++;
- if( ! VerifyDisplayName( display ) ) {
- ErrorF("Bad display name: %s\n", display);
- UseMsg();
- FatalError("Bad display name, exiting: %s\n", display);
- }
- }
- else if ( strcmp( argv[i], "-a") == 0)
- {
- if(++i < argc)
- defaultPointerControl.num = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-ac") == 0)
- {
- defeatAccessControl = TRUE;
- }
-#ifdef MEMBUG
- else if ( strcmp( argv[i], "-alloc") == 0)
- {
- if(++i < argc)
- Memory_fail = atoi(argv[i]);
- else
- UseMsg();
- }
-#endif
- else if ( strcmp( argv[i], "-audit") == 0)
- {
- if(++i < argc)
- auditTrailLevel = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-auth") == 0)
- {
- if(++i < argc)
- InitAuthorization (argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "bc") == 0)
- permitOldBugs = TRUE;
- else if ( strcmp( argv[i], "-br") == 0)
- blackRoot = TRUE;
- else if ( strcmp( argv[i], "+bs") == 0)
- enableBackingStore = TRUE;
- else if ( strcmp( argv[i], "-bs") == 0)
- disableBackingStore = TRUE;
- else if ( strcmp( argv[i], "c") == 0)
- {
- if(++i < argc)
- defaultKeyboardControl.click = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-c") == 0)
- {
- defaultKeyboardControl.click = 0;
- }
- else if ( strcmp( argv[i], "-cc") == 0)
- {
- if(++i < argc)
- defaultColorVisualClass = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-co") == 0)
- {
- if(++i < argc)
- rgbPath = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-core") == 0)
- CoreDump = TRUE;
- else if ( strcmp( argv[i], "-dpi") == 0)
- {
- if(++i < argc)
- monitorResolution = atoi(argv[i]);
- else
- UseMsg();
- }
-#ifdef DPMSExtension
- else if ( strcmp( argv[i], "dpms") == 0)
- DPMSEnabledSwitch = TRUE;
- else if ( strcmp( argv[i], "-dpms") == 0)
- DPMSDisabledSwitch = TRUE;
-#endif
- else if ( strcmp( argv[i], "-deferglyphs") == 0)
- {
- if(++i >= argc || !ParseGlyphCachingMode(argv[i]))
- UseMsg();
- }
- else if ( strcmp( argv[i], "-f") == 0)
- {
- if(++i < argc)
- defaultKeyboardControl.bell = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fc") == 0)
- {
- if(++i < argc)
- defaultCursorFont = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fn") == 0)
- {
- if(++i < argc)
- defaultTextFont = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fp") == 0)
- {
- if(++i < argc)
- {
-#ifdef sgi
- userdefinedfontpath = 1;
-#endif /* sgi */
- defaultFontPath = argv[i];
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-help") == 0)
- {
- UseMsg();
- exit(0);
- }
-#ifdef XKB
- else if ( (skip=XkbProcessArguments(argc,argv,i))!=0 ) {
- if (skip>0)
- i+= skip-1;
- else UseMsg();
- }
-#endif
-#ifdef RLIMIT_DATA
- else if ( strcmp( argv[i], "-ld") == 0)
- {
- if(++i < argc)
- {
- limitDataSpace = atoi(argv[i]);
- if (limitDataSpace > 0)
- limitDataSpace *= 1024;
- }
- else
- UseMsg();
- }
-#endif
-#ifdef RLIMIT_NOFILE
- else if ( strcmp( argv[i], "-lf") == 0)
- {
- if(++i < argc)
- limitNoFile = atoi(argv[i]);
- else
- UseMsg();
- }
-#endif
-#ifdef RLIMIT_STACK
- else if ( strcmp( argv[i], "-ls") == 0)
- {
- if(++i < argc)
- {
- limitStackSpace = atoi(argv[i]);
- if (limitStackSpace > 0)
- limitStackSpace *= 1024;
- }
- else
- UseMsg();
- }
-#endif
-#ifdef SERVER_LOCK
- else if ( strcmp ( argv[i], "-nolock") == 0)
- {
-#if !defined(WIN32) && !defined(__UNIXOS2__) && !defined(__CYGWIN__)
- if (getuid() != 0)
- ErrorF("Warning: the -nolock option can only be used by root\n");
- else
-#endif
- nolock = TRUE;
- }
-#endif
-#ifndef NOLOGOHACK
- else if ( strcmp( argv[i], "-logo") == 0)
- {
- logoScreenSaver = 1;
- }
- else if ( strcmp( argv[i], "nologo") == 0)
- {
- logoScreenSaver = 0;
- }
-#endif
- else if ( strcmp( argv[i], "-nolisten") == 0)
- {
- if(++i < argc) {
- if (_XSERVTransNoListen(argv[i]))
- FatalError ("Failed to disable listen for %s transport",
- argv[i]);
- } else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-noreset") == 0)
- {
- dispatchExceptionAtReset = 0;
- }
- else if ( strcmp( argv[i], "-reset") == 0)
- {
- dispatchExceptionAtReset = DE_RESET;
- }
- else if ( strcmp( argv[i], "-p") == 0)
- {
- if(++i < argc)
- defaultScreenSaverInterval = ((CARD32)atoi(argv[i])) *
- MILLI_PER_MIN;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-pn") == 0)
- PartialNetwork = TRUE;
- else if ( strcmp( argv[i], "-nopn") == 0)
- PartialNetwork = FALSE;
- else if ( strcmp( argv[i], "r") == 0)
- defaultKeyboardControl.autoRepeat = TRUE;
- else if ( strcmp( argv[i], "-r") == 0)
- defaultKeyboardControl.autoRepeat = FALSE;
- else if ( strcmp( argv[i], "-s") == 0)
- {
- if(++i < argc)
- defaultScreenSaverTime = ((CARD32)atoi(argv[i])) *
- MILLI_PER_MIN;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-su") == 0)
- disableSaveUnders = TRUE;
- else if ( strcmp( argv[i], "-t") == 0)
- {
- if(++i < argc)
- defaultPointerControl.threshold = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-terminate") == 0)
- {
- dispatchExceptionAtReset = DE_TERMINATE;
- }
- else if ( strcmp( argv[i], "-to") == 0)
- {
- if(++i < argc)
- TimeOutValue = ((CARD32)atoi(argv[i])) * MILLI_PER_SECOND;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-tst") == 0)
- {
- noTestExtensions = TRUE;
- }
- else if ( strcmp( argv[i], "v") == 0)
- defaultScreenSaverBlanking = PreferBlanking;
- else if ( strcmp( argv[i], "-v") == 0)
- defaultScreenSaverBlanking = DontPreferBlanking;
- else if ( strcmp( argv[i], "-wm") == 0)
- defaultBackingStore = WhenMapped;
- else if ( strcmp( argv[i], "-maxbigreqsize") == 0) {
- if(++i < argc) {
- long reqSizeArg = atol(argv[i]);
-
- /* Request size > 128MB does not make much sense... */
- if( reqSizeArg > 0L && reqSizeArg < 128L ) {
- maxBigRequestSize = (reqSizeArg * 1048576L) - 1L;
- }
- else
- {
- UseMsg();
- }
- }
- else
- {
- UseMsg();
- }
- }
-#ifdef PANORAMIX
- else if ( strcmp( argv[i], "+xinerama") == 0){
- noPanoramiXExtension = FALSE;
- }
- else if ( strcmp( argv[i], "-xinerama") == 0){
- noPanoramiXExtension = TRUE;
- }
- else if ( strcmp( argv[i], "-disablexineramaextension") == 0){
- PanoramiXExtensionDisabledHack = TRUE;
- }
-#endif
- else if ( strcmp( argv[i], "-x") == 0)
- {
- if(++i >= argc)
- UseMsg();
- /* For U**x, which doesn't support dynamic loading, there's nothing
- * to do when we see a -x. Either the extension is linked in or
- * it isn't */
- }
- else if ( strcmp( argv[i], "-I") == 0)
- {
- /* ignore all remaining arguments */
- break;
- }
- else if (strncmp (argv[i], "tty", 3) == 0)
- {
- /* just in case any body is interested */
- dev_tty_from_init = argv[i];
- }
-#ifdef XDMCP
- else if ((skip = XdmcpOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef XPRINT
- else if ((skip = PrinterOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef XCSECURITY
- else if ((skip = XSecurityOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef AIXV3
- else if ( strcmp( argv[i], "-timeout") == 0)
- {
- if(++i < argc)
- SelectWaitTime = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-sync") == 0)
- {
- SyncOn++;
- }
-#endif
-#ifdef SMART_SCHEDULE
- else if ( strcmp( argv[i], "-dumbSched") == 0)
- {
- SmartScheduleDisable = TRUE;
- }
- else if ( strcmp( argv[i], "-schedInterval") == 0)
- {
- if (++i < argc)
- {
- SmartScheduleInterval = atoi(argv[i]);
- SmartScheduleSlice = SmartScheduleInterval;
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-schedMax") == 0)
- {
- if (++i < argc)
- {
- SmartScheduleMaxSlice = atoi(argv[i]);
- }
- else
- UseMsg();
- }
-#endif
-#ifdef RENDER
- else if ( strcmp( argv[i], "-render" ) == 0)
- {
- if (++i < argc)
- {
- int policy = PictureParseCmapPolicy (argv[i]);
-
- if (policy != PictureCmapPolicyInvalid)
- PictureCmapPolicy = policy;
- else
- UseMsg ();
- }
- else
- UseMsg ();
- }
-#endif
- else if ( strcmp( argv[i], "+extension") == 0)
- {
- if (++i < argc)
- {
- if (!EnableDisableExtension(argv[i], TRUE))
- EnableDisableExtensionError(argv[i], TRUE);
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-extension") == 0)
- {
- if (++i < argc)
- {
- if (!EnableDisableExtension(argv[i], FALSE))
- EnableDisableExtensionError(argv[i], FALSE);
- }
- else
- UseMsg();
- }
- else
- {
- ErrorF("Unrecognized option: %s\n", argv[i]);
- UseMsg();
- FatalError("Unrecognized option: %s\n", argv[i]);
- }
- }
-}
-
-#ifdef COMMANDLINE_CHALLENGED_OPERATING_SYSTEMS
-static void
-InsertFileIntoCommandLine(
- int *resargc, char ***resargv,
- int prefix_argc, char **prefix_argv,
- char *filename,
- int suffix_argc, char **suffix_argv)
-{
- struct stat st;
- FILE *f;
- char *p;
- char *q;
- int insert_argc;
- char *buf;
- int len;
- int i;
-
- f = fopen(filename, "r");
- if (!f)
- FatalError("Can't open option file %s\n", filename);
-
- fstat(fileno(f), &st);
-
- buf = (char *) xalloc((unsigned) st.st_size + 1);
- if (!buf)
- FatalError("Out of Memory\n");
-
- len = fread(buf, 1, (unsigned) st.st_size, f);
-
- fclose(f);
-
- if (len < 0)
- FatalError("Error reading option file %s\n", filename);
-
- buf[len] = '\0';
-
- p = buf;
- q = buf;
- insert_argc = 0;
-
- while (*p)
- {
- while (isspace(*p))
- p++;
- if (!*p)
- break;
- if (*p == '#')
- {
- while (*p && *p != '\n')
- p++;
- } else
- {
- while (*p && !isspace(*p))
- *q++ = *p++;
- /* Since p and q might still be pointing at the same place, we */
- /* need to step p over the whitespace now before we add the null. */
- if (*p)
- p++;
- *q++ = '\0';
- insert_argc++;
- }
- }
-
- buf = (char *) xrealloc(buf, q - buf);
- if (!buf)
- FatalError("Out of memory reallocing option buf\n");
-
- *resargc = prefix_argc + insert_argc + suffix_argc;
- *resargv = (char **) xalloc((*resargc + 1) * sizeof(char *));
- if (!*resargv)
- FatalError("Out of Memory\n");
-
- memcpy(*resargv, prefix_argv, prefix_argc * sizeof(char *));
-
- p = buf;
- for (i = 0; i < insert_argc; i++)
- {
- (*resargv)[prefix_argc + i] = p;
- p += strlen(p) + 1;
- }
-
- memcpy(*resargv + prefix_argc + insert_argc,
- suffix_argv, suffix_argc * sizeof(char *));
-
- (*resargv)[*resargc] = NULL;
-} /* end InsertFileIntoCommandLine */
-
-
-void
-ExpandCommandLine(int *pargc, char ***pargv)
-{
- int i;
-
-#if !defined(WIN32) && !defined(__UNIXOS2__) && !defined(__CYGWIN__)
- if (getuid() != geteuid())
- return;
-#endif
-
- for (i = 1; i < *pargc; i++)
- {
- if ( (0 == strcmp((*pargv)[i], "-config")) && (i < (*pargc - 1)) )
- {
- InsertFileIntoCommandLine(pargc, pargv,
- i, *pargv,
- (*pargv)[i+1], /* filename */
- *pargc - i - 2, *pargv + i + 2);
- i--;
- }
- }
-} /* end ExpandCommandLine */
-#endif
-
-/* Implement a simple-minded font authorization scheme. The authorization
- name is "hp-hostname-1", the contents are simply the host name. */
-int
-set_font_authorizations(char **authorizations, int *authlen, pointer client)
-{
-#define AUTHORIZATION_NAME "hp-hostname-1"
-#if defined(TCPCONN) || defined(STREAMSCONN)
- static char *result = NULL;
- static char *p = NULL;
-
- if (p == NULL)
- {
- char hname[1024], *hnameptr;
- unsigned int len;
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo hints, *ai = NULL;
-#else
- struct hostent *host;
-#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
- _Xgethostbynameparams hparams;
-#endif
-#endif
-
- gethostname(hname, 1024);
-#if defined(IPv6) && defined(AF_INET6)
- bzero(&hints, sizeof(hints));
- hints.ai_flags = AI_CANONNAME;
- if (getaddrinfo(hname, NULL, &hints, &ai) == 0) {
- hnameptr = ai->ai_canonname;
- } else {
- hnameptr = hname;
- }
-#else
- host = _XGethostbyname(hname, hparams);
- if (host == NULL)
- hnameptr = hname;
- else
- hnameptr = host->h_name;
-#endif
-
- len = strlen(hnameptr) + 1;
- result = xalloc(len + sizeof(AUTHORIZATION_NAME) + 4);
-
- p = result;
- *p++ = sizeof(AUTHORIZATION_NAME) >> 8;
- *p++ = sizeof(AUTHORIZATION_NAME) & 0xff;
- *p++ = (len) >> 8;
- *p++ = (len & 0xff);
-
- memmove(p, AUTHORIZATION_NAME, sizeof(AUTHORIZATION_NAME));
- p += sizeof(AUTHORIZATION_NAME);
- memmove(p, hnameptr, len);
- p += len;
-#if defined(IPv6) && defined(AF_INET6)
- if (ai) {
- freeaddrinfo(ai);
- }
-#endif
- }
- *authlen = p - result;
- *authorizations = result;
- return 1;
-#else /* TCPCONN */
- return 0;
-#endif /* TCPCONN */
-}
-
-/* XALLOC -- X's internal memory allocator. Why does it return unsigned
- * long * instead of the more common char *? Well, if you read K&R you'll
- * see they say that alloc must return a pointer "suitable for conversion"
- * to whatever type you really want. In a full-blown generic allocator
- * there's no way to solve the alignment problems without potentially
- * wasting lots of space. But we have a more limited problem. We know
- * we're only ever returning pointers to structures which will have to
- * be long word aligned. So we are making a stronger guarantee. It might
- * have made sense to make Xalloc return char * to conform with people's
- * expectations of malloc, but this makes lint happier.
- */
-
-#ifndef INTERNAL_MALLOC
-
-void *
-Xalloc(unsigned long amount)
-{
- register pointer ptr;
-
- if ((long)amount <= 0) {
- return (unsigned long *)NULL;
- }
- /* aligned extra on long word boundary */
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
-#ifdef MEMBUG
- if (!Must_have_memory && Memory_fail &&
- ((random() % MEM_FAIL_SCALE) < Memory_fail))
- return (unsigned long *)NULL;
-#endif
- if ((ptr = (pointer)malloc(amount))) {
- return (unsigned long *)ptr;
- }
- if (Must_have_memory)
- FatalError("Out of memory");
- return (unsigned long *)NULL;
-}
-
-/*****************
- * XNFalloc
- * "no failure" realloc, alternate interface to Xalloc w/o Must_have_memory
- *****************/
-
-void *
-XNFalloc(unsigned long amount)
-{
- register pointer ptr;
-
- if ((long)amount <= 0)
- {
- return (unsigned long *)NULL;
- }
- /* aligned extra on long word boundary */
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
- ptr = (pointer)malloc(amount);
- if (!ptr)
- {
- FatalError("Out of memory");
- }
- return ((unsigned long *)ptr);
-}
-
-/*****************
- * Xcalloc
- *****************/
-
-void *
-Xcalloc(unsigned long amount)
-{
- unsigned long *ret;
-
- ret = Xalloc (amount);
- if (ret)
- bzero ((char *) ret, (int) amount);
- return ret;
-}
-
-/*****************
- * XNFcalloc
- *****************/
-
-void *
-XNFcalloc(unsigned long amount)
-{
- unsigned long *ret;
-
- ret = Xalloc (amount);
- if (ret)
- bzero ((char *) ret, (int) amount);
- else if ((long)amount > 0)
- FatalError("Out of memory");
- return ret;
-}
-
-/*****************
- * Xrealloc
- *****************/
-
-void *
-Xrealloc(pointer ptr, unsigned long amount)
-{
-#ifdef MEMBUG
- if (!Must_have_memory && Memory_fail &&
- ((random() % MEM_FAIL_SCALE) < Memory_fail))
- return (unsigned long *)NULL;
-#endif
- if ((long)amount <= 0)
- {
- if (ptr && !amount)
- free(ptr);
- return (unsigned long *)NULL;
- }
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
- if (ptr)
- ptr = (pointer)realloc((char *)ptr, amount);
- else
- ptr = (pointer)malloc(amount);
- if (ptr)
- return (unsigned long *)ptr;
- if (Must_have_memory)
- FatalError("Out of memory");
- return (unsigned long *)NULL;
-}
-
-/*****************
- * XNFrealloc
- * "no failure" realloc, alternate interface to Xrealloc w/o Must_have_memory
- *****************/
-
-void *
-XNFrealloc(pointer ptr, unsigned long amount)
-{
- if (( ptr = (pointer)Xrealloc( ptr, amount ) ) == NULL)
- {
- if ((long)amount > 0)
- FatalError( "Out of memory" );
- }
- return ((unsigned long *)ptr);
-}
-
-/*****************
- * Xfree
- * calls free
- *****************/
-
-void
-Xfree(pointer ptr)
-{
- if (ptr)
- free((char *)ptr);
-}
-
-void
-OsInitAllocator (void)
-{
-#ifdef MEMBUG
- static int been_here;
-
- /* Check the memory system after each generation */
- if (been_here)
- CheckMemory ();
- else
- been_here = 1;
-#endif
-}
-#endif /* !INTERNAL_MALLOC */
-
-
-char *
-Xstrdup(const char *s)
-{
- char *sd;
-
- if (s == NULL)
- return NULL;
-
- sd = (char *)Xalloc(strlen(s) + 1);
- if (sd != NULL)
- strcpy(sd, s);
- return sd;
-}
-
-
-char *
-XNFstrdup(const char *s)
-{
- char *sd;
-
- if (s == NULL)
- return NULL;
-
- sd = (char *)XNFalloc(strlen(s) + 1);
- strcpy(sd, s);
- return sd;
-}
-
-#ifdef SMART_SCHEDULE
-
-unsigned long SmartScheduleIdleCount;
-Bool SmartScheduleIdle;
-Bool SmartScheduleTimerStopped;
-
-#ifdef SIGVTALRM
-#define SMART_SCHEDULE_POSSIBLE
-#endif
-
-#ifdef SMART_SCHEDULE_POSSIBLE
-#define SMART_SCHEDULE_SIGNAL SIGALRM
-#define SMART_SCHEDULE_TIMER ITIMER_REAL
-#endif
-
-#ifdef NX_TRANS_SOCKET
-void
-SmartScheduleStopTimer (void)
-#else
-static void
-SmartScheduleStopTimer (void)
-#endif
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct itimerval timer;
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "SmartScheduleStopTimer: Stopping timer.\n");
- #endif
-
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 0;
- timer.it_value.tv_sec = 0;
- timer.it_value.tv_usec = 0;
- (void) setitimer (ITIMER_REAL, &timer, 0);
- SmartScheduleTimerStopped = TRUE;
-#endif
-}
-
-Bool
-SmartScheduleStartTimer (void)
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct itimerval timer;
-
- #ifdef NX_TRANS_SOCKET
-
- if (SmartScheduleDisable)
- {
- return FALSE;
- }
-
- #endif
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "SmartScheduleStartTimer: Starting timer with [%ld] ms.\n",
- SmartScheduleInterval);
- #endif
-
- SmartScheduleTimerStopped = FALSE;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = SmartScheduleInterval * 1000;
- timer.it_value.tv_sec = 0;
- timer.it_value.tv_usec = SmartScheduleInterval * 1000;
- return setitimer (ITIMER_REAL, &timer, 0) >= 0;
-#endif
- return FALSE;
-}
-
-#ifdef SMART_SCHEDULE_POSSIBLE
-static void
-SmartScheduleTimer (int sig)
-{
- int olderrno = errno;
-
- SmartScheduleTime += SmartScheduleInterval;
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "SmartScheduleTimer: Got timer with time [%ld] ms.\n",
- SmartScheduleTime);
- #endif
-
- if (SmartScheduleIdle)
- {
- SmartScheduleStopTimer ();
- }
- errno = olderrno;
-}
-#endif
-
-Bool
-SmartScheduleInit (void)
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct sigaction act;
-
- if (SmartScheduleDisable)
- return TRUE;
-
- #ifdef NX_TRANS_TEST
- fprintf(stderr, "SmartScheduleInit: Initializing the smart scheduler.\n");
- #endif
-
- bzero ((char *) &act, sizeof(struct sigaction));
-
- /* Set up the timer signal function */
- act.sa_handler = SmartScheduleTimer;
- sigemptyset (&act.sa_mask);
- sigaddset (&act.sa_mask, SMART_SCHEDULE_SIGNAL);
- if (sigaction (SMART_SCHEDULE_SIGNAL, &act, 0) < 0)
- {
- perror ("sigaction for smart scheduler");
- return FALSE;
- }
- /* Set up the virtual timer */
- if (!SmartScheduleStartTimer ())
- {
- perror ("scheduling timer");
- return FALSE;
- }
- /* stop the timer and wait for WaitForSomething to start it */
- SmartScheduleStopTimer ();
- return TRUE;
-#else
- return FALSE;
-#endif
-}
-#endif
-
-#ifdef SIG_BLOCK
-static sigset_t PreviousSignalMask;
-static int BlockedSignalCount;
-#endif
-
-void
-OsBlockSignals (void)
-{
-#ifdef SIG_BLOCK
- if (BlockedSignalCount++ == 0)
- {
- sigset_t set;
-
- sigemptyset (&set);
-#ifdef SIGALRM
- sigaddset (&set, SIGALRM);
-#endif
-#ifdef SIGVTALRM
- sigaddset (&set, SIGVTALRM);
-#endif
-#ifdef SIGWINCH
- sigaddset (&set, SIGWINCH);
-#endif
-#ifdef SIGIO
- sigaddset (&set, SIGIO);
-#endif
-#ifdef SIGTSTP
- sigaddset (&set, SIGTSTP);
-#endif
-#ifdef SIGTTIN
- sigaddset (&set, SIGTTIN);
-#endif
-#ifdef SIGTTOU
- sigaddset (&set, SIGTTOU);
-#endif
-#ifdef SIGCHLD
- sigaddset (&set, SIGCHLD);
-#endif
- sigprocmask (SIG_BLOCK, &set, &PreviousSignalMask);
- }
-#endif
-}
-
-void
-OsReleaseSignals (void)
-{
-#ifdef SIG_BLOCK
- if (--BlockedSignalCount == 0)
- {
- sigprocmask (SIG_SETMASK, &PreviousSignalMask, 0);
- }
-#endif
-}
-
-#if !defined(WIN32) && !defined(__UNIXOS2__)
-/*
- * "safer" versions of system(3), popen(3) and pclose(3) which give up
- * all privs before running a command.
- *
- * This is based on the code in FreeBSD 2.2 libc.
- *
- * XXX It'd be good to redirect stderr so that it ends up in the log file
- * as well. As it is now, xkbcomp messages don't end up in the log file.
- */
-
-int
-System(char *command)
-{
- int pid, p;
-#ifdef SIGCHLD
- void (*csig)(int);
-#endif
- int status;
-
- if (!command)
- return(1);
-
-#ifdef SIGCHLD
- csig = signal(SIGCHLD, SIG_DFL);
-#endif
-
-#ifdef DEBUG
- ErrorF("System: `%s'\n", command);
-#endif
-
-#ifdef NX_TRANS_EXIT
- if (OsVendorStartRedirectErrorFProc != NULL) {
- OsVendorStartRedirectErrorFProc();
- }
-#endif
- switch (pid = fork()) {
- case -1: /* error */
- p = -1;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- execl("/bin/sh", "sh", "-c", command, (char *)NULL);
- _exit(127);
- default: /* parent */
- do {
- p = waitpid(pid, &status, 0);
- } while (p == -1 && errno == EINTR);
-
- }
-#ifdef NX_TRANS_EXIT
- if (OsVendorEndRedirectErrorFProc != NULL) {
- OsVendorEndRedirectErrorFProc();
- }
-#endif
-
-#ifdef SIGCHLD
- signal(SIGCHLD, csig);
-#endif
-
- return p == -1 ? -1 : status;
-}
-
-static struct pid {
- struct pid *next;
- FILE *fp;
- int pid;
-} *pidlist;
-
-pointer
-Popen(char *command, char *type)
-{
- struct pid *cur;
- FILE *iop;
- int pdes[2], pid;
-
- if (command == NULL || type == NULL)
- return NULL;
-
- if ((*type != 'r' && *type != 'w') || type[1])
- return NULL;
-
- if ((cur = (struct pid *)xalloc(sizeof(struct pid))) == NULL)
- return NULL;
-
- if (pipe(pdes) < 0) {
- xfree(cur);
- return NULL;
- }
-
-#ifdef NX_TRANS_EXIT
- if (OsVendorStartRedirectErrorFProc != NULL) {
- OsVendorStartRedirectErrorFProc();
- }
- OsBlockSignals ();
-#endif
- switch (pid = fork()) {
- case -1: /* error */
- close(pdes[0]);
- close(pdes[1]);
- xfree(cur);
-#ifdef NX_TRANS_EXIT
- if (OsVendorEndRedirectErrorFProc != NULL) {
- OsVendorEndRedirectErrorFProc();
- }
- OsReleaseSignals ();
-#endif
- return NULL;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- if (*type == 'r') {
- if (pdes[1] != 1) {
- /* stdout */
- dup2(pdes[1], 1);
- close(pdes[1]);
- }
- close(pdes[0]);
- } else {
- if (pdes[0] != 0) {
- /* stdin */
- dup2(pdes[0], 0);
- close(pdes[0]);
- }
- close(pdes[1]);
- }
-
- #ifdef NX_TRANS_SOCKET
-
- /*
- * Check if the child process should not
- * use the parent's libraries.
- */
-
- if (_NXUnsetLibraryPath)
- {
- #ifndef __sun
-
- unsetenv ("LD_LIBRARY_PATH");
-
- #else
-
- extern char **environ;
-
- char **ep = environ;
-
- ep = environ;
-
- while (*ep)
- {
- if (!strncmp("LD_LIBRARY_PATH=", *ep, strlen("LD_LIBRARY_PATH=")))
- {
- break;
- }
-
- *ep++;
- }
-
- while (*ep)
- {
- *ep = *(ep + 1);
- ep++;
- }
-
- #endif
- }
-
- #endif
-
- #ifdef NX_TRANS_EXIT
- OsReleaseSignals ();
- #endif
-
- execl("/bin/sh", "sh", "-c", command, (char *)NULL);
- _exit(127);
- }
-
-#ifndef NX_TRANS_EXIT
- /* Avoid EINTR during stdio calls */
- OsBlockSignals ();
-#endif
-
- /* parent */
- if (*type == 'r') {
- iop = fdopen(pdes[0], type);
- close(pdes[1]);
- } else {
- iop = fdopen(pdes[1], type);
- close(pdes[0]);
- }
-
- cur->fp = iop;
- cur->pid = pid;
- cur->next = pidlist;
- pidlist = cur;
-
-#ifdef DEBUG
- ErrorF("Popen: `%s', fp = %p\n", command, iop);
-#endif
-
- return iop;
-}
-
-/* fopen that drops privileges */
-pointer
-Fopen(char *file, char *type)
-{
- FILE *iop;
-#ifndef HAS_SAVED_IDS_AND_SETEUID
- struct pid *cur;
- int pdes[2], pid;
-
- if (file == NULL || type == NULL)
- return NULL;
-
- if ((*type != 'r' && *type != 'w') || type[1])
- return NULL;
-
- if ((cur = (struct pid *)xalloc(sizeof(struct pid))) == NULL)
- return NULL;
-
- if (pipe(pdes) < 0) {
- xfree(cur);
- return NULL;
- }
-
- switch (pid = fork()) {
- case -1: /* error */
- close(pdes[0]);
- close(pdes[1]);
- xfree(cur);
- return NULL;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- if (*type == 'r') {
- if (pdes[1] != 1) {
- /* stdout */
- dup2(pdes[1], 1);
- close(pdes[1]);
- }
- close(pdes[0]);
- } else {
- if (pdes[0] != 0) {
- /* stdin */
- dup2(pdes[0], 0);
- close(pdes[0]);
- }
- close(pdes[1]);
- }
- execl("/bin/cat", "cat", file, (char *)NULL);
- _exit(127);
- }
-
- /* Avoid EINTR during stdio calls */
- OsBlockSignals ();
-
- /* parent */
- if (*type == 'r') {
- iop = fdopen(pdes[0], type);
- close(pdes[1]);
- } else {
- iop = fdopen(pdes[1], type);
- close(pdes[0]);
- }
-
- cur->fp = iop;
- cur->pid = pid;
- cur->next = pidlist;
- pidlist = cur;
-
-#ifdef DEBUG
- ErrorF("Popen: `%s', fp = %p\n", command, iop);
-#endif
-
- return iop;
-#else
- int ruid, euid;
-
- ruid = getuid();
- euid = geteuid();
-
- if (seteuid(ruid) == -1) {
- return NULL;
- }
- iop = fopen(file, type);
-
- if (seteuid(euid) == -1) {
- fclose(iop);
- return NULL;
- }
- return iop;
-#endif /* HAS_SAVED_IDS_AND_SETEUID */
-}
-
-int
-Pclose(pointer iop)
-{
- struct pid *cur, *last;
- int pstat;
- int pid;
-
-#ifdef DEBUG
- ErrorF("Pclose: fp = %p\n", iop);
-#endif
-
- fclose(iop);
-
- for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
- if (cur->fp == iop)
- break;
- if (cur == NULL)
- return -1;
-
- do {
- pid = waitpid(cur->pid, &pstat, 0);
- } while (pid == -1 && errno == EINTR);
-
- if (last == NULL)
- pidlist = cur->next;
- else
- last->next = cur->next;
- xfree(cur);
-
- /* allow EINTR again */
- OsReleaseSignals ();
-
-#ifdef NX_TRANS_EXIT
- if (OsVendorEndRedirectErrorFProc != NULL) {
- OsVendorEndRedirectErrorFProc();
- }
-#endif
- return pid == -1 ? -1 : pstat;
-}
-
-int
-Fclose(pointer iop)
-{
-#ifdef HAS_SAVED_IDS_AND_SETEUID
- return fclose(iop);
-#else
- return Pclose(iop);
-#endif
-}
-
-#endif /* !WIN32 && !__UNIXOS2__ */
-
-
-/*
- * CheckUserParameters: check for long command line arguments and long
- * environment variables. By default, these checks are only done when
- * the server's euid != ruid. In 3.3.x, these checks were done in an
- * external wrapper utility.
- */
-
-/* Consider LD* variables insecure? */
-#ifndef REMOVE_ENV_LD
-#define REMOVE_ENV_LD 1
-#endif
-
-/* Remove long environment variables? */
-#ifndef REMOVE_LONG_ENV
-#define REMOVE_LONG_ENV 1
-#endif
-
-/*
- * Disallow stdout or stderr as pipes? It's possible to block the X server
- * when piping stdout+stderr to a pipe.
- *
- * Don't enable this because it looks like it's going to cause problems.
- */
-#ifndef NO_OUTPUT_PIPES
-#define NO_OUTPUT_PIPES 0
-#endif
-
-
-/* Check args and env only if running setuid (euid == 0 && euid != uid) ? */
-#ifndef CHECK_EUID
-#ifndef WIN32
-#define CHECK_EUID 1
-#else
-#define CHECK_EUID 0
-#endif
-#endif
-
-/*
- * Maybe the locale can be faked to make isprint(3) report that everything
- * is printable? Avoid it by default.
- */
-#ifndef USE_ISPRINT
-#define USE_ISPRINT 0
-#endif
-
-#define MAX_ARG_LENGTH 128
-#define MAX_ENV_LENGTH 256
-#define MAX_ENV_PATH_LENGTH 2048 /* Limit for *PATH and TERMCAP */
-
-#if USE_ISPRINT
-#include <ctype.h>
-#define checkPrintable(c) isprint(c)
-#else
-#define checkPrintable(c) (((c) & 0x7f) >= 0x20 && ((c) & 0x7f) != 0x7f)
-#endif
-
-enum BadCode {
- NotBad = 0,
- UnsafeArg,
- ArgTooLong,
- UnprintableArg,
- EnvTooLong,
- OutputIsPipe,
- InternalError
-};
-
-#if defined(VENDORSUPPORT)
-#define BUGADDRESS VENDORSUPPORT
-#elif defined(BUILDERADDR)
-#define BUGADDRESS BUILDERADDR
-#else
-#define BUGADDRESS "xorg@freedesktop.org"
-#endif
-
-#define ARGMSG \
- "\nIf the arguments used are valid, and have been rejected incorrectly\n" \
- "please send details of the arguments and why they are valid to\n" \
- "%s. In the meantime, you can start the Xserver as\n" \
- "the \"super user\" (root).\n"
-
-#define ENVMSG \
- "\nIf the environment is valid, and have been rejected incorrectly\n" \
- "please send details of the environment and why it is valid to\n" \
- "%s. In the meantime, you can start the Xserver as\n" \
- "the \"super user\" (root).\n"
-
-void
-CheckUserParameters(int argc, char **argv, char **envp)
-{
- enum BadCode bad = NotBad;
- int i = 0, j;
- char *a, *e = NULL;
-#if defined(__QNX__) && !defined(__QNXNTO__)
- char cmd_name[64];
-#endif
-
-#if CHECK_EUID
- if (geteuid() == 0 && getuid() != geteuid())
-#endif
- {
- /* Check each argv[] */
- for (i = 1; i < argc; i++) {
- if (strcmp(argv[i], "-fp") == 0)
- {
- i++; /* continue with next argument. skip the length check */
- if (i >= argc)
- break;
- } else
- {
- if (strlen(argv[i]) > MAX_ARG_LENGTH) {
- bad = ArgTooLong;
- break;
- }
- }
- a = argv[i];
- while (*a) {
- if (checkPrintable(*a) == 0) {
- bad = UnprintableArg;
- break;
- }
- a++;
- }
- if (bad)
- break;
- }
- if (!bad) {
- /* Check each envp[] */
- for (i = 0; envp[i]; i++) {
-
- /* Check for bad environment variables and values */
-#if REMOVE_ENV_LD
- while (envp[i] && (strncmp(envp[i], "LD", 2) == 0)) {
-#ifdef ENVDEBUG
- ErrorF("CheckUserParameters: removing %s from the "
- "environment\n", strtok(envp[i], "="));
-#endif
- for (j = i; envp[j]; j++) {
- envp[j] = envp[j+1];
- }
- }
-#endif
- if (envp[i] && (strlen(envp[i]) > MAX_ENV_LENGTH)) {
-#if REMOVE_LONG_ENV
-#ifdef ENVDEBUG
- ErrorF("CheckUserParameters: removing %s from the "
- "environment\n", strtok(envp[i], "="));
-#endif
- for (j = i; envp[j]; j++) {
- envp[j] = envp[j+1];
- }
- i--;
-#else
- char *eq;
- int len;
-
- eq = strchr(envp[i], '=');
- if (!eq)
- continue;
- len = eq - envp[i];
- e = malloc(len + 1);
- if (!e) {
- bad = InternalError;
- break;
- }
- strncpy(e, envp[i], len);
- e[len] = 0;
- if (len >= 4 &&
- (strcmp(e + len - 4, "PATH") == 0 ||
- strcmp(e, "TERMCAP") == 0)) {
- if (strlen(envp[i]) > MAX_ENV_PATH_LENGTH) {
- bad = EnvTooLong;
- break;
- } else {
- free(e);
- }
- } else {
- bad = EnvTooLong;
- break;
- }
-#endif
- }
- }
- }
-#if NO_OUTPUT_PIPES
- if (!bad) {
- struct stat buf;
-
- if (fstat(fileno(stdout), &buf) == 0 && S_ISFIFO(buf.st_mode))
- bad = OutputIsPipe;
- if (fstat(fileno(stderr), &buf) == 0 && S_ISFIFO(buf.st_mode))
- bad = OutputIsPipe;
- }
-#endif
- }
- switch (bad) {
- case NotBad:
- return;
- case UnsafeArg:
- ErrorF("Command line argument number %d is unsafe\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case ArgTooLong:
- ErrorF("Command line argument number %d is too long\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case UnprintableArg:
- ErrorF("Command line argument number %d contains unprintable"
- " characters\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case EnvTooLong:
- ErrorF("Environment variable `%s' is too long\n", e);
- ErrorF(ENVMSG, BUGADDRESS);
- break;
- case OutputIsPipe:
- ErrorF("Stdout and/or stderr is a pipe\n");
- break;
- case InternalError:
- ErrorF("Internal Error\n");
- break;
- default:
- ErrorF("Unknown error\n");
- ErrorF(ARGMSG, BUGADDRESS);
- ErrorF(ENVMSG, BUGADDRESS);
- break;
- }
- FatalError("X server aborted because of unsafe environment\n");
-}
-
-/*
- * CheckUserAuthorization: check if the user is allowed to start the
- * X server. This usually means some sort of PAM checking, and it is
- * usually only done for setuid servers (uid != euid).
- */
-
-#ifdef USE_PAM
-#include <security/pam_appl.h>
-#include <security/pam_misc.h>
-#include <pwd.h>
-#endif /* USE_PAM */
-
-void
-CheckUserAuthorization(void)
-{
-#ifdef USE_PAM
- static struct pam_conv conv = {
- misc_conv,
- NULL
- };
-
- pam_handle_t *pamh = NULL;
- struct passwd *pw;
- int retval;
-
- if (getuid() != geteuid()) {
- pw = getpwuid(getuid());
- if (pw == NULL)
- FatalError("getpwuid() failed for uid %d\n", getuid());
-
- retval = pam_start("xserver", pw->pw_name, &conv, &pamh);
- if (retval != PAM_SUCCESS)
- FatalError("pam_start() failed.\n"
- "\tMissing or mangled PAM config file or module?\n");
-
- retval = pam_authenticate(pamh, 0);
- if (retval != PAM_SUCCESS) {
- pam_end(pamh, retval);
- FatalError("PAM authentication failed, cannot start X server.\n"
- "\tPerhaps you do not have console ownership?\n");
- }
-
- retval = pam_acct_mgmt(pamh, 0);
- if (retval != PAM_SUCCESS) {
- pam_end(pamh, retval);
- FatalError("PAM authentication failed, cannot start X server.\n"
- "\tPerhaps you do not have console ownership?\n");
- }
-
- /* this is not a session, so do not do session management */
- pam_end(pamh, PAM_SUCCESS);
- }
-#endif
-}
-
-#ifdef __SCO__
-#include <fcntl.h>
-
-static void
-lockit (int fd, short what)
-{
- struct flock lck;
-
- lck.l_whence = 0;
- lck.l_start = 0;
- lck.l_len = 1;
- lck.l_type = what;
-
- (void)fcntl (fd, F_SETLKW, &lck);
-}
-
-/* SCO OpenServer 5 lacks pread/pwrite. Emulate them. */
-ssize_t
-pread (int fd, void *buf, size_t nbytes, off_t offset)
-{
- off_t saved;
- ssize_t ret;
-
- lockit (fd, F_RDLCK);
- saved = lseek (fd, 0, SEEK_CUR);
- lseek (fd, offset, SEEK_SET);
- ret = read (fd, buf, nbytes);
- lseek (fd, saved, SEEK_SET);
- lockit (fd, F_UNLCK);
-
- return ret;
-}
-
-ssize_t
-pwrite (int fd, const void *buf, size_t nbytes, off_t offset)
-{
- off_t saved;
- ssize_t ret;
-
- lockit (fd, F_WRLCK);
- saved = lseek (fd, 0, SEEK_CUR);
- lseek (fd, offset, SEEK_SET);
- ret = write (fd, buf, nbytes);
- lseek (fd, saved, SEEK_SET);
- lockit (fd, F_UNLCK);
-
- return ret;
-}
-#endif /* __SCO__ */
diff --git a/nx-X11/programs/Xserver/os/utils.c.X.original b/nx-X11/programs/Xserver/os/utils.c.X.original
deleted file mode 100644
index b0a806fd7..000000000
--- a/nx-X11/programs/Xserver/os/utils.c.X.original
+++ /dev/null
@@ -1,2296 +0,0 @@
-/* $XdotOrg: xc/programs/Xserver/os/utils.c,v 1.21 2005/11/08 06:33:30 jkj Exp $ */
-/* $Xorg: utils.c,v 1.5 2001/02/09 02:05:24 xorgcvs Exp $ */
-/*
-
-Copyright 1987, 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 by Digital Equipment Corporation, Maynard, Massachusetts,
-Copyright 1994 Quarterdeck Office Systems.
-
- 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 names of Digital and
-Quarterdeck not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-DIGITAL AND QUARTERDECK DISCLAIM 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.
-
-*/
-/* $XFree86: xc/programs/Xserver/os/utils.c,v 3.96 2004/01/07 04:16:37 dawes Exp $ */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef __CYGWIN__
-#include <stdlib.h>
-#include <signal.h>
-#endif
-
-#if defined(WIN32) && !defined(__CYGWIN__)
-#include <X11/Xwinsock.h>
-#endif
-#include <X11/Xos.h>
-#include <stdio.h>
-#include "misc.h"
-#include <X11/X.h>
-#include <X11/Xtrans/Xtrans.h>
-#include "input.h"
-#include "dixfont.h"
-#include "osdep.h"
-#ifdef X_POSIX_C_SOURCE
-#define _POSIX_C_SOURCE X_POSIX_C_SOURCE
-#include <signal.h>
-#undef _POSIX_C_SOURCE
-#else
-#if defined(X_NOT_POSIX) || defined(_POSIX_SOURCE)
-#include <signal.h>
-#else
-#define _POSIX_SOURCE
-#include <signal.h>
-#undef _POSIX_SOURCE
-#endif
-#endif
-#ifndef WIN32
-#include <sys/wait.h>
-#endif
-#if !defined(SYSV) && !defined(WIN32) && !defined(Lynx) && !defined(QNX4)
-#include <sys/resource.h>
-#endif
-#include <time.h>
-#include <sys/stat.h>
-#include <ctype.h> /* for isspace */
-#include <stdarg.h>
-
-#if defined(DGUX)
-#include <sys/resource.h>
-#include <netdb.h>
-#endif
-
-#include <stdlib.h> /* for malloc() */
-
-#if defined(TCPCONN) || defined(STREAMSCONN)
-# ifndef WIN32
-# include <netdb.h>
-# endif
-#endif
-
-#include "opaque.h"
-
-#ifdef SMART_SCHEDULE
-#include "dixstruct.h"
-#endif
-
-#ifdef XKB
-#include <X11/extensions/XKBsrv.h>
-#endif
-#ifdef XCSECURITY
-#define _SECURITY_SERVER
-#include <X11/extensions/security.h>
-#endif
-
-#ifdef RENDER
-#include "picture.h"
-#endif
-
-#ifdef XPRINT
-#include "DiPrint.h"
-#endif
-
-Bool noTestExtensions;
-#ifdef BIGREQS
-Bool noBigReqExtension = FALSE;
-#endif
-#ifdef COMPOSITE
-/* COMPOSITE is disabled by default for now until the
- * interface is stable */
-Bool noCompositeExtension = TRUE;
-#endif
-#ifdef DAMAGE
-Bool noDamageExtension = FALSE;
-#endif
-#ifdef DBE
-Bool noDbeExtension = FALSE;
-#endif
-#ifdef DPSEXT
-Bool noDPSExtension = FALSE;
-#endif
-#ifdef DPMSExtension
-Bool noDPMSExtension = FALSE;
-#endif
-#ifdef EVI
-Bool noEVIExtension = FALSE;
-#endif
-#ifdef FONTCACHE
-Bool noFontCacheExtension = FALSE;
-#endif
-#ifdef GLXEXT
-Bool noGlxExtension = FALSE;
-#endif
-#ifdef LBX
-Bool noLbxExtension = FALSE;
-#endif
-#ifdef SCREENSAVER
-Bool noScreenSaverExtension = FALSE;
-#endif
-#ifdef MITSHM
-Bool noMITShmExtension = FALSE;
-#endif
-#ifdef MITMISC
-Bool noMITMiscExtension = FALSE;
-#endif
-#ifdef MULTIBUFFER
-Bool noMultibufferExtension = FALSE;
-#endif
-#ifdef RANDR
-Bool noRRExtension = FALSE;
-#endif
-#ifdef RENDER
-Bool noRenderExtension = FALSE;
-#endif
-#ifdef SHAPE
-Bool noShapeExtension = FALSE;
-#endif
-#ifdef XCSECURITY
-Bool noSecurityExtension = FALSE;
-#endif
-#ifdef XSYNC
-Bool noSyncExtension = FALSE;
-#endif
-#ifdef TOGCUP
-Bool noXcupExtension = FALSE;
-#endif
-#ifdef RES
-Bool noResExtension = FALSE;
-#endif
-#ifdef XAPPGROUP
-Bool noXagExtension = FALSE;
-#endif
-#ifdef XCMISC
-Bool noXCMiscExtension = FALSE;
-#endif
-#ifdef XEVIE
-/* Xevie is disabled by default for now until the
- * interface is stable */
-Bool noXevieExtension = TRUE;
-#endif
-#ifdef XF86BIGFONT
-Bool noXFree86BigfontExtension = FALSE;
-#endif
-#ifdef XFreeXDGA
-Bool noXFree86DGAExtension = FALSE;
-#endif
-#ifdef XF86DRI
-Bool noXFree86DRIExtension = FALSE;
-#endif
-#ifdef XF86MISC
-Bool noXFree86MiscExtension = FALSE;
-#endif
-#ifdef XF86VIDMODE
-Bool noXFree86VidModeExtension = FALSE;
-#endif
-#ifdef XFIXES
-Bool noXFixesExtension = FALSE;
-#endif
-/* |noXkbExtension| is defined in xc/programs/Xserver/xkb/xkbInit.c */
-#ifdef PANORAMIX
-/* Xinerama is disabled by default unless enabled via +xinerama */
-Bool noPanoramiXExtension = TRUE;
-#endif
-#ifdef XINPUT
-Bool noXInputExtension = FALSE;
-#endif
-#ifdef XIDLE
-Bool noXIdleExtension = FALSE;
-#endif
-#ifdef XV
-Bool noXvExtension = FALSE;
-#endif
-
-#define X_INCLUDE_NETDB_H
-#include <X11/Xos_r.h>
-
-#include <errno.h>
-
-Bool CoreDump;
-
-#ifdef PANORAMIX
-Bool PanoramiXVisibilityNotifySent = FALSE;
-Bool PanoramiXMapped = FALSE;
-Bool PanoramiXWindowExposureSent = FALSE;
-Bool PanoramiXOneExposeRequest = FALSE;
-Bool PanoramiXExtensionDisabledHack = FALSE;
-#endif
-
-int auditTrailLevel = 1;
-
-Bool Must_have_memory = FALSE;
-
-#ifdef AIXV3
-int SyncOn = 0;
-extern int SelectWaitTime;
-#endif
-
-#ifdef DEBUG
-#ifndef SPECIAL_MALLOC
-#define MEMBUG
-#endif
-#endif
-
-#if defined(SVR4) || defined(__linux__) || defined(CSRG_BASED)
-#define HAS_SAVED_IDS_AND_SETEUID
-#endif
-
-#ifdef MEMBUG
-#define MEM_FAIL_SCALE 100000
-long Memory_fail = 0;
-#include <stdlib.h> /* for random() */
-#endif
-
-#ifdef sgi
-int userdefinedfontpath = 0;
-#endif /* sgi */
-
-char *dev_tty_from_init = NULL; /* since we need to parse it anyway */
-
-extern char dispatchExceptionAtReset;
-
-/* Extension enable/disable in miinitext.c */
-extern Bool EnableDisableExtension(char *name, Bool enable);
-extern void EnableDisableExtensionError(char *name, Bool enable);
-
-OsSigHandlerPtr
-OsSignal(sig, handler)
- int sig;
- OsSigHandlerPtr handler;
-{
-#ifdef X_NOT_POSIX
- return signal(sig, handler);
-#else
- struct sigaction act, oact;
-
- sigemptyset(&act.sa_mask);
- if (handler != SIG_IGN)
- sigaddset(&act.sa_mask, sig);
- act.sa_flags = 0;
- act.sa_handler = handler;
- sigaction(sig, &act, &oact);
- return oact.sa_handler;
-#endif
-}
-
-#ifdef SERVER_LOCK
-/*
- * Explicit support for a server lock file like the ones used for UUCP.
- * For architectures with virtual terminals that can run more than one
- * server at a time. This keeps the servers from stomping on each other
- * if the user forgets to give them different display numbers.
- */
-#ifndef __UNIXOS2__
-#define LOCK_DIR "/tmp"
-#endif
-#define LOCK_TMP_PREFIX "/.tX"
-#define LOCK_PREFIX "/.X"
-#define LOCK_SUFFIX "-lock"
-
-#if defined(DGUX)
-#include <limits.h>
-#include <sys/param.h>
-#endif
-
-#ifdef __UNIXOS2__
-#define link rename
-#endif
-
-#ifndef PATH_MAX
-#ifndef Lynx
-#include <sys/param.h>
-#else
-#include <param.h>
-#endif
-#ifndef PATH_MAX
-#ifdef MAXPATHLEN
-#define PATH_MAX MAXPATHLEN
-#else
-#define PATH_MAX 1024
-#endif
-#endif
-#endif
-
-static Bool StillLocking = FALSE;
-static char LockFile[PATH_MAX];
-static Bool nolock = FALSE;
-
-/*
- * LockServer --
- * Check if the server lock file exists. If so, check if the PID
- * contained inside is valid. If so, then die. Otherwise, create
- * the lock file containing the PID.
- */
-void
-LockServer(void)
-{
- char tmp[PATH_MAX], pid_str[12];
- int lfd, i, haslock, l_pid, t;
- char *tmppath = NULL;
- int len;
- char port[20];
-
- if (nolock) return;
- /*
- * Path names
- */
-#ifndef __UNIXOS2__
- tmppath = LOCK_DIR;
-#else
- /* OS/2 uses TMP directory, must also prepare for 8.3 names */
- tmppath = getenv("TMP");
- if (!tmppath)
- FatalError("No TMP dir found\n");
-#endif
-
- sprintf(port, "%d", atoi(display));
- len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
- strlen(LOCK_TMP_PREFIX);
- len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
- if (len > sizeof(LockFile))
- FatalError("Display name `%s' is too long\n", port);
- (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
- (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
-
- /*
- * Create a temporary file containing our PID. Attempt three times
- * to create the file.
- */
- StillLocking = TRUE;
- i = 0;
- do {
- i++;
- lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
- if (lfd < 0)
- sleep(2);
- else
- break;
- } while (i < 3);
- if (lfd < 0) {
- unlink(tmp);
- i = 0;
- do {
- i++;
- lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
- if (lfd < 0)
- sleep(2);
- else
- break;
- } while (i < 3);
- }
- if (lfd < 0)
- FatalError("Could not create lock file in %s\n", tmp);
- (void) sprintf(pid_str, "%10ld\n", (long)getpid());
- (void) write(lfd, pid_str, 11);
-#ifndef __UNIXOS2__
-#ifndef USE_CHMOD
- (void) fchmod(lfd, 0444);
-#else
- (void) chmod(tmp, 0444);
-#endif
-#endif
- (void) close(lfd);
-
- /*
- * OK. Now the tmp file exists. Try three times to move it in place
- * for the lock.
- */
- i = 0;
- haslock = 0;
- while ((!haslock) && (i++ < 3)) {
- haslock = (link(tmp,LockFile) == 0);
- if (haslock) {
- /*
- * We're done.
- */
- break;
- }
- else {
- /*
- * Read the pid from the existing file
- */
- lfd = open(LockFile, O_RDONLY);
- if (lfd < 0) {
- unlink(tmp);
- FatalError("Can't read lock file %s\n", LockFile);
- }
- pid_str[0] = '\0';
- if (read(lfd, pid_str, 11) != 11) {
- /*
- * Bogus lock file.
- */
- unlink(LockFile);
- close(lfd);
- continue;
- }
- pid_str[11] = '\0';
- sscanf(pid_str, "%d", &l_pid);
- close(lfd);
-
- /*
- * Now try to kill the PID to see if it exists.
- */
- errno = 0;
- t = kill(l_pid, 0);
- if ((t< 0) && (errno == ESRCH)) {
- /*
- * Stale lock file.
- */
- unlink(LockFile);
- continue;
- }
- else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
- /*
- * Process is still active.
- */
- unlink(tmp);
- FatalError("Server is already active for display %s\n%s %s\n%s\n",
- port, "\tIf this server is no longer running, remove",
- LockFile, "\tand start again.");
- }
- }
- }
- unlink(tmp);
- if (!haslock)
- FatalError("Could not create server lock file: %s\n", LockFile);
- StillLocking = FALSE;
-}
-
-/*
- * UnlockServer --
- * Remove the server lock file.
- */
-void
-UnlockServer(void)
-{
- if (nolock) return;
-
- if (!StillLocking){
-
-#ifdef __UNIXOS2__
- (void) chmod(LockFile,S_IREAD|S_IWRITE);
-#endif /* __UNIXOS2__ */
- (void) unlink(LockFile);
- }
-}
-#endif /* SERVER_LOCK */
-
-/* Force connections to close on SIGHUP from init */
-
-/*ARGSUSED*/
-SIGVAL
-AutoResetServer (int sig)
-{
- int olderrno = errno;
-
- dispatchException |= DE_RESET;
- isItTimeToYield = TRUE;
-#ifdef GPROF
- chdir ("/tmp");
- exit (0);
-#endif
-#if defined(SYSV) && defined(X_NOT_POSIX)
- OsSignal (SIGHUP, AutoResetServer);
-#endif
- errno = olderrno;
-}
-
-/* Force connections to close and then exit on SIGTERM, SIGINT */
-
-/*ARGSUSED*/
-SIGVAL
-GiveUp(int sig)
-{
- int olderrno = errno;
-
- dispatchException |= DE_TERMINATE;
- isItTimeToYield = TRUE;
-#if defined(SYSV) && defined(X_NOT_POSIX)
- if (sig)
- OsSignal(sig, SIG_IGN);
-#endif
- errno = olderrno;
-}
-
-#ifndef DDXTIME
-CARD32
-GetTimeInMillis(void)
-{
- struct timeval tp;
-
- X_GETTIMEOFDAY(&tp);
- return(tp.tv_sec * 1000) + (tp.tv_usec / 1000);
-}
-#endif
-
-void
-AdjustWaitForDelay (pointer waitTime, unsigned long newdelay)
-{
- static struct timeval delay_val;
- struct timeval **wt = (struct timeval **) waitTime;
- unsigned long olddelay;
-
- if (*wt == NULL)
- {
- delay_val.tv_sec = newdelay / 1000;
- delay_val.tv_usec = 1000 * (newdelay % 1000);
- *wt = &delay_val;
- }
- else
- {
- olddelay = (*wt)->tv_sec * 1000 + (*wt)->tv_usec / 1000;
- if (newdelay < olddelay)
- {
- (*wt)->tv_sec = newdelay / 1000;
- (*wt)->tv_usec = 1000 * (newdelay % 1000);
- }
- }
-}
-
-void UseMsg(void)
-{
-#if !defined(AIXrt) && !defined(AIX386)
- ErrorF("use: X [:<display>] [option]\n");
- ErrorF("-a # mouse acceleration (pixels)\n");
- ErrorF("-ac disable access control restrictions\n");
-#ifdef MEMBUG
- ErrorF("-alloc int chance alloc should fail\n");
-#endif
- ErrorF("-audit int set audit trail level\n");
- ErrorF("-auth file select authorization file\n");
- ErrorF("bc enable bug compatibility\n");
- ErrorF("-br create root window with black background\n");
- ErrorF("+bs enable any backing store support\n");
- ErrorF("-bs disable any backing store support\n");
- ErrorF("-c turns off key-click\n");
- ErrorF("c # key-click volume (0-100)\n");
- ErrorF("-cc int default color visual class\n");
- ErrorF("-co file color database file\n");
-#ifdef COMMANDLINE_CHALLENGED_OPERATING_SYSTEMS
- ErrorF("-config file read options from file\n");
-#endif
- ErrorF("-core generate core dump on fatal error\n");
- ErrorF("-dpi int screen resolution in dots per inch\n");
-#ifdef DPMSExtension
- ErrorF("dpms enables VESA DPMS monitor control\n");
- ErrorF("-dpms disables VESA DPMS monitor control\n");
-#endif
- ErrorF("-deferglyphs [none|all|16] defer loading of [no|all|16-bit] glyphs\n");
- ErrorF("-f # bell base (0-100)\n");
- ErrorF("-fc string cursor font\n");
- ErrorF("-fn string default font name\n");
- ErrorF("-fp string default font path\n");
- ErrorF("-help prints message with these options\n");
- ErrorF("-I ignore all remaining arguments\n");
-#ifdef RLIMIT_DATA
- ErrorF("-ld int limit data space to N Kb\n");
-#endif
-#ifdef RLIMIT_NOFILE
- ErrorF("-lf int limit number of open files to N\n");
-#endif
-#ifdef RLIMIT_STACK
- ErrorF("-ls int limit stack space to N Kb\n");
-#endif
-#ifdef SERVER_LOCK
- ErrorF("-nolock disable the locking mechanism\n");
-#endif
-#ifndef NOLOGOHACK
- ErrorF("-logo enable logo in screen saver\n");
- ErrorF("nologo disable logo in screen saver\n");
-#endif
- ErrorF("-nolisten string don't listen on protocol\n");
- ErrorF("-noreset don't reset after last client exists\n");
- ErrorF("-reset reset after last client exists\n");
- ErrorF("-p # screen-saver pattern duration (minutes)\n");
- ErrorF("-pn accept failure to listen on all ports\n");
- ErrorF("-nopn reject failure to listen on all ports\n");
- ErrorF("-r turns off auto-repeat\n");
- ErrorF("r turns on auto-repeat \n");
-#ifdef RENDER
- ErrorF("-render [default|mono|gray|color] set render color alloc policy\n");
-#endif
- ErrorF("-s # screen-saver timeout (minutes)\n");
-#ifdef XCSECURITY
- ErrorF("-sp file security policy file\n");
-#endif
-#ifdef XPRINT
- PrinterUseMsg();
-#endif
- ErrorF("-su disable any save under support\n");
- ErrorF("-t # mouse threshold (pixels)\n");
- ErrorF("-terminate terminate at server reset\n");
- ErrorF("-to # connection time out\n");
- ErrorF("-tst disable testing extensions\n");
- ErrorF("ttyxx server started from init on /dev/ttyxx\n");
- ErrorF("v video blanking for screen-saver\n");
- ErrorF("-v screen-saver without video blanking\n");
- ErrorF("-wm WhenMapped default backing-store\n");
- ErrorF("-x string loads named extension at init time \n");
- ErrorF("-maxbigreqsize set maximal bigrequest size \n");
-#ifdef PANORAMIX
- ErrorF("+xinerama Enable XINERAMA extension\n");
- ErrorF("-xinerama Disable XINERAMA extension\n");
-#endif
-#ifdef SMART_SCHEDULE
- ErrorF("-dumbSched Disable smart scheduling, enable old behavior\n");
- ErrorF("-schedInterval int Set scheduler interval in msec\n");
-#endif
- ErrorF("+extension name Enable extension\n");
- ErrorF("-extension name Disable extension\n");
-#ifdef XDMCP
- XdmcpUseMsg();
-#endif
-#endif /* !AIXrt && ! AIX386 */
-#ifdef XKB
- XkbUseMsg();
-#endif
- ddxUseMsg();
-}
-
-/* This function performs a rudimentary sanity check
- * on the display name passed in on the command-line,
- * since this string is used to generate filenames.
- * It is especially important that the display name
- * not contain a "/" and not start with a "-".
- * --kvajk
- */
-static int
-VerifyDisplayName(const char *d)
-{
- if ( d == (char *)0 ) return( 0 ); /* null */
- if ( *d == '\0' ) return( 0 ); /* empty */
- if ( *d == '-' ) return( 0 ); /* could be confused for an option */
- if ( *d == '.' ) return( 0 ); /* must not equal "." or ".." */
- if ( strchr(d, '/') != (char *)0 ) return( 0 ); /* very important!!! */
- return( 1 );
-}
-
-/*
- * This function is responsible for doing initalisation of any global
- * variables at an very early point of server startup (even before
- * |ProcessCommandLine()|.
- */
-void InitGlobals(void)
-{
- ddxInitGlobals();
-}
-
-
-/*
- * This function parses the command line. Handles device-independent fields
- * and allows ddx to handle additional fields. It is not allowed to modify
- * argc or any of the strings pointed to by argv.
- */
-void
-ProcessCommandLine(int argc, char *argv[])
-{
- int i, skip;
-
- defaultKeyboardControl.autoRepeat = TRUE;
-
-#ifdef NO_PART_NET
- PartialNetwork = FALSE;
-#else
- PartialNetwork = TRUE;
-#endif
-
- for ( i = 1; i < argc; i++ )
- {
- /* call ddx first, so it can peek/override if it wants */
- if((skip = ddxProcessArgument(argc, argv, i)))
- {
- i += (skip - 1);
- }
- else if(argv[i][0] == ':')
- {
- /* initialize display */
- display = argv[i];
- display++;
- if( ! VerifyDisplayName( display ) ) {
- ErrorF("Bad display name: %s\n", display);
- UseMsg();
- FatalError("Bad display name, exiting: %s\n", display);
- }
- }
- else if ( strcmp( argv[i], "-a") == 0)
- {
- if(++i < argc)
- defaultPointerControl.num = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-ac") == 0)
- {
- defeatAccessControl = TRUE;
- }
-#ifdef MEMBUG
- else if ( strcmp( argv[i], "-alloc") == 0)
- {
- if(++i < argc)
- Memory_fail = atoi(argv[i]);
- else
- UseMsg();
- }
-#endif
- else if ( strcmp( argv[i], "-audit") == 0)
- {
- if(++i < argc)
- auditTrailLevel = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-auth") == 0)
- {
- if(++i < argc)
- InitAuthorization (argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "bc") == 0)
- permitOldBugs = TRUE;
- else if ( strcmp( argv[i], "-br") == 0)
- blackRoot = TRUE;
- else if ( strcmp( argv[i], "+bs") == 0)
- enableBackingStore = TRUE;
- else if ( strcmp( argv[i], "-bs") == 0)
- disableBackingStore = TRUE;
- else if ( strcmp( argv[i], "c") == 0)
- {
- if(++i < argc)
- defaultKeyboardControl.click = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-c") == 0)
- {
- defaultKeyboardControl.click = 0;
- }
- else if ( strcmp( argv[i], "-cc") == 0)
- {
- if(++i < argc)
- defaultColorVisualClass = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-co") == 0)
- {
- if(++i < argc)
- rgbPath = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-core") == 0)
- CoreDump = TRUE;
- else if ( strcmp( argv[i], "-dpi") == 0)
- {
- if(++i < argc)
- monitorResolution = atoi(argv[i]);
- else
- UseMsg();
- }
-#ifdef DPMSExtension
- else if ( strcmp( argv[i], "dpms") == 0)
- DPMSEnabledSwitch = TRUE;
- else if ( strcmp( argv[i], "-dpms") == 0)
- DPMSDisabledSwitch = TRUE;
-#endif
- else if ( strcmp( argv[i], "-deferglyphs") == 0)
- {
- if(++i >= argc || !ParseGlyphCachingMode(argv[i]))
- UseMsg();
- }
- else if ( strcmp( argv[i], "-f") == 0)
- {
- if(++i < argc)
- defaultKeyboardControl.bell = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fc") == 0)
- {
- if(++i < argc)
- defaultCursorFont = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fn") == 0)
- {
- if(++i < argc)
- defaultTextFont = argv[i];
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-fp") == 0)
- {
- if(++i < argc)
- {
-#ifdef sgi
- userdefinedfontpath = 1;
-#endif /* sgi */
- defaultFontPath = argv[i];
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-help") == 0)
- {
- UseMsg();
- exit(0);
- }
-#ifdef XKB
- else if ( (skip=XkbProcessArguments(argc,argv,i))!=0 ) {
- if (skip>0)
- i+= skip-1;
- else UseMsg();
- }
-#endif
-#ifdef RLIMIT_DATA
- else if ( strcmp( argv[i], "-ld") == 0)
- {
- if(++i < argc)
- {
- limitDataSpace = atoi(argv[i]);
- if (limitDataSpace > 0)
- limitDataSpace *= 1024;
- }
- else
- UseMsg();
- }
-#endif
-#ifdef RLIMIT_NOFILE
- else if ( strcmp( argv[i], "-lf") == 0)
- {
- if(++i < argc)
- limitNoFile = atoi(argv[i]);
- else
- UseMsg();
- }
-#endif
-#ifdef RLIMIT_STACK
- else if ( strcmp( argv[i], "-ls") == 0)
- {
- if(++i < argc)
- {
- limitStackSpace = atoi(argv[i]);
- if (limitStackSpace > 0)
- limitStackSpace *= 1024;
- }
- else
- UseMsg();
- }
-#endif
-#ifdef SERVER_LOCK
- else if ( strcmp ( argv[i], "-nolock") == 0)
- {
-#if !defined(WIN32) && !defined(__UNIXOS2__) && !defined(__CYGWIN__)
- if (getuid() != 0)
- ErrorF("Warning: the -nolock option can only be used by root\n");
- else
-#endif
- nolock = TRUE;
- }
-#endif
-#ifndef NOLOGOHACK
- else if ( strcmp( argv[i], "-logo") == 0)
- {
- logoScreenSaver = 1;
- }
- else if ( strcmp( argv[i], "nologo") == 0)
- {
- logoScreenSaver = 0;
- }
-#endif
- else if ( strcmp( argv[i], "-nolisten") == 0)
- {
- if(++i < argc) {
- if (_XSERVTransNoListen(argv[i]))
- FatalError ("Failed to disable listen for %s transport",
- argv[i]);
- } else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-noreset") == 0)
- {
- dispatchExceptionAtReset = 0;
- }
- else if ( strcmp( argv[i], "-reset") == 0)
- {
- dispatchExceptionAtReset = DE_RESET;
- }
- else if ( strcmp( argv[i], "-p") == 0)
- {
- if(++i < argc)
- defaultScreenSaverInterval = ((CARD32)atoi(argv[i])) *
- MILLI_PER_MIN;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-pn") == 0)
- PartialNetwork = TRUE;
- else if ( strcmp( argv[i], "-nopn") == 0)
- PartialNetwork = FALSE;
- else if ( strcmp( argv[i], "r") == 0)
- defaultKeyboardControl.autoRepeat = TRUE;
- else if ( strcmp( argv[i], "-r") == 0)
- defaultKeyboardControl.autoRepeat = FALSE;
- else if ( strcmp( argv[i], "-s") == 0)
- {
- if(++i < argc)
- defaultScreenSaverTime = ((CARD32)atoi(argv[i])) *
- MILLI_PER_MIN;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-su") == 0)
- disableSaveUnders = TRUE;
- else if ( strcmp( argv[i], "-t") == 0)
- {
- if(++i < argc)
- defaultPointerControl.threshold = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-terminate") == 0)
- {
- dispatchExceptionAtReset = DE_TERMINATE;
- }
- else if ( strcmp( argv[i], "-to") == 0)
- {
- if(++i < argc)
- TimeOutValue = ((CARD32)atoi(argv[i])) * MILLI_PER_SECOND;
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-tst") == 0)
- {
- noTestExtensions = TRUE;
- }
- else if ( strcmp( argv[i], "v") == 0)
- defaultScreenSaverBlanking = PreferBlanking;
- else if ( strcmp( argv[i], "-v") == 0)
- defaultScreenSaverBlanking = DontPreferBlanking;
- else if ( strcmp( argv[i], "-wm") == 0)
- defaultBackingStore = WhenMapped;
- else if ( strcmp( argv[i], "-maxbigreqsize") == 0) {
- if(++i < argc) {
- long reqSizeArg = atol(argv[i]);
-
- /* Request size > 128MB does not make much sense... */
- if( reqSizeArg > 0L && reqSizeArg < 128L ) {
- maxBigRequestSize = (reqSizeArg * 1048576L) - 1L;
- }
- else
- {
- UseMsg();
- }
- }
- else
- {
- UseMsg();
- }
- }
-#ifdef PANORAMIX
- else if ( strcmp( argv[i], "+xinerama") == 0){
- noPanoramiXExtension = FALSE;
- }
- else if ( strcmp( argv[i], "-xinerama") == 0){
- noPanoramiXExtension = TRUE;
- }
- else if ( strcmp( argv[i], "-disablexineramaextension") == 0){
- PanoramiXExtensionDisabledHack = TRUE;
- }
-#endif
- else if ( strcmp( argv[i], "-x") == 0)
- {
- if(++i >= argc)
- UseMsg();
- /* For U**x, which doesn't support dynamic loading, there's nothing
- * to do when we see a -x. Either the extension is linked in or
- * it isn't */
- }
- else if ( strcmp( argv[i], "-I") == 0)
- {
- /* ignore all remaining arguments */
- break;
- }
- else if (strncmp (argv[i], "tty", 3) == 0)
- {
- /* just in case any body is interested */
- dev_tty_from_init = argv[i];
- }
-#ifdef XDMCP
- else if ((skip = XdmcpOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef XPRINT
- else if ((skip = PrinterOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef XCSECURITY
- else if ((skip = XSecurityOptions(argc, argv, i)) != i)
- {
- i = skip - 1;
- }
-#endif
-#ifdef AIXV3
- else if ( strcmp( argv[i], "-timeout") == 0)
- {
- if(++i < argc)
- SelectWaitTime = atoi(argv[i]);
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-sync") == 0)
- {
- SyncOn++;
- }
-#endif
-#ifdef SMART_SCHEDULE
- else if ( strcmp( argv[i], "-dumbSched") == 0)
- {
- SmartScheduleDisable = TRUE;
- }
- else if ( strcmp( argv[i], "-schedInterval") == 0)
- {
- if (++i < argc)
- {
- SmartScheduleInterval = atoi(argv[i]);
- SmartScheduleSlice = SmartScheduleInterval;
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-schedMax") == 0)
- {
- if (++i < argc)
- {
- SmartScheduleMaxSlice = atoi(argv[i]);
- }
- else
- UseMsg();
- }
-#endif
-#ifdef RENDER
- else if ( strcmp( argv[i], "-render" ) == 0)
- {
- if (++i < argc)
- {
- int policy = PictureParseCmapPolicy (argv[i]);
-
- if (policy != PictureCmapPolicyInvalid)
- PictureCmapPolicy = policy;
- else
- UseMsg ();
- }
- else
- UseMsg ();
- }
-#endif
- else if ( strcmp( argv[i], "+extension") == 0)
- {
- if (++i < argc)
- {
- if (!EnableDisableExtension(argv[i], TRUE))
- EnableDisableExtensionError(argv[i], TRUE);
- }
- else
- UseMsg();
- }
- else if ( strcmp( argv[i], "-extension") == 0)
- {
- if (++i < argc)
- {
- if (!EnableDisableExtension(argv[i], FALSE))
- EnableDisableExtensionError(argv[i], FALSE);
- }
- else
- UseMsg();
- }
- else
- {
- ErrorF("Unrecognized option: %s\n", argv[i]);
- UseMsg();
- FatalError("Unrecognized option: %s\n", argv[i]);
- }
- }
-}
-
-#ifdef COMMANDLINE_CHALLENGED_OPERATING_SYSTEMS
-static void
-InsertFileIntoCommandLine(
- int *resargc, char ***resargv,
- int prefix_argc, char **prefix_argv,
- char *filename,
- int suffix_argc, char **suffix_argv)
-{
- struct stat st;
- FILE *f;
- char *p;
- char *q;
- int insert_argc;
- char *buf;
- int len;
- int i;
-
- f = fopen(filename, "r");
- if (!f)
- FatalError("Can't open option file %s\n", filename);
-
- fstat(fileno(f), &st);
-
- buf = (char *) xalloc((unsigned) st.st_size + 1);
- if (!buf)
- FatalError("Out of Memory\n");
-
- len = fread(buf, 1, (unsigned) st.st_size, f);
-
- fclose(f);
-
- if (len < 0)
- FatalError("Error reading option file %s\n", filename);
-
- buf[len] = '\0';
-
- p = buf;
- q = buf;
- insert_argc = 0;
-
- while (*p)
- {
- while (isspace(*p))
- p++;
- if (!*p)
- break;
- if (*p == '#')
- {
- while (*p && *p != '\n')
- p++;
- } else
- {
- while (*p && !isspace(*p))
- *q++ = *p++;
- /* Since p and q might still be pointing at the same place, we */
- /* need to step p over the whitespace now before we add the null. */
- if (*p)
- p++;
- *q++ = '\0';
- insert_argc++;
- }
- }
-
- buf = (char *) xrealloc(buf, q - buf);
- if (!buf)
- FatalError("Out of memory reallocing option buf\n");
-
- *resargc = prefix_argc + insert_argc + suffix_argc;
- *resargv = (char **) xalloc((*resargc + 1) * sizeof(char *));
- if (!*resargv)
- FatalError("Out of Memory\n");
-
- memcpy(*resargv, prefix_argv, prefix_argc * sizeof(char *));
-
- p = buf;
- for (i = 0; i < insert_argc; i++)
- {
- (*resargv)[prefix_argc + i] = p;
- p += strlen(p) + 1;
- }
-
- memcpy(*resargv + prefix_argc + insert_argc,
- suffix_argv, suffix_argc * sizeof(char *));
-
- (*resargv)[*resargc] = NULL;
-} /* end InsertFileIntoCommandLine */
-
-
-void
-ExpandCommandLine(int *pargc, char ***pargv)
-{
- int i;
-
-#if !defined(WIN32) && !defined(__UNIXOS2__) && !defined(__CYGWIN__)
- if (getuid() != geteuid())
- return;
-#endif
-
- for (i = 1; i < *pargc; i++)
- {
- if ( (0 == strcmp((*pargv)[i], "-config")) && (i < (*pargc - 1)) )
- {
- InsertFileIntoCommandLine(pargc, pargv,
- i, *pargv,
- (*pargv)[i+1], /* filename */
- *pargc - i - 2, *pargv + i + 2);
- i--;
- }
- }
-} /* end ExpandCommandLine */
-#endif
-
-/* Implement a simple-minded font authorization scheme. The authorization
- name is "hp-hostname-1", the contents are simply the host name. */
-int
-set_font_authorizations(char **authorizations, int *authlen, pointer client)
-{
-#define AUTHORIZATION_NAME "hp-hostname-1"
-#if defined(TCPCONN) || defined(STREAMSCONN)
- static char *result = NULL;
- static char *p = NULL;
-
- if (p == NULL)
- {
- char hname[1024], *hnameptr;
- unsigned int len;
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo hints, *ai = NULL;
-#else
- struct hostent *host;
-#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
- _Xgethostbynameparams hparams;
-#endif
-#endif
-
- gethostname(hname, 1024);
-#if defined(IPv6) && defined(AF_INET6)
- bzero(&hints, sizeof(hints));
- hints.ai_flags = AI_CANONNAME;
- if (getaddrinfo(hname, NULL, &hints, &ai) == 0) {
- hnameptr = ai->ai_canonname;
- } else {
- hnameptr = hname;
- }
-#else
- host = _XGethostbyname(hname, hparams);
- if (host == NULL)
- hnameptr = hname;
- else
- hnameptr = host->h_name;
-#endif
-
- len = strlen(hnameptr) + 1;
- result = xalloc(len + sizeof(AUTHORIZATION_NAME) + 4);
-
- p = result;
- *p++ = sizeof(AUTHORIZATION_NAME) >> 8;
- *p++ = sizeof(AUTHORIZATION_NAME) & 0xff;
- *p++ = (len) >> 8;
- *p++ = (len & 0xff);
-
- memmove(p, AUTHORIZATION_NAME, sizeof(AUTHORIZATION_NAME));
- p += sizeof(AUTHORIZATION_NAME);
- memmove(p, hnameptr, len);
- p += len;
-#if defined(IPv6) && defined(AF_INET6)
- if (ai) {
- freeaddrinfo(ai);
- }
-#endif
- }
- *authlen = p - result;
- *authorizations = result;
- return 1;
-#else /* TCPCONN */
- return 0;
-#endif /* TCPCONN */
-}
-
-/* XALLOC -- X's internal memory allocator. Why does it return unsigned
- * long * instead of the more common char *? Well, if you read K&R you'll
- * see they say that alloc must return a pointer "suitable for conversion"
- * to whatever type you really want. In a full-blown generic allocator
- * there's no way to solve the alignment problems without potentially
- * wasting lots of space. But we have a more limited problem. We know
- * we're only ever returning pointers to structures which will have to
- * be long word aligned. So we are making a stronger guarantee. It might
- * have made sense to make Xalloc return char * to conform with people's
- * expectations of malloc, but this makes lint happier.
- */
-
-#ifndef INTERNAL_MALLOC
-
-void *
-Xalloc(unsigned long amount)
-{
- register pointer ptr;
-
- if ((long)amount <= 0) {
- return (unsigned long *)NULL;
- }
- /* aligned extra on long word boundary */
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
-#ifdef MEMBUG
- if (!Must_have_memory && Memory_fail &&
- ((random() % MEM_FAIL_SCALE) < Memory_fail))
- return (unsigned long *)NULL;
-#endif
- if ((ptr = (pointer)malloc(amount))) {
- return (unsigned long *)ptr;
- }
- if (Must_have_memory)
- FatalError("Out of memory");
- return (unsigned long *)NULL;
-}
-
-/*****************
- * XNFalloc
- * "no failure" realloc, alternate interface to Xalloc w/o Must_have_memory
- *****************/
-
-void *
-XNFalloc(unsigned long amount)
-{
- register pointer ptr;
-
- if ((long)amount <= 0)
- {
- return (unsigned long *)NULL;
- }
- /* aligned extra on long word boundary */
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
- ptr = (pointer)malloc(amount);
- if (!ptr)
- {
- FatalError("Out of memory");
- }
- return ((unsigned long *)ptr);
-}
-
-/*****************
- * Xcalloc
- *****************/
-
-void *
-Xcalloc(unsigned long amount)
-{
- unsigned long *ret;
-
- ret = Xalloc (amount);
- if (ret)
- bzero ((char *) ret, (int) amount);
- return ret;
-}
-
-/*****************
- * XNFcalloc
- *****************/
-
-void *
-XNFcalloc(unsigned long amount)
-{
- unsigned long *ret;
-
- ret = Xalloc (amount);
- if (ret)
- bzero ((char *) ret, (int) amount);
- else if ((long)amount > 0)
- FatalError("Out of memory");
- return ret;
-}
-
-/*****************
- * Xrealloc
- *****************/
-
-void *
-Xrealloc(pointer ptr, unsigned long amount)
-{
-#ifdef MEMBUG
- if (!Must_have_memory && Memory_fail &&
- ((random() % MEM_FAIL_SCALE) < Memory_fail))
- return (unsigned long *)NULL;
-#endif
- if ((long)amount <= 0)
- {
- if (ptr && !amount)
- free(ptr);
- return (unsigned long *)NULL;
- }
- amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
- if (ptr)
- ptr = (pointer)realloc((char *)ptr, amount);
- else
- ptr = (pointer)malloc(amount);
- if (ptr)
- return (unsigned long *)ptr;
- if (Must_have_memory)
- FatalError("Out of memory");
- return (unsigned long *)NULL;
-}
-
-/*****************
- * XNFrealloc
- * "no failure" realloc, alternate interface to Xrealloc w/o Must_have_memory
- *****************/
-
-void *
-XNFrealloc(pointer ptr, unsigned long amount)
-{
- if (( ptr = (pointer)Xrealloc( ptr, amount ) ) == NULL)
- {
- if ((long)amount > 0)
- FatalError( "Out of memory" );
- }
- return ((unsigned long *)ptr);
-}
-
-/*****************
- * Xfree
- * calls free
- *****************/
-
-void
-Xfree(pointer ptr)
-{
- if (ptr)
- free((char *)ptr);
-}
-
-void
-OsInitAllocator (void)
-{
-#ifdef MEMBUG
- static int been_here;
-
- /* Check the memory system after each generation */
- if (been_here)
- CheckMemory ();
- else
- been_here = 1;
-#endif
-}
-#endif /* !INTERNAL_MALLOC */
-
-
-char *
-Xstrdup(const char *s)
-{
- char *sd;
-
- if (s == NULL)
- return NULL;
-
- sd = (char *)Xalloc(strlen(s) + 1);
- if (sd != NULL)
- strcpy(sd, s);
- return sd;
-}
-
-
-char *
-XNFstrdup(const char *s)
-{
- char *sd;
-
- if (s == NULL)
- return NULL;
-
- sd = (char *)XNFalloc(strlen(s) + 1);
- strcpy(sd, s);
- return sd;
-}
-
-#ifdef SMART_SCHEDULE
-
-unsigned long SmartScheduleIdleCount;
-Bool SmartScheduleIdle;
-Bool SmartScheduleTimerStopped;
-
-#ifdef SIGVTALRM
-#define SMART_SCHEDULE_POSSIBLE
-#endif
-
-#ifdef SMART_SCHEDULE_POSSIBLE
-#define SMART_SCHEDULE_SIGNAL SIGALRM
-#define SMART_SCHEDULE_TIMER ITIMER_REAL
-#endif
-
-static void
-SmartScheduleStopTimer (void)
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct itimerval timer;
-
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 0;
- timer.it_value.tv_sec = 0;
- timer.it_value.tv_usec = 0;
- (void) setitimer (ITIMER_REAL, &timer, 0);
- SmartScheduleTimerStopped = TRUE;
-#endif
-}
-
-Bool
-SmartScheduleStartTimer (void)
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct itimerval timer;
-
- SmartScheduleTimerStopped = FALSE;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = SmartScheduleInterval * 1000;
- timer.it_value.tv_sec = 0;
- timer.it_value.tv_usec = SmartScheduleInterval * 1000;
- return setitimer (ITIMER_REAL, &timer, 0) >= 0;
-#endif
- return FALSE;
-}
-
-#ifdef SMART_SCHEDULE_POSSIBLE
-static void
-SmartScheduleTimer (int sig)
-{
- int olderrno = errno;
-
- SmartScheduleTime += SmartScheduleInterval;
- if (SmartScheduleIdle)
- {
- SmartScheduleStopTimer ();
- }
- errno = olderrno;
-}
-#endif
-
-Bool
-SmartScheduleInit (void)
-{
-#ifdef SMART_SCHEDULE_POSSIBLE
- struct sigaction act;
-
- if (SmartScheduleDisable)
- return TRUE;
-
- bzero ((char *) &act, sizeof(struct sigaction));
-
- /* Set up the timer signal function */
- act.sa_handler = SmartScheduleTimer;
- sigemptyset (&act.sa_mask);
- sigaddset (&act.sa_mask, SMART_SCHEDULE_SIGNAL);
- if (sigaction (SMART_SCHEDULE_SIGNAL, &act, 0) < 0)
- {
- perror ("sigaction for smart scheduler");
- return FALSE;
- }
- /* Set up the virtual timer */
- if (!SmartScheduleStartTimer ())
- {
- perror ("scheduling timer");
- return FALSE;
- }
- /* stop the timer and wait for WaitForSomething to start it */
- SmartScheduleStopTimer ();
- return TRUE;
-#else
- return FALSE;
-#endif
-}
-#endif
-
-#ifdef SIG_BLOCK
-static sigset_t PreviousSignalMask;
-static int BlockedSignalCount;
-#endif
-
-void
-OsBlockSignals (void)
-{
-#ifdef SIG_BLOCK
- if (BlockedSignalCount++ == 0)
- {
- sigset_t set;
-
- sigemptyset (&set);
-#ifdef SIGALRM
- sigaddset (&set, SIGALRM);
-#endif
-#ifdef SIGVTALRM
- sigaddset (&set, SIGVTALRM);
-#endif
-#ifdef SIGWINCH
- sigaddset (&set, SIGWINCH);
-#endif
-#ifdef SIGIO
- sigaddset (&set, SIGIO);
-#endif
-#ifdef SIGTSTP
- sigaddset (&set, SIGTSTP);
-#endif
-#ifdef SIGTTIN
- sigaddset (&set, SIGTTIN);
-#endif
-#ifdef SIGTTOU
- sigaddset (&set, SIGTTOU);
-#endif
-#ifdef SIGCHLD
- sigaddset (&set, SIGCHLD);
-#endif
- sigprocmask (SIG_BLOCK, &set, &PreviousSignalMask);
- }
-#endif
-}
-
-void
-OsReleaseSignals (void)
-{
-#ifdef SIG_BLOCK
- if (--BlockedSignalCount == 0)
- {
- sigprocmask (SIG_SETMASK, &PreviousSignalMask, 0);
- }
-#endif
-}
-
-#if !defined(WIN32) && !defined(__UNIXOS2__)
-/*
- * "safer" versions of system(3), popen(3) and pclose(3) which give up
- * all privs before running a command.
- *
- * This is based on the code in FreeBSD 2.2 libc.
- *
- * XXX It'd be good to redirect stderr so that it ends up in the log file
- * as well. As it is now, xkbcomp messages don't end up in the log file.
- */
-
-int
-System(char *command)
-{
- int pid, p;
-#ifdef SIGCHLD
- void (*csig)(int);
-#endif
- int status;
-
- if (!command)
- return(1);
-
-#ifdef SIGCHLD
- csig = signal(SIGCHLD, SIG_DFL);
-#endif
-
-#ifdef DEBUG
- ErrorF("System: `%s'\n", command);
-#endif
-
- switch (pid = fork()) {
- case -1: /* error */
- p = -1;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- execl("/bin/sh", "sh", "-c", command, (char *)NULL);
- _exit(127);
- default: /* parent */
- do {
- p = waitpid(pid, &status, 0);
- } while (p == -1 && errno == EINTR);
-
- }
-
-#ifdef SIGCHLD
- signal(SIGCHLD, csig);
-#endif
-
- return p == -1 ? -1 : status;
-}
-
-static struct pid {
- struct pid *next;
- FILE *fp;
- int pid;
-} *pidlist;
-
-pointer
-Popen(char *command, char *type)
-{
- struct pid *cur;
- FILE *iop;
- int pdes[2], pid;
-
- if (command == NULL || type == NULL)
- return NULL;
-
- if ((*type != 'r' && *type != 'w') || type[1])
- return NULL;
-
- if ((cur = (struct pid *)xalloc(sizeof(struct pid))) == NULL)
- return NULL;
-
- if (pipe(pdes) < 0) {
- xfree(cur);
- return NULL;
- }
-
- switch (pid = fork()) {
- case -1: /* error */
- close(pdes[0]);
- close(pdes[1]);
- xfree(cur);
- return NULL;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- if (*type == 'r') {
- if (pdes[1] != 1) {
- /* stdout */
- dup2(pdes[1], 1);
- close(pdes[1]);
- }
- close(pdes[0]);
- } else {
- if (pdes[0] != 0) {
- /* stdin */
- dup2(pdes[0], 0);
- close(pdes[0]);
- }
- close(pdes[1]);
- }
- execl("/bin/sh", "sh", "-c", command, (char *)NULL);
- _exit(127);
- }
-
- /* Avoid EINTR during stdio calls */
- OsBlockSignals ();
-
- /* parent */
- if (*type == 'r') {
- iop = fdopen(pdes[0], type);
- close(pdes[1]);
- } else {
- iop = fdopen(pdes[1], type);
- close(pdes[0]);
- }
-
- cur->fp = iop;
- cur->pid = pid;
- cur->next = pidlist;
- pidlist = cur;
-
-#ifdef DEBUG
- ErrorF("Popen: `%s', fp = %p\n", command, iop);
-#endif
-
- return iop;
-}
-
-/* fopen that drops privileges */
-pointer
-Fopen(char *file, char *type)
-{
- FILE *iop;
-#ifndef HAS_SAVED_IDS_AND_SETEUID
- struct pid *cur;
- int pdes[2], pid;
-
- if (file == NULL || type == NULL)
- return NULL;
-
- if ((*type != 'r' && *type != 'w') || type[1])
- return NULL;
-
- if ((cur = (struct pid *)xalloc(sizeof(struct pid))) == NULL)
- return NULL;
-
- if (pipe(pdes) < 0) {
- xfree(cur);
- return NULL;
- }
-
- switch (pid = fork()) {
- case -1: /* error */
- close(pdes[0]);
- close(pdes[1]);
- xfree(cur);
- return NULL;
- case 0: /* child */
- if (setgid(getgid()) == -1)
- _exit(127);
- if (setuid(getuid()) == -1)
- _exit(127);
- if (*type == 'r') {
- if (pdes[1] != 1) {
- /* stdout */
- dup2(pdes[1], 1);
- close(pdes[1]);
- }
- close(pdes[0]);
- } else {
- if (pdes[0] != 0) {
- /* stdin */
- dup2(pdes[0], 0);
- close(pdes[0]);
- }
- close(pdes[1]);
- }
- execl("/bin/cat", "cat", file, (char *)NULL);
- _exit(127);
- }
-
- /* Avoid EINTR during stdio calls */
- OsBlockSignals ();
-
- /* parent */
- if (*type == 'r') {
- iop = fdopen(pdes[0], type);
- close(pdes[1]);
- } else {
- iop = fdopen(pdes[1], type);
- close(pdes[0]);
- }
-
- cur->fp = iop;
- cur->pid = pid;
- cur->next = pidlist;
- pidlist = cur;
-
-#ifdef DEBUG
- ErrorF("Popen: `%s', fp = %p\n", command, iop);
-#endif
-
- return iop;
-#else
- int ruid, euid;
-
- ruid = getuid();
- euid = geteuid();
-
- if (seteuid(ruid) == -1) {
- return NULL;
- }
- iop = fopen(file, type);
-
- if (seteuid(euid) == -1) {
- fclose(iop);
- return NULL;
- }
- return iop;
-#endif /* HAS_SAVED_IDS_AND_SETEUID */
-}
-
-int
-Pclose(pointer iop)
-{
- struct pid *cur, *last;
- int pstat;
- int pid;
-
-#ifdef DEBUG
- ErrorF("Pclose: fp = %p\n", iop);
-#endif
-
- fclose(iop);
-
- for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
- if (cur->fp == iop)
- break;
- if (cur == NULL)
- return -1;
-
- do {
- pid = waitpid(cur->pid, &pstat, 0);
- } while (pid == -1 && errno == EINTR);
-
- if (last == NULL)
- pidlist = cur->next;
- else
- last->next = cur->next;
- xfree(cur);
-
- /* allow EINTR again */
- OsReleaseSignals ();
-
- return pid == -1 ? -1 : pstat;
-}
-
-int
-Fclose(pointer iop)
-{
-#ifdef HAS_SAVED_IDS_AND_SETEUID
- return fclose(iop);
-#else
- return Pclose(iop);
-#endif
-}
-
-#endif /* !WIN32 && !__UNIXOS2__ */
-
-
-/*
- * CheckUserParameters: check for long command line arguments and long
- * environment variables. By default, these checks are only done when
- * the server's euid != ruid. In 3.3.x, these checks were done in an
- * external wrapper utility.
- */
-
-/* Consider LD* variables insecure? */
-#ifndef REMOVE_ENV_LD
-#define REMOVE_ENV_LD 1
-#endif
-
-/* Remove long environment variables? */
-#ifndef REMOVE_LONG_ENV
-#define REMOVE_LONG_ENV 1
-#endif
-
-/*
- * Disallow stdout or stderr as pipes? It's possible to block the X server
- * when piping stdout+stderr to a pipe.
- *
- * Don't enable this because it looks like it's going to cause problems.
- */
-#ifndef NO_OUTPUT_PIPES
-#define NO_OUTPUT_PIPES 0
-#endif
-
-
-/* Check args and env only if running setuid (euid == 0 && euid != uid) ? */
-#ifndef CHECK_EUID
-#ifndef WIN32
-#define CHECK_EUID 1
-#else
-#define CHECK_EUID 0
-#endif
-#endif
-
-/*
- * Maybe the locale can be faked to make isprint(3) report that everything
- * is printable? Avoid it by default.
- */
-#ifndef USE_ISPRINT
-#define USE_ISPRINT 0
-#endif
-
-#define MAX_ARG_LENGTH 128
-#define MAX_ENV_LENGTH 256
-#define MAX_ENV_PATH_LENGTH 2048 /* Limit for *PATH and TERMCAP */
-
-#if USE_ISPRINT
-#include <ctype.h>
-#define checkPrintable(c) isprint(c)
-#else
-#define checkPrintable(c) (((c) & 0x7f) >= 0x20 && ((c) & 0x7f) != 0x7f)
-#endif
-
-enum BadCode {
- NotBad = 0,
- UnsafeArg,
- ArgTooLong,
- UnprintableArg,
- EnvTooLong,
- OutputIsPipe,
- InternalError
-};
-
-#if defined(VENDORSUPPORT)
-#define BUGADDRESS VENDORSUPPORT
-#elif defined(BUILDERADDR)
-#define BUGADDRESS BUILDERADDR
-#else
-#define BUGADDRESS "xorg@freedesktop.org"
-#endif
-
-#define ARGMSG \
- "\nIf the arguments used are valid, and have been rejected incorrectly\n" \
- "please send details of the arguments and why they are valid to\n" \
- "%s. In the meantime, you can start the Xserver as\n" \
- "the \"super user\" (root).\n"
-
-#define ENVMSG \
- "\nIf the environment is valid, and have been rejected incorrectly\n" \
- "please send details of the environment and why it is valid to\n" \
- "%s. In the meantime, you can start the Xserver as\n" \
- "the \"super user\" (root).\n"
-
-void
-CheckUserParameters(int argc, char **argv, char **envp)
-{
- enum BadCode bad = NotBad;
- int i = 0, j;
- char *a, *e = NULL;
-#if defined(__QNX__) && !defined(__QNXNTO__)
- char cmd_name[64];
-#endif
-
-#if CHECK_EUID
- if (geteuid() == 0 && getuid() != geteuid())
-#endif
- {
- /* Check each argv[] */
- for (i = 1; i < argc; i++) {
- if (strcmp(argv[i], "-fp") == 0)
- {
- i++; /* continue with next argument. skip the length check */
- if (i >= argc)
- break;
- } else
- {
- if (strlen(argv[i]) > MAX_ARG_LENGTH) {
- bad = ArgTooLong;
- break;
- }
- }
- a = argv[i];
- while (*a) {
- if (checkPrintable(*a) == 0) {
- bad = UnprintableArg;
- break;
- }
- a++;
- }
- if (bad)
- break;
- }
- if (!bad) {
- /* Check each envp[] */
- for (i = 0; envp[i]; i++) {
-
- /* Check for bad environment variables and values */
-#if REMOVE_ENV_LD
- while (envp[i] && (strncmp(envp[i], "LD", 2) == 0)) {
-#ifdef ENVDEBUG
- ErrorF("CheckUserParameters: removing %s from the "
- "environment\n", strtok(envp[i], "="));
-#endif
- for (j = i; envp[j]; j++) {
- envp[j] = envp[j+1];
- }
- }
-#endif
- if (envp[i] && (strlen(envp[i]) > MAX_ENV_LENGTH)) {
-#if REMOVE_LONG_ENV
-#ifdef ENVDEBUG
- ErrorF("CheckUserParameters: removing %s from the "
- "environment\n", strtok(envp[i], "="));
-#endif
- for (j = i; envp[j]; j++) {
- envp[j] = envp[j+1];
- }
- i--;
-#else
- char *eq;
- int len;
-
- eq = strchr(envp[i], '=');
- if (!eq)
- continue;
- len = eq - envp[i];
- e = malloc(len + 1);
- if (!e) {
- bad = InternalError;
- break;
- }
- strncpy(e, envp[i], len);
- e[len] = 0;
- if (len >= 4 &&
- (strcmp(e + len - 4, "PATH") == 0 ||
- strcmp(e, "TERMCAP") == 0)) {
- if (strlen(envp[i]) > MAX_ENV_PATH_LENGTH) {
- bad = EnvTooLong;
- break;
- } else {
- free(e);
- }
- } else {
- bad = EnvTooLong;
- break;
- }
-#endif
- }
- }
- }
-#if NO_OUTPUT_PIPES
- if (!bad) {
- struct stat buf;
-
- if (fstat(fileno(stdout), &buf) == 0 && S_ISFIFO(buf.st_mode))
- bad = OutputIsPipe;
- if (fstat(fileno(stderr), &buf) == 0 && S_ISFIFO(buf.st_mode))
- bad = OutputIsPipe;
- }
-#endif
- }
- switch (bad) {
- case NotBad:
- return;
- case UnsafeArg:
- ErrorF("Command line argument number %d is unsafe\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case ArgTooLong:
- ErrorF("Command line argument number %d is too long\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case UnprintableArg:
- ErrorF("Command line argument number %d contains unprintable"
- " characters\n", i);
- ErrorF(ARGMSG, BUGADDRESS);
- break;
- case EnvTooLong:
- ErrorF("Environment variable `%s' is too long\n", e);
- ErrorF(ENVMSG, BUGADDRESS);
- break;
- case OutputIsPipe:
- ErrorF("Stdout and/or stderr is a pipe\n");
- break;
- case InternalError:
- ErrorF("Internal Error\n");
- break;
- default:
- ErrorF("Unknown error\n");
- ErrorF(ARGMSG, BUGADDRESS);
- ErrorF(ENVMSG, BUGADDRESS);
- break;
- }
- FatalError("X server aborted because of unsafe environment\n");
-}
-
-/*
- * CheckUserAuthorization: check if the user is allowed to start the
- * X server. This usually means some sort of PAM checking, and it is
- * usually only done for setuid servers (uid != euid).
- */
-
-#ifdef USE_PAM
-#include <security/pam_appl.h>
-#include <security/pam_misc.h>
-#include <pwd.h>
-#endif /* USE_PAM */
-
-void
-CheckUserAuthorization(void)
-{
-#ifdef USE_PAM
- static struct pam_conv conv = {
- misc_conv,
- NULL
- };
-
- pam_handle_t *pamh = NULL;
- struct passwd *pw;
- int retval;
-
- if (getuid() != geteuid()) {
- pw = getpwuid(getuid());
- if (pw == NULL)
- FatalError("getpwuid() failed for uid %d\n", getuid());
-
- retval = pam_start("xserver", pw->pw_name, &conv, &pamh);
- if (retval != PAM_SUCCESS)
- FatalError("pam_start() failed.\n"
- "\tMissing or mangled PAM config file or module?\n");
-
- retval = pam_authenticate(pamh, 0);
- if (retval != PAM_SUCCESS) {
- pam_end(pamh, retval);
- FatalError("PAM authentication failed, cannot start X server.\n"
- "\tPerhaps you do not have console ownership?\n");
- }
-
- retval = pam_acct_mgmt(pamh, 0);
- if (retval != PAM_SUCCESS) {
- pam_end(pamh, retval);
- FatalError("PAM authentication failed, cannot start X server.\n"
- "\tPerhaps you do not have console ownership?\n");
- }
-
- /* this is not a session, so do not do session management */
- pam_end(pamh, PAM_SUCCESS);
- }
-#endif
-}
-
-#ifdef __SCO__
-#include <fcntl.h>
-
-static void
-lockit (int fd, short what)
-{
- struct flock lck;
-
- lck.l_whence = 0;
- lck.l_start = 0;
- lck.l_len = 1;
- lck.l_type = what;
-
- (void)fcntl (fd, F_SETLKW, &lck);
-}
-
-/* SCO OpenServer 5 lacks pread/pwrite. Emulate them. */
-ssize_t
-pread (int fd, void *buf, size_t nbytes, off_t offset)
-{
- off_t saved;
- ssize_t ret;
-
- lockit (fd, F_RDLCK);
- saved = lseek (fd, 0, SEEK_CUR);
- lseek (fd, offset, SEEK_SET);
- ret = read (fd, buf, nbytes);
- lseek (fd, saved, SEEK_SET);
- lockit (fd, F_UNLCK);
-
- return ret;
-}
-
-ssize_t
-pwrite (int fd, const void *buf, size_t nbytes, off_t offset)
-{
- off_t saved;
- ssize_t ret;
-
- lockit (fd, F_WRLCK);
- saved = lseek (fd, 0, SEEK_CUR);
- lseek (fd, offset, SEEK_SET);
- ret = write (fd, buf, nbytes);
- lseek (fd, saved, SEEK_SET);
- lockit (fd, F_UNLCK);
-
- return ret;
-}
-#endif /* __SCO__ */
diff --git a/nx-X11/programs/Xserver/os/xdmcp.c.NX.original b/nx-X11/programs/Xserver/os/xdmcp.c.NX.original
deleted file mode 100644
index 032d58f15..000000000
--- a/nx-X11/programs/Xserver/os/xdmcp.c.NX.original
+++ /dev/null
@@ -1,1710 +0,0 @@
-/* $XdotOrg: xc/programs/Xserver/os/xdmcp.c,v 1.10 2005/07/03 08:53:52 daniels Exp $ */
-/* $Xorg: xdmcp.c,v 1.4 2001/01/31 13:37:19 pookie Exp $ */
-/*
- * Copyright 1989 Network Computing Devices, Inc., Mountain View, California.
- *
- * 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 N.C.D. not be used in advertising or
- * publicity pertaining to distribution of the software without specific,
- * written prior permission. N.C.D. makes no representations about the
- * suitability of this software for any purpose. It is provided "as is"
- * without express or implied warranty.
- *
- */
-/* $XFree86: xc/programs/Xserver/os/xdmcp.c,v 3.31 2003/12/30 21:24:32 herrb Exp $ */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-
-#include <X11/Xos.h>
-
-#if !defined(WIN32)
-#ifndef Lynx
-#include <sys/param.h>
-#include <sys/socket.h>
-#else
-#include <socket.h>
-#endif
-#include <netinet/in.h>
-#include <netdb.h>
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "misc.h"
-#include <X11/Xpoll.h>
-#include "osdep.h"
-#include "input.h"
-#include "dixstruct.h"
-#include "opaque.h"
-
-#if defined(DGUX)
-#include <net/net_ioctl.h>
-#include <sys/ioctl.h>
-#endif
-
-#ifdef STREAMSCONN
-#include <tiuser.h>
-#include <netconfig.h>
-#include <netdir.h>
-#endif
-
-#ifndef NX_TRANS_SOCKET
-
-#define NX_TRANS_SOCKET
-#define NX_TRANS_TEST
-
-#endif
-
-#ifdef XDMCP
-#undef REQUEST
-
-#ifdef XDMCP_NO_IPV6
-#undef IPv6
-#endif
-
-#include <X11/Xdmcp.h>
-
-#define X_INCLUDE_NETDB_H
-#include <X11/Xos_r.h>
-
-#ifdef NX_TRANS_SOCKET
-
-xdmcp_states XdmcpState;
-
-int XdmcpStartTime;
-int XdmcpTimeOutRtx;
-
-#endif
-
-extern char *defaultDisplayClass;
-
-static int xdmcpSocket, sessionSocket;
-static xdmcp_states state;
-#if defined(IPv6) && defined(AF_INET6)
-static int xdmcpSocket6;
-static struct sockaddr_storage req_sockaddr;
-#else
-static struct sockaddr_in req_sockaddr;
-#endif
-static int req_socklen;
-static CARD32 SessionID;
-static CARD32 timeOutTime;
-static int timeOutRtx;
-static CARD32 defaultKeepaliveDormancy = XDM_DEF_DORMANCY;
-static CARD32 keepaliveDormancy = XDM_DEF_DORMANCY;
-static CARD16 DisplayNumber;
-static xdmcp_states XDM_INIT_STATE = XDM_OFF;
-#ifdef HASXDMAUTH
-static char *xdmAuthCookie;
-#endif
-
-static XdmcpBuffer buffer;
-
-#if defined(IPv6) && defined(AF_INET6)
-
-static struct addrinfo *mgrAddr;
-static struct addrinfo *mgrAddrFirst;
-
-#define SOCKADDR_TYPE struct sockaddr_storage
-#define SOCKADDR_FAMILY(s) ((struct sockaddr *)&(s))->sa_family
-
-#ifdef BSD44SOCKETS
-#define SOCKLEN_FIELD(s) ((struct sockaddr *)&(s))->sa_len
-#define SOCKLEN_TYPE unsigned char
-#else
-#define SOCKLEN_TYPE unsigned int
-#endif
-
-#else
-
-#define SOCKADDR_TYPE struct sockaddr_in
-#define SOCKADDR_FAMILY(s) (s).sin_family
-
-#ifdef BSD44SOCKETS
-#define SOCKLEN_FIELD(s) (s).sin_len
-#define SOCKLEN_TYPE unsigned char
-#else
-#define SOCKLEN_TYPE size_t
-#endif
-
-#endif
-
-static SOCKADDR_TYPE ManagerAddress;
-static SOCKADDR_TYPE FromAddress;
-
-#ifdef SOCKLEN_FIELD
-#define ManagerAddressLen SOCKLEN_FIELD(ManagerAddress)
-#define FromAddressLen SOCKLEN_FIELD(FromAddress)
-#else
-static SOCKLEN_TYPE ManagerAddressLen, FromAddressLen;
-#endif
-
-#if defined(IPv6) && defined(AF_INET6)
-static struct multicastinfo {
- struct multicastinfo *next;
- struct addrinfo *ai;
- int hops;
-} *mcastlist;
-#endif
-
-static void XdmcpAddHost(
- struct sockaddr *from,
- int fromlen,
- ARRAY8Ptr AuthenticationName,
- ARRAY8Ptr hostname,
- ARRAY8Ptr status);
-
-static void XdmcpSelectHost(
- struct sockaddr *host_sockaddr,
- int host_len,
- ARRAY8Ptr AuthenticationName);
-
-static void get_xdmcp_sock(void);
-
-static void send_query_msg(void);
-
-static void recv_willing_msg(
- struct sockaddr * /*from*/,
- int /*fromlen*/,
- unsigned /*length*/);
-
-static void send_request_msg(void);
-
-static void recv_accept_msg(unsigned /*length*/);
-
-static void recv_decline_msg(unsigned /*length*/);
-
-static void send_manage_msg(void);
-
-static void recv_refuse_msg(unsigned /*length*/);
-
-static void recv_failed_msg(unsigned /*length*/);
-
-static void send_keepalive_msg(void);
-
-static void recv_alive_msg(unsigned /*length*/);
-
-static void XdmcpFatal(
- char * /*type*/,
- ARRAY8Ptr /*status*/);
-
-static void XdmcpWarning(char * /*str*/);
-
-static void get_manager_by_name(
- int /*argc*/,
- char ** /*argv*/,
- int /*i*/);
-
-static void get_fromaddr_by_name(int /*argc*/, char ** /*argv*/, int /*i*/);
-
-#if defined(IPv6) && defined(AF_INET6)
-static int get_mcast_options(int /*argc*/, char ** /*argv*/, int /*i*/);
-#endif
-
-static void receive_packet(int /*socketfd*/);
-
-static void send_packet(void);
-
-extern void XdmcpDeadSession(char * /*reason*/);
-
-static void timeout(void);
-
-static void restart(void);
-
-static void XdmcpBlockHandler(
- pointer /*data*/,
- struct timeval ** /*wt*/,
- pointer /*LastSelectMask*/);
-
-static void XdmcpWakeupHandler(
- pointer /*data*/,
- int /*i*/,
- pointer /*LastSelectMask*/);
-
-void XdmcpRegisterManufacturerDisplayID(
- char * /*name*/,
- int /*length*/);
-
-
-static unsigned short xdm_udp_port = XDM_UDP_PORT;
-static Bool OneSession = FALSE;
-static const char *xdm_from = NULL;
-
-void
-XdmcpUseMsg (void)
-{
- ErrorF("-query host-name contact named host for XDMCP\n");
- ErrorF("-broadcast broadcast for XDMCP\n");
-#if defined(IPv6) && defined(AF_INET6)
- ErrorF("-multicast [addr [hops]] IPv6 multicast for XDMCP\n");
-#endif
- ErrorF("-indirect host-name contact named host for indirect XDMCP\n");
- ErrorF("-port port-num UDP port number to send messages to\n");
- ErrorF("-from local-address specify the local address to connect from\n");
- ErrorF("-once Terminate server after one session\n");
- ErrorF("-class display-class specify display class to send in manage\n");
-#ifdef HASXDMAUTH
- ErrorF("-cookie xdm-auth-bits specify the magic cookie for XDMCP\n");
-#endif
- ErrorF("-displayID display-id manufacturer display ID for request\n");
-}
-
-int
-XdmcpOptions(int argc, char **argv, int i)
-{
- if (strcmp(argv[i], "-query") == 0) {
- get_manager_by_name(argc, argv, i++);
- XDM_INIT_STATE = XDM_QUERY;
- AccessUsingXdmcp ();
- return (i + 1);
- }
- if (strcmp(argv[i], "-broadcast") == 0) {
- XDM_INIT_STATE = XDM_BROADCAST;
- AccessUsingXdmcp ();
- return (i + 1);
- }
-#if defined(IPv6) && defined(AF_INET6)
- if (strcmp(argv[i], "-multicast") == 0) {
- i = get_mcast_options(argc, argv, ++i);
- XDM_INIT_STATE = XDM_MULTICAST;
- AccessUsingXdmcp ();
- return (i + 1);
- }
-#endif
- if (strcmp(argv[i], "-indirect") == 0) {
- get_manager_by_name(argc, argv, i++);
- XDM_INIT_STATE = XDM_INDIRECT;
- AccessUsingXdmcp ();
- return (i + 1);
- }
- if (strcmp(argv[i], "-port") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing port number in command line\n");
- }
- xdm_udp_port = (unsigned short) atoi(argv[i]);
- return (i + 1);
- }
- if (strcmp(argv[i], "-from") == 0) {
- get_fromaddr_by_name(argc, argv, ++i);
- return (i + 1);
- }
- if (strcmp(argv[i], "-once") == 0) {
- OneSession = TRUE;
- return (i + 1);
- }
- if (strcmp(argv[i], "-class") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing class name in command line\n");
- }
- defaultDisplayClass = argv[i];
- return (i + 1);
- }
-#ifdef HASXDMAUTH
- if (strcmp(argv[i], "-cookie") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing cookie data in command line\n");
- }
- xdmAuthCookie = argv[i];
- return (i + 1);
- }
-#endif
- if (strcmp(argv[i], "-displayID") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing displayID in command line\n");
- }
- XdmcpRegisterManufacturerDisplayID (argv[i], strlen (argv[i]));
- return (i + 1);
- }
- return (i);
-}
-
-/*
- * This section is a collection of routines for
- * registering server-specific data with the XDMCP
- * state machine.
- */
-
-
-/*
- * Save all broadcast addresses away so BroadcastQuery
- * packets get sent everywhere
- */
-
-#define MAX_BROADCAST 10
-
-/* This stays sockaddr_in since IPv6 doesn't support broadcast */
-static struct sockaddr_in BroadcastAddresses[MAX_BROADCAST];
-static int NumBroadcastAddresses;
-
-void
-XdmcpRegisterBroadcastAddress (struct sockaddr_in *addr)
-{
- struct sockaddr_in *bcast;
- if (NumBroadcastAddresses >= MAX_BROADCAST)
- return;
- bcast = &BroadcastAddresses[NumBroadcastAddresses++];
- bzero (bcast, sizeof (struct sockaddr_in));
-#ifdef BSD44SOCKETS
- bcast->sin_len = addr->sin_len;
-#endif
- bcast->sin_family = addr->sin_family;
- bcast->sin_port = htons (xdm_udp_port);
- bcast->sin_addr = addr->sin_addr;
-}
-
-/*
- * Each authentication type is registered here; Validator
- * will be called to check all access attempts using
- * the specified authentication type
- */
-
-static ARRAYofARRAY8 AuthenticationNames, AuthenticationDatas;
-typedef struct _AuthenticationFuncs {
- ValidatorFunc Validator;
- GeneratorFunc Generator;
- AddAuthorFunc AddAuth;
-} AuthenticationFuncsRec, *AuthenticationFuncsPtr;
-
-static AuthenticationFuncsPtr AuthenticationFuncsList;
-
-void
-XdmcpRegisterAuthentication (
- char *name,
- int namelen,
- char *data,
- int datalen,
- ValidatorFunc Validator,
- GeneratorFunc Generator,
- AddAuthorFunc AddAuth)
-{
- int i;
- ARRAY8 AuthenticationName, AuthenticationData;
- static AuthenticationFuncsPtr newFuncs;
-
- if (!XdmcpAllocARRAY8 (&AuthenticationName, namelen))
- return;
- if (!XdmcpAllocARRAY8 (&AuthenticationData, datalen))
- {
- XdmcpDisposeARRAY8 (&AuthenticationName);
- return;
- }
- for (i = 0; i < namelen; i++)
- AuthenticationName.data[i] = name[i];
- for (i = 0; i < datalen; i++)
- AuthenticationData.data[i] = data[i];
- if (!(XdmcpReallocARRAYofARRAY8 (&AuthenticationNames,
- AuthenticationNames.length + 1) &&
- XdmcpReallocARRAYofARRAY8 (&AuthenticationDatas,
- AuthenticationDatas.length + 1) &&
- (newFuncs = (AuthenticationFuncsPtr) xalloc (
- (AuthenticationNames.length + 1) * sizeof (AuthenticationFuncsRec)))))
- {
- XdmcpDisposeARRAY8 (&AuthenticationName);
- XdmcpDisposeARRAY8 (&AuthenticationData);
- return;
- }
- for (i = 0; i < AuthenticationNames.length - 1; i++)
- newFuncs[i] = AuthenticationFuncsList[i];
- newFuncs[AuthenticationNames.length-1].Validator = Validator;
- newFuncs[AuthenticationNames.length-1].Generator = Generator;
- newFuncs[AuthenticationNames.length-1].AddAuth = AddAuth;
- xfree (AuthenticationFuncsList);
- AuthenticationFuncsList = newFuncs;
- AuthenticationNames.data[AuthenticationNames.length-1] = AuthenticationName;
- AuthenticationDatas.data[AuthenticationDatas.length-1] = AuthenticationData;
-}
-
-/*
- * Select the authentication type to be used; this is
- * set by the manager of the host to be connected to.
- */
-
-ARRAY8 noAuthenticationName = {(CARD16) 0, (CARD8Ptr) 0};
-ARRAY8 noAuthenticationData = {(CARD16) 0, (CARD8Ptr) 0};
-ARRAY8Ptr AuthenticationName = &noAuthenticationName;
-ARRAY8Ptr AuthenticationData = &noAuthenticationData;
-AuthenticationFuncsPtr AuthenticationFuncs;
-
-void
-XdmcpSetAuthentication (ARRAY8Ptr name)
-{
- int i;
-
- for (i = 0; i < AuthenticationNames.length; i++)
- if (XdmcpARRAY8Equal (&AuthenticationNames.data[i], name))
- {
- AuthenticationName = &AuthenticationNames.data[i];
- AuthenticationData = &AuthenticationDatas.data[i];
- AuthenticationFuncs = &AuthenticationFuncsList[i];
- break;
- }
-}
-
-/*
- * Register the host address for the display
- */
-
-static ARRAY16 ConnectionTypes;
-static ARRAYofARRAY8 ConnectionAddresses;
-static long xdmcpGeneration;
-
-void
-XdmcpRegisterConnection (
- int type,
- char *address,
- int addrlen)
-{
- int i;
- CARD8 *newAddress;
-
- if (xdmcpGeneration != serverGeneration)
- {
- XdmcpDisposeARRAY16 (&ConnectionTypes);
- XdmcpDisposeARRAYofARRAY8 (&ConnectionAddresses);
- xdmcpGeneration = serverGeneration;
- }
- if (xdm_from != NULL) { /* Only register the requested address */
- const void *regAddr = address;
- const void *fromAddr = NULL;
- int regAddrlen = addrlen;
-
- if (addrlen == sizeof(struct in_addr)) {
- if (SOCKADDR_FAMILY(FromAddress) == AF_INET) {
- fromAddr = &((struct sockaddr_in *)&FromAddress)->sin_addr;
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if ((SOCKADDR_FAMILY(FromAddress) == AF_INET6) &&
- IN6_IS_ADDR_V4MAPPED(
- &((struct sockaddr_in6 *)&FromAddress)->sin6_addr)) {
- fromAddr = &((struct sockaddr_in6 *)&FromAddress)->sin6_addr.s6_addr[12];
- }
-#endif
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if (addrlen == sizeof(struct in6_addr)) {
- if (SOCKADDR_FAMILY(FromAddress) == AF_INET6) {
- fromAddr = &((struct sockaddr_in6 *)&FromAddress)->sin6_addr;
- } else if ((SOCKADDR_FAMILY(FromAddress) == AF_INET) &&
- IN6_IS_ADDR_V4MAPPED((struct in6_addr *) address)) {
- fromAddr = &((struct sockaddr_in *)&FromAddress)->sin_addr;
- regAddr = &((struct sockaddr_in6 *)&address)->sin6_addr.s6_addr[12];
- regAddrlen = sizeof(struct in_addr);
- }
- }
-#endif
- if (fromAddr && memcmp(regAddr, fromAddr, regAddrlen) != 0) {
- return;
- }
- }
- newAddress = (CARD8 *) xalloc (addrlen * sizeof (CARD8));
- if (!newAddress)
- return;
- if (!XdmcpReallocARRAY16 (&ConnectionTypes, ConnectionTypes.length + 1))
- {
- xfree (newAddress);
- return;
- }
- if (!XdmcpReallocARRAYofARRAY8 (&ConnectionAddresses,
- ConnectionAddresses.length + 1))
- {
- xfree (newAddress);
- return;
- }
- ConnectionTypes.data[ConnectionTypes.length - 1] = (CARD16) type;
- for (i = 0; i < addrlen; i++)
- newAddress[i] = address[i];
- ConnectionAddresses.data[ConnectionAddresses.length-1].data = newAddress;
- ConnectionAddresses.data[ConnectionAddresses.length-1].length = addrlen;
-}
-
-/*
- * Register an Authorization Name. XDMCP advertises this list
- * to the manager.
- */
-
-static ARRAYofARRAY8 AuthorizationNames;
-
-void
-XdmcpRegisterAuthorizations (void)
-{
- XdmcpDisposeARRAYofARRAY8 (&AuthorizationNames);
- RegisterAuthorizations ();
-}
-
-void
-XdmcpRegisterAuthorization (char *name, int namelen)
-{
- ARRAY8 authName;
- int i;
-
- authName.data = (CARD8 *) xalloc (namelen * sizeof (CARD8));
- if (!authName.data)
- return;
- if (!XdmcpReallocARRAYofARRAY8 (&AuthorizationNames, AuthorizationNames.length +1))
- {
- xfree (authName.data);
- return;
- }
- for (i = 0; i < namelen; i++)
- authName.data[i] = (CARD8) name[i];
- authName.length = namelen;
- AuthorizationNames.data[AuthorizationNames.length-1] = authName;
-}
-
-/*
- * Register the DisplayClass string
- */
-
-ARRAY8 DisplayClass;
-
-void
-XdmcpRegisterDisplayClass (char *name, int length)
-{
- int i;
-
- XdmcpDisposeARRAY8 (&DisplayClass);
- if (!XdmcpAllocARRAY8 (&DisplayClass, length))
- return;
- for (i = 0; i < length; i++)
- DisplayClass.data[i] = (CARD8) name[i];
-}
-
-/*
- * Register the Manufacturer display ID
- */
-
-ARRAY8 ManufacturerDisplayID;
-
-void
-XdmcpRegisterManufacturerDisplayID (char *name, int length)
-{
- int i;
-
- XdmcpDisposeARRAY8 (&ManufacturerDisplayID);
- if (!XdmcpAllocARRAY8 (&ManufacturerDisplayID, length))
- return;
- for (i = 0; i < length; i++)
- ManufacturerDisplayID.data[i] = (CARD8) name[i];
-}
-
-/*
- * initialize XDMCP; create the socket, compute the display
- * number, set up the state machine
- */
-
-void
-XdmcpInit(void)
-{
-#ifdef NX_TRANS_SOCKET
-
- XdmcpStartTime = GetTimeInMillis();
-
-#endif
-
- state = XDM_INIT_STATE;
-#ifdef HASXDMAUTH
- if (xdmAuthCookie)
- XdmAuthenticationInit (xdmAuthCookie, strlen (xdmAuthCookie));
-#endif
- if (state != XDM_OFF)
- {
- XdmcpRegisterAuthorizations();
- XdmcpRegisterDisplayClass (defaultDisplayClass, strlen (defaultDisplayClass));
- AccessUsingXdmcp();
- RegisterBlockAndWakeupHandlers (XdmcpBlockHandler, XdmcpWakeupHandler,
- (pointer) 0);
- timeOutRtx = 0;
- DisplayNumber = (CARD16) atoi(display);
- get_xdmcp_sock();
- send_packet();
- }
-}
-
-void
-XdmcpReset (void)
-{
- state = XDM_INIT_STATE;
- if (state != XDM_OFF)
- {
- RegisterBlockAndWakeupHandlers (XdmcpBlockHandler, XdmcpWakeupHandler,
- (pointer) 0);
- timeOutRtx = 0;
- send_packet();
- }
-}
-
-/*
- * Called whenever a new connection is created; notices the
- * first connection and saves it to terminate the session
- * when it is closed
- */
-
-void
-XdmcpOpenDisplay(int sock)
-{
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- state = XDM_RUN_SESSION;
- sessionSocket = sock;
-}
-
-void
-XdmcpCloseDisplay(int sock)
-{
- if ((state != XDM_RUN_SESSION && state != XDM_AWAIT_ALIVE_RESPONSE)
- || sessionSocket != sock)
- return;
- state = XDM_INIT_STATE;
- if (OneSession)
- dispatchException |= DE_TERMINATE;
- else
- dispatchException |= DE_RESET;
- isItTimeToYield = TRUE;
-}
-
-/*
- * called before going to sleep, this routine
- * may modify the timeout value about to be sent
- * to select; in this way XDMCP can do appropriate things
- * dynamically while starting up
- */
-
-/*ARGSUSED*/
-static void
-XdmcpBlockHandler(
- pointer data, /* unused */
- struct timeval **wt,
- pointer pReadmask)
-{
- fd_set *LastSelectMask = (fd_set*)pReadmask;
- CARD32 millisToGo;
-
- if (state == XDM_OFF)
- return;
- FD_SET(xdmcpSocket, LastSelectMask);
-#if defined(IPv6) && defined(AF_INET6)
- if (xdmcpSocket6 >= 0)
- FD_SET(xdmcpSocket6, LastSelectMask);
-#endif
- if (timeOutTime == 0)
- return;
- millisToGo = timeOutTime - GetTimeInMillis();
- if ((int) millisToGo < 0)
- millisToGo = 0;
- AdjustWaitForDelay (wt, millisToGo);
-}
-
-/*
- * called after select returns; this routine will
- * recognise when XDMCP packets await and
- * process them appropriately
- */
-
-/*ARGSUSED*/
-static void
-XdmcpWakeupHandler(
- pointer data, /* unused */
- int i,
- pointer pReadmask)
-{
- fd_set* LastSelectMask = (fd_set*)pReadmask;
- fd_set devicesReadable;
-
-#ifdef NX_TRANS_SOCKET
-
- XdmcpState = state;
- XdmcpTimeOutRtx = timeOutRtx;
-
-#endif
-
- if (state == XDM_OFF)
- return;
- if (i > 0)
- {
- if (FD_ISSET(xdmcpSocket, LastSelectMask))
- {
- receive_packet(xdmcpSocket);
- FD_CLR(xdmcpSocket, LastSelectMask);
- }
-#if defined(IPv6) && defined(AF_INET6)
- if (xdmcpSocket6 >= 0 && FD_ISSET(xdmcpSocket6, LastSelectMask))
- {
- receive_packet(xdmcpSocket6);
- FD_CLR(xdmcpSocket6, LastSelectMask);
- }
-#endif
- XFD_ANDSET(&devicesReadable, LastSelectMask, &EnabledDevices);
- if (XFD_ANYSET(&devicesReadable))
- {
- if (state == XDM_AWAIT_USER_INPUT)
- restart();
- else if (state == XDM_RUN_SESSION)
- keepaliveDormancy = defaultKeepaliveDormancy;
- }
- if (XFD_ANYSET(&AllClients) && state == XDM_RUN_SESSION)
- timeOutTime = GetTimeInMillis() + keepaliveDormancy * 1000;
- }
- else if (timeOutTime && (int) (GetTimeInMillis() - timeOutTime) >= 0)
- {
- if (state == XDM_RUN_SESSION)
- {
- state = XDM_KEEPALIVE;
- send_packet();
- }
- else
- timeout();
- }
-}
-
-/*
- * This routine should be called from the routine that drives the
- * user's host menu when the user selects a host
- */
-
-static void
-XdmcpSelectHost(
- struct sockaddr *host_sockaddr,
- int host_len,
- ARRAY8Ptr AuthenticationName)
-{
- state = XDM_START_CONNECTION;
- memmove(&req_sockaddr, host_sockaddr, host_len);
- req_socklen = host_len;
- XdmcpSetAuthentication (AuthenticationName);
- send_packet();
-}
-
-/*
- * !!! this routine should be replaced by a routine that adds
- * the host to the user's host menu. the current version just
- * selects the first host to respond with willing message.
- */
-
-/*ARGSUSED*/
-static void
-XdmcpAddHost(
- struct sockaddr *from,
- int fromlen,
- ARRAY8Ptr AuthenticationName,
- ARRAY8Ptr hostname,
- ARRAY8Ptr status)
-{
- XdmcpSelectHost(from, fromlen, AuthenticationName);
-}
-
-/*
- * A message is queued on the socket; read it and
- * do the appropriate thing
- */
-
-ARRAY8 UnwillingMessage = { (CARD8) 14, (CARD8 *) "Host unwilling" };
-
-static void
-receive_packet(int socketfd)
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct sockaddr_storage from;
-#else
- struct sockaddr_in from;
-#endif
- int fromlen = sizeof(from);
- XdmcpHeader header;
-
- /* read message off socket */
- if (!XdmcpFill (socketfd, &buffer, (XdmcpNetaddr) &from, &fromlen))
- return;
-
- /* reset retransmission backoff */
- timeOutRtx = 0;
-
- if (!XdmcpReadHeader (&buffer, &header))
- return;
-
- if (header.version != XDM_PROTOCOL_VERSION)
- return;
-
- switch (header.opcode) {
- case WILLING:
- recv_willing_msg((struct sockaddr *) &from, fromlen, header.length);
- break;
- case UNWILLING:
- XdmcpFatal("Manager unwilling", &UnwillingMessage);
- break;
- case ACCEPT:
- recv_accept_msg(header.length);
- break;
- case DECLINE:
- recv_decline_msg(header.length);
- break;
- case REFUSE:
- recv_refuse_msg(header.length);
- break;
- case FAILED:
- recv_failed_msg(header.length);
- break;
- case ALIVE:
- recv_alive_msg(header.length);
- break;
- }
-}
-
-/*
- * send the appropriate message given the current state
- */
-
-static void
-send_packet(void)
-{
- int rtx;
- switch (state) {
- case XDM_QUERY:
- case XDM_BROADCAST:
- case XDM_INDIRECT:
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_MULTICAST:
-#endif
- send_query_msg();
- break;
- case XDM_START_CONNECTION:
- send_request_msg();
- break;
- case XDM_MANAGE:
- send_manage_msg();
- break;
- case XDM_KEEPALIVE:
- send_keepalive_msg();
- break;
- default:
- break;
- }
- rtx = (XDM_MIN_RTX << timeOutRtx);
- if (rtx > XDM_MAX_RTX)
- rtx = XDM_MAX_RTX;
- timeOutTime = GetTimeInMillis() + rtx * 1000;
-}
-
-/*
- * The session is declared dead for some reason; too many
- * timeouts, or Keepalive failure.
- */
-
-void
-XdmcpDeadSession (char *reason)
-{
- ErrorF ("XDM: %s, declaring session dead\n", reason);
- state = XDM_INIT_STATE;
- isItTimeToYield = TRUE;
- dispatchException |= DE_RESET;
- timeOutTime = 0;
- timeOutRtx = 0;
- send_packet();
-}
-
-/*
- * Timeout waiting for an XDMCP response.
- */
-
-static void
-timeout(void)
-{
- timeOutRtx++;
- if (state == XDM_AWAIT_ALIVE_RESPONSE && timeOutRtx >= XDM_KA_RTX_LIMIT )
- {
- XdmcpDeadSession ("too many keepalive retransmissions");
- return;
- }
- else if (timeOutRtx >= XDM_RTX_LIMIT)
- {
- /* Quit if "-once" specified, otherwise reset and try again. */
- if (OneSession) {
- dispatchException |= DE_TERMINATE;
- ErrorF("XDM: too many retransmissions\n");
- } else {
- XdmcpDeadSession("too many retransmissions");
- }
- return;
- }
-
-#if defined(IPv6) && defined(AF_INET6)
- if (state == XDM_COLLECT_QUERY || state == XDM_COLLECT_INDIRECT_QUERY) {
- /* Try next address */
- for (mgrAddr = mgrAddr->ai_next; ; mgrAddr = mgrAddr->ai_next) {
- if (mgrAddr == NULL) {
- mgrAddr = mgrAddrFirst;
- }
- if (mgrAddr->ai_family == AF_INET
- || mgrAddr->ai_family == AF_INET6)
- break;
- }
-#ifndef SIN6_LEN
- ManagerAddressLen = mgrAddr->ai_addrlen;
-#endif
- memcpy(&ManagerAddress, mgrAddr->ai_addr, mgrAddr->ai_addrlen);
- }
-#endif
-
- switch (state) {
- case XDM_COLLECT_QUERY:
- state = XDM_QUERY;
- break;
- case XDM_COLLECT_BROADCAST_QUERY:
- state = XDM_BROADCAST;
- break;
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_COLLECT_MULTICAST_QUERY:
- state = XDM_MULTICAST;
- break;
-#endif
- case XDM_COLLECT_INDIRECT_QUERY:
- state = XDM_INDIRECT;
- break;
- case XDM_AWAIT_REQUEST_RESPONSE:
- state = XDM_START_CONNECTION;
- break;
- case XDM_AWAIT_MANAGE_RESPONSE:
- state = XDM_MANAGE;
- break;
- case XDM_AWAIT_ALIVE_RESPONSE:
- state = XDM_KEEPALIVE;
- break;
- default:
- break;
- }
- send_packet();
-}
-
-static void
-restart(void)
-{
- state = XDM_INIT_STATE;
- timeOutRtx = 0;
- send_packet();
-}
-
-int
-XdmcpCheckAuthentication (
- ARRAY8Ptr Name,
- ARRAY8Ptr Data,
- int packet_type)
-{
- return (XdmcpARRAY8Equal (Name, AuthenticationName) &&
- (AuthenticationName->length == 0 ||
- (*AuthenticationFuncs->Validator) (AuthenticationData, Data, packet_type)));
-}
-
-int
-XdmcpAddAuthorization (
- ARRAY8Ptr name,
- ARRAY8Ptr data)
-{
- AddAuthorFunc AddAuth;
-
- if (AuthenticationFuncs && AuthenticationFuncs->AddAuth)
- AddAuth = AuthenticationFuncs->AddAuth;
- else
- AddAuth = AddAuthorization;
- return (*AddAuth) ((unsigned short)name->length,
- (char *)name->data,
- (unsigned short)data->length,
- (char *)data->data);
-}
-
-/*
- * from here to the end of this file are routines private
- * to the state machine.
- */
-
-static void
-get_xdmcp_sock(void)
-{
-#ifdef STREAMSCONN
- struct netconfig *nconf;
-
- if ((xdmcpSocket = t_open("/dev/udp", O_RDWR, 0)) < 0) {
- XdmcpWarning("t_open() of /dev/udp failed");
- return;
- }
-
- if( t_bind(xdmcpSocket,NULL,NULL) < 0 ) {
- XdmcpWarning("UDP socket creation failed");
- t_error("t_bind(xdmcpSocket) failed" );
- t_close(xdmcpSocket);
- return;
- }
-
- /*
- * This part of the code looks contrived. It will actually fit in nicely
- * when the CLTS part of Xtrans is implemented.
- */
-
- if( (nconf=getnetconfigent("udp")) == NULL ) {
- XdmcpWarning("UDP socket creation failed: getnetconfigent()");
- t_unbind(xdmcpSocket);
- t_close(xdmcpSocket);
- return;
- }
-
- if( netdir_options(nconf, ND_SET_BROADCAST, xdmcpSocket, NULL) ) {
- XdmcpWarning("UDP set broadcast option failed: netdir_options()");
- freenetconfigent(nconf);
- t_unbind(xdmcpSocket);
- t_close(xdmcpSocket);
- return;
- }
-
- freenetconfigent(nconf);
-#else
- int soopts = 1;
-
-#if defined(IPv6) && defined(AF_INET6)
- if ((xdmcpSocket6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
- XdmcpWarning("INET6 UDP socket creation failed");
-#endif
- if ((xdmcpSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
- XdmcpWarning("UDP socket creation failed");
-#ifdef SO_BROADCAST
- else if (setsockopt(xdmcpSocket, SOL_SOCKET, SO_BROADCAST, (char *)&soopts,
- sizeof(soopts)) < 0)
- XdmcpWarning("UDP set broadcast socket-option failed");
-#endif /* SO_BROADCAST */
- if (xdmcpSocket >= 0 && xdm_from != NULL) {
- if (bind(xdmcpSocket, (struct sockaddr *)&FromAddress,
- FromAddressLen) < 0) {
- FatalError("Xserver: failed to bind to -from address: %s\n", xdm_from);
- }
- }
-#endif /* STREAMSCONN */
-}
-
-static void
-send_query_msg(void)
-{
- XdmcpHeader header;
- Bool broadcast = FALSE;
-#if defined(IPv6) && defined(AF_INET6)
- Bool multicast = FALSE;
-#endif
- int i;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- switch(state){
- case XDM_QUERY:
- header.opcode = (CARD16) QUERY;
- state = XDM_COLLECT_QUERY;
- break;
- case XDM_BROADCAST:
- header.opcode = (CARD16) BROADCAST_QUERY;
- state = XDM_COLLECT_BROADCAST_QUERY;
- broadcast = TRUE;
- break;
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_MULTICAST:
- header.opcode = (CARD16) BROADCAST_QUERY;
- state = XDM_COLLECT_MULTICAST_QUERY;
- multicast = TRUE;
- break;
-#endif
- case XDM_INDIRECT:
- header.opcode = (CARD16) INDIRECT_QUERY;
- state = XDM_COLLECT_INDIRECT_QUERY;
- break;
- default:
- break;
- }
- header.length = 1;
- for (i = 0; i < AuthenticationNames.length; i++)
- header.length += 2 + AuthenticationNames.data[i].length;
-
- XdmcpWriteHeader (&buffer, &header);
- XdmcpWriteARRAYofARRAY8 (&buffer, &AuthenticationNames);
- if (broadcast)
- {
- int i;
-
- for (i = 0; i < NumBroadcastAddresses; i++)
- XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &BroadcastAddresses[i],
- sizeof (struct sockaddr_in));
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if (multicast)
- {
- struct multicastinfo *mcl;
- struct addrinfo *ai;
-
- for (mcl = mcastlist; mcl != NULL; mcl = mcl->next) {
- for (ai = mcl->ai ; ai != NULL; ai = ai->ai_next) {
- if (ai->ai_family == AF_INET) {
- unsigned char hopflag = (unsigned char) mcl->hops;
- socketfd = xdmcpSocket;
- setsockopt(socketfd, IPPROTO_IP, IP_MULTICAST_TTL,
- &hopflag, sizeof(hopflag));
- } else if (ai->ai_family == AF_INET6) {
- int hopflag6 = mcl->hops;
- socketfd = xdmcpSocket6;
- setsockopt(socketfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
- &hopflag6, sizeof(hopflag6));
- } else {
- continue;
- }
- XdmcpFlush (socketfd, &buffer,
- (XdmcpNetaddr) ai->ai_addr, ai->ai_addrlen);
- break;
- }
- }
- }
-#endif
- else
- {
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(ManagerAddress) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &ManagerAddress,
- ManagerAddressLen);
- }
-}
-
-static void
-recv_willing_msg(
- struct sockaddr *from,
- int fromlen,
- unsigned length)
-{
- ARRAY8 authenticationName;
- ARRAY8 hostname;
- ARRAY8 status;
-
- authenticationName.data = 0;
- hostname.data = 0;
- status.data = 0;
- if (XdmcpReadARRAY8 (&buffer, &authenticationName) &&
- XdmcpReadARRAY8 (&buffer, &hostname) &&
- XdmcpReadARRAY8 (&buffer, &status))
- {
- if (length == 6 + authenticationName.length +
- hostname.length + status.length)
- {
- switch (state)
- {
- case XDM_COLLECT_QUERY:
- XdmcpSelectHost(from, fromlen, &authenticationName);
- break;
- case XDM_COLLECT_BROADCAST_QUERY:
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_COLLECT_MULTICAST_QUERY:
-#endif
- case XDM_COLLECT_INDIRECT_QUERY:
- XdmcpAddHost(from, fromlen, &authenticationName, &hostname, &status);
- break;
- default:
- break;
- }
- }
- }
- XdmcpDisposeARRAY8 (&authenticationName);
- XdmcpDisposeARRAY8 (&hostname);
- XdmcpDisposeARRAY8 (&status);
-}
-
-static void
-send_request_msg(void)
-{
- XdmcpHeader header;
- int length;
- int i;
- CARD16 XdmcpConnectionType;
- ARRAY8 authenticationData;
- int socketfd = xdmcpSocket;
-
- switch (SOCKADDR_FAMILY(ManagerAddress))
- {
- case AF_INET: XdmcpConnectionType=FamilyInternet; break;
-#if defined(IPv6) && defined(AF_INET6)
- case AF_INET6: XdmcpConnectionType=FamilyInternet6; break;
-#endif
- default: XdmcpConnectionType=0xffff; break;
- }
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) REQUEST;
-
- length = 2; /* display number */
- length += 1 + 2 * ConnectionTypes.length; /* connection types */
- length += 1; /* connection addresses */
- for (i = 0; i < ConnectionAddresses.length; i++)
- length += 2 + ConnectionAddresses.data[i].length;
- authenticationData.length = 0;
- authenticationData.data = 0;
- if (AuthenticationFuncs)
- {
- (*AuthenticationFuncs->Generator) (AuthenticationData,
- &authenticationData,
- REQUEST);
- }
- length += 2 + AuthenticationName->length; /* authentication name */
- length += 2 + authenticationData.length; /* authentication data */
- length += 1; /* authorization names */
- for (i = 0; i < AuthorizationNames.length; i++)
- length += 2 + AuthorizationNames.data[i].length;
- length += 2 + ManufacturerDisplayID.length; /* display ID */
- header.length = length;
-
- if (!XdmcpWriteHeader (&buffer, &header))
- {
- XdmcpDisposeARRAY8 (&authenticationData);
- return;
- }
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteCARD8 (&buffer, ConnectionTypes.length);
-
- /* The connection array is send reordered, so that connections of */
- /* the same address type as the XDMCP manager connection are send */
- /* first. This works around a bug in xdm. mario@klebsch.de */
- for (i = 0; i < (int)ConnectionTypes.length; i++)
- if (ConnectionTypes.data[i]==XdmcpConnectionType)
- XdmcpWriteCARD16 (&buffer, ConnectionTypes.data[i]);
- for (i = 0; i < (int)ConnectionTypes.length; i++)
- if (ConnectionTypes.data[i]!=XdmcpConnectionType)
- XdmcpWriteCARD16 (&buffer, ConnectionTypes.data[i]);
-
- XdmcpWriteCARD8 (&buffer, ConnectionAddresses.length);
- for (i = 0; i < (int)ConnectionAddresses.length; i++)
- if ( (i<ConnectionTypes.length) &&
- (ConnectionTypes.data[i]==XdmcpConnectionType) )
- XdmcpWriteARRAY8 (&buffer, &ConnectionAddresses.data[i]);
- for (i = 0; i < (int)ConnectionAddresses.length; i++)
- if ( (i>=ConnectionTypes.length) ||
- (ConnectionTypes.data[i]!=XdmcpConnectionType) )
- XdmcpWriteARRAY8 (&buffer, &ConnectionAddresses.data[i]);
-
- XdmcpWriteARRAY8 (&buffer, AuthenticationName);
- XdmcpWriteARRAY8 (&buffer, &authenticationData);
- XdmcpDisposeARRAY8 (&authenticationData);
- XdmcpWriteARRAYofARRAY8 (&buffer, &AuthorizationNames);
- XdmcpWriteARRAY8 (&buffer, &ManufacturerDisplayID);
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- if (XdmcpFlush (socketfd, &buffer,
- (XdmcpNetaddr) &req_sockaddr, req_socklen))
- state = XDM_AWAIT_REQUEST_RESPONSE;
-}
-
-static void
-recv_accept_msg(unsigned length)
-{
- CARD32 AcceptSessionID;
- ARRAY8 AcceptAuthenticationName, AcceptAuthenticationData;
- ARRAY8 AcceptAuthorizationName, AcceptAuthorizationData;
-
- if (state != XDM_AWAIT_REQUEST_RESPONSE)
- return;
- AcceptAuthenticationName.data = 0;
- AcceptAuthenticationData.data = 0;
- AcceptAuthorizationName.data = 0;
- AcceptAuthorizationData.data = 0;
- if (XdmcpReadCARD32 (&buffer, &AcceptSessionID) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthenticationName) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthenticationData) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthorizationName) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthorizationData))
- {
- if (length == 12 + AcceptAuthenticationName.length +
- AcceptAuthenticationData.length +
- AcceptAuthorizationName.length +
- AcceptAuthorizationData.length)
- {
- if (!XdmcpCheckAuthentication (&AcceptAuthenticationName,
- &AcceptAuthenticationData, ACCEPT))
- {
- XdmcpFatal ("Authentication Failure", &AcceptAuthenticationName);
- }
- /* permit access control manipulations from this host */
- AugmentSelf (&req_sockaddr, req_socklen);
- /* if the authorization specified in the packet fails
- * to be acceptable, enable the local addresses
- */
- if (!XdmcpAddAuthorization (&AcceptAuthorizationName,
- &AcceptAuthorizationData))
- {
- AddLocalHosts ();
- }
- SessionID = AcceptSessionID;
- state = XDM_MANAGE;
- send_packet();
- }
- }
- XdmcpDisposeARRAY8 (&AcceptAuthenticationName);
- XdmcpDisposeARRAY8 (&AcceptAuthenticationData);
- XdmcpDisposeARRAY8 (&AcceptAuthorizationName);
- XdmcpDisposeARRAY8 (&AcceptAuthorizationData);
-}
-
-static void
-recv_decline_msg(unsigned length)
-{
- ARRAY8 status, DeclineAuthenticationName, DeclineAuthenticationData;
-
- status.data = 0;
- DeclineAuthenticationName.data = 0;
- DeclineAuthenticationData.data = 0;
- if (XdmcpReadARRAY8 (&buffer, &status) &&
- XdmcpReadARRAY8 (&buffer, &DeclineAuthenticationName) &&
- XdmcpReadARRAY8 (&buffer, &DeclineAuthenticationData))
- {
- if (length == 6 + status.length +
- DeclineAuthenticationName.length +
- DeclineAuthenticationData.length &&
- XdmcpCheckAuthentication (&DeclineAuthenticationName,
- &DeclineAuthenticationData, DECLINE))
- {
- XdmcpFatal ("Session declined", &status);
- }
- }
- XdmcpDisposeARRAY8 (&status);
- XdmcpDisposeARRAY8 (&DeclineAuthenticationName);
- XdmcpDisposeARRAY8 (&DeclineAuthenticationData);
-}
-
-static void
-send_manage_msg(void)
-{
- XdmcpHeader header;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) MANAGE;
- header.length = 8 + DisplayClass.length;
-
- if (!XdmcpWriteHeader (&buffer, &header))
- return;
- XdmcpWriteCARD32 (&buffer, SessionID);
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteARRAY8 (&buffer, &DisplayClass);
- state = XDM_AWAIT_MANAGE_RESPONSE;
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen);
-}
-
-static void
-recv_refuse_msg(unsigned length)
-{
- CARD32 RefusedSessionID;
-
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- if (length != 4)
- return;
- if (XdmcpReadCARD32 (&buffer, &RefusedSessionID))
- {
- if (RefusedSessionID == SessionID)
- {
- state = XDM_START_CONNECTION;
- send_packet();
- }
- }
-}
-
-static void
-recv_failed_msg(unsigned length)
-{
- CARD32 FailedSessionID;
- ARRAY8 status;
-
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- status.data = 0;
- if (XdmcpReadCARD32 (&buffer, &FailedSessionID) &&
- XdmcpReadARRAY8 (&buffer, &status))
- {
- if (length == 6 + status.length &&
- SessionID == FailedSessionID)
- {
- XdmcpFatal ("Session failed", &status);
- }
- }
- XdmcpDisposeARRAY8 (&status);
-}
-
-static void
-send_keepalive_msg(void)
-{
- XdmcpHeader header;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) KEEPALIVE;
- header.length = 6;
-
- XdmcpWriteHeader (&buffer, &header);
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteCARD32 (&buffer, SessionID);
-
- state = XDM_AWAIT_ALIVE_RESPONSE;
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen);
-}
-
-static void
-recv_alive_msg (unsigned length)
-{
- CARD8 SessionRunning;
- CARD32 AliveSessionID;
-
- if (state != XDM_AWAIT_ALIVE_RESPONSE)
- return;
- if (length != 5)
- return;
- if (XdmcpReadCARD8 (&buffer, &SessionRunning) &&
- XdmcpReadCARD32 (&buffer, &AliveSessionID))
- {
- if (SessionRunning && AliveSessionID == SessionID)
- {
- /* backoff dormancy period */
- state = XDM_RUN_SESSION;
- if ((GetTimeInMillis() - lastDeviceEventTime.milliseconds) >
- keepaliveDormancy * 1000)
- {
- keepaliveDormancy <<= 1;
- if (keepaliveDormancy > XDM_MAX_DORMANCY)
- keepaliveDormancy = XDM_MAX_DORMANCY;
- }
- timeOutTime = GetTimeInMillis() + keepaliveDormancy * 1000;
- }
- else
- {
- XdmcpDeadSession ("Alive response indicates session dead");
- }
- }
-}
-
-static void
-XdmcpFatal (
- char *type,
- ARRAY8Ptr status)
-{
- FatalError ("XDMCP fatal error: %s %*.*s\n", type,
- status->length, status->length, status->data);
-}
-
-static void
-XdmcpWarning(char *str)
-{
- ErrorF("XDMCP warning: %s\n", str);
-}
-
-static void
-get_addr_by_name(
- char * argtype,
- char * namestr,
- int port,
- int socktype,
- SOCKADDR_TYPE *addr,
- SOCKLEN_TYPE *addrlen
-#if defined(IPv6) && defined(AF_INET6)
- ,
- struct addrinfo **aip,
- struct addrinfo **aifirstp
-#endif
- )
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo *ai;
- struct addrinfo hints;
- char portstr[6];
- char *pport = portstr;
- int gaierr;
-
- bzero(&hints, sizeof(hints));
- hints.ai_socktype = socktype;
-
- if (port == 0) {
- pport = NULL;
- } else if (port > 0 && port < 65535) {
- sprintf(portstr, "%d", port);
- } else {
- FatalError("Xserver: port out of range: %d\n", port);
- }
-
- if (*aifirstp != NULL) {
- freeaddrinfo(*aifirstp);
- *aifirstp = NULL;
- }
-
- if ((gaierr = getaddrinfo(namestr, pport, &hints, aifirstp)) == 0) {
- for (ai = *aifirstp; ai != NULL; ai = ai->ai_next) {
- if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)
- break;
- }
- if ((ai == NULL) || (ai->ai_addrlen > sizeof(SOCKADDR_TYPE))) {
- FatalError ("Xserver: %s host %s not on supported network type\n",
- argtype, namestr);
- } else {
- *aip = ai;
- *addrlen = ai->ai_addrlen;
- memcpy(addr, ai->ai_addr, ai->ai_addrlen);
- }
- } else {
- FatalError("Xserver: %s: %s %s\n", gai_strerror(gaierr), argtype, namestr);
- }
-#else
- struct hostent *hep;
-#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
- _Xgethostbynameparams hparams;
-#endif
-#if defined(WIN32) && (defined(TCPCONN) || defined(DNETCONN))
- _XSERVTransWSAStartup();
-#endif
- if (!(hep = _XGethostbyname(namestr, hparams)))
- {
- FatalError("Xserver: %s unknown host: %s\n", argtype, namestr);
- }
- if (hep->h_length == sizeof (struct in_addr))
- {
- memmove(&addr->sin_addr, hep->h_addr, hep->h_length);
- *addrlen = sizeof(struct sockaddr_in);
- addr->sin_family = AF_INET;
- addr->sin_port = htons (port);
- }
- else
- {
- FatalError("Xserver: %s host on strange network %s\n", argtype, namestr);
- }
-#endif
-}
-
-static void
-get_manager_by_name(
- int argc,
- char **argv,
- int i)
-{
-
- if ((i + 1) == argc)
- {
- FatalError("Xserver: missing %s host name in command line\n", argv[i]);
- }
-
- get_addr_by_name(argv[i], argv[i+1], xdm_udp_port, SOCK_DGRAM,
- &ManagerAddress, &ManagerAddressLen
-#if defined(IPv6) && defined(AF_INET6)
- , &mgrAddr, &mgrAddrFirst
-#endif
- );
-}
-
-
-static void
-get_fromaddr_by_name(
- int argc,
- char **argv,
- int i)
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo *ai = NULL;
- struct addrinfo *aifirst = NULL;
-#endif
- if (i == argc)
- {
- FatalError("Xserver: missing -from host name in command line\n");
- }
- get_addr_by_name("-from", argv[i], 0, 0, &FromAddress, &FromAddressLen
-#if defined(IPv6) && defined(AF_INET6)
- , &ai, &aifirst
-#endif
- );
- xdm_from = argv[i];
-}
-
-
-#if defined(IPv6) && defined(AF_INET6)
-static int
-get_mcast_options(argc, argv, i)
- int argc, i;
- char **argv;
-{
- char *address = XDM_DEFAULT_MCAST_ADDR6;
- int hopcount = 1;
- struct addrinfo hints;
- char portstr[6];
- int gaierr;
- struct addrinfo *ai, *firstai;
-
- if ((i < argc) && (argv[i][0] != '-') && (argv[i][0] != '+')) {
- address = argv[i++];
- if ((i < argc) && (argv[i][0] != '-') && (argv[i][0] != '+')) {
- hopcount = strtol(argv[i++], NULL, 10);
- if ((hopcount < 1) || (hopcount > 255)) {
- FatalError("Xserver: multicast hop count out of range: %d\n",
- hopcount);
- }
- }
- }
-
- if (xdm_udp_port > 0 && xdm_udp_port < 65535) {
- sprintf(portstr, "%d", xdm_udp_port);
- } else {
- FatalError("Xserver: port out of range: %d\n", xdm_udp_port);
- }
- bzero(&hints, sizeof(hints));
- hints.ai_socktype = SOCK_DGRAM;
-
- if ((gaierr = getaddrinfo(address, portstr, &hints, &firstai)) == 0) {
- for (ai = firstai; ai != NULL; ai = ai->ai_next) {
- if (((ai->ai_family == AF_INET) &&
- IN_MULTICAST(((struct sockaddr_in *) ai->ai_addr)
- ->sin_addr.s_addr))
- || ((ai->ai_family == AF_INET6) &&
- IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *) ai->ai_addr)
- ->sin6_addr)))
- break;
- }
- if (ai == NULL) {
- FatalError ("Xserver: address not supported multicast type %s\n",
- address);
- } else {
- struct multicastinfo *mcastinfo, *mcl;
-
- mcastinfo = malloc(sizeof(struct multicastinfo));
- mcastinfo->next = NULL;
- mcastinfo->ai = firstai;
- mcastinfo->hops = hopcount;
-
- if (mcastlist == NULL) {
- mcastlist = mcastinfo;
- } else {
- for (mcl = mcastlist; mcl->next != NULL; mcl = mcl->next) {
- /* Do nothing - just find end of list */
- }
- mcl->next = mcastinfo;
- }
- }
- } else {
- FatalError("Xserver: %s: %s\n", gai_strerror(gaierr), address);
- }
- return i;
-}
-#endif
-
-#else
-static int xdmcp_non_empty; /* avoid complaint by ranlib */
-#endif /* XDMCP */
diff --git a/nx-X11/programs/Xserver/os/xdmcp.c.X.original b/nx-X11/programs/Xserver/os/xdmcp.c.X.original
deleted file mode 100644
index 19a62a56b..000000000
--- a/nx-X11/programs/Xserver/os/xdmcp.c.X.original
+++ /dev/null
@@ -1,1681 +0,0 @@
-/* $XdotOrg: xc/programs/Xserver/os/xdmcp.c,v 1.10 2005/07/03 08:53:52 daniels Exp $ */
-/* $Xorg: xdmcp.c,v 1.4 2001/01/31 13:37:19 pookie Exp $ */
-/*
- * Copyright 1989 Network Computing Devices, Inc., Mountain View, California.
- *
- * 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 N.C.D. not be used in advertising or
- * publicity pertaining to distribution of the software without specific,
- * written prior permission. N.C.D. makes no representations about the
- * suitability of this software for any purpose. It is provided "as is"
- * without express or implied warranty.
- *
- */
-/* $XFree86: xc/programs/Xserver/os/xdmcp.c,v 3.31 2003/12/30 21:24:32 herrb Exp $ */
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#ifdef WIN32
-#include <X11/Xwinsock.h>
-#endif
-
-#include <X11/Xos.h>
-
-#if !defined(WIN32)
-#ifndef Lynx
-#include <sys/param.h>
-#include <sys/socket.h>
-#else
-#include <socket.h>
-#endif
-#include <netinet/in.h>
-#include <netdb.h>
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "misc.h"
-#include <X11/Xpoll.h>
-#include "osdep.h"
-#include "input.h"
-#include "dixstruct.h"
-#include "opaque.h"
-
-#if defined(DGUX)
-#include <net/net_ioctl.h>
-#include <sys/ioctl.h>
-#endif
-
-#ifdef STREAMSCONN
-#include <tiuser.h>
-#include <netconfig.h>
-#include <netdir.h>
-#endif
-
-#ifdef XDMCP
-#undef REQUEST
-
-#ifdef XDMCP_NO_IPV6
-#undef IPv6
-#endif
-
-#include <X11/Xdmcp.h>
-
-#define X_INCLUDE_NETDB_H
-#include <X11/Xos_r.h>
-
-extern char *defaultDisplayClass;
-
-static int xdmcpSocket, sessionSocket;
-static xdmcp_states state;
-#if defined(IPv6) && defined(AF_INET6)
-static int xdmcpSocket6;
-static struct sockaddr_storage req_sockaddr;
-#else
-static struct sockaddr_in req_sockaddr;
-#endif
-static int req_socklen;
-static CARD32 SessionID;
-static CARD32 timeOutTime;
-static int timeOutRtx;
-static CARD32 defaultKeepaliveDormancy = XDM_DEF_DORMANCY;
-static CARD32 keepaliveDormancy = XDM_DEF_DORMANCY;
-static CARD16 DisplayNumber;
-static xdmcp_states XDM_INIT_STATE = XDM_OFF;
-#ifdef HASXDMAUTH
-static char *xdmAuthCookie;
-#endif
-
-static XdmcpBuffer buffer;
-
-#if defined(IPv6) && defined(AF_INET6)
-
-static struct addrinfo *mgrAddr;
-static struct addrinfo *mgrAddrFirst;
-
-#define SOCKADDR_TYPE struct sockaddr_storage
-#define SOCKADDR_FAMILY(s) ((struct sockaddr *)&(s))->sa_family
-
-#ifdef BSD44SOCKETS
-#define SOCKLEN_FIELD(s) ((struct sockaddr *)&(s))->sa_len
-#define SOCKLEN_TYPE unsigned char
-#else
-#define SOCKLEN_TYPE unsigned int
-#endif
-
-#else
-
-#define SOCKADDR_TYPE struct sockaddr_in
-#define SOCKADDR_FAMILY(s) (s).sin_family
-
-#ifdef BSD44SOCKETS
-#define SOCKLEN_FIELD(s) (s).sin_len
-#define SOCKLEN_TYPE unsigned char
-#else
-#define SOCKLEN_TYPE size_t
-#endif
-
-#endif
-
-static SOCKADDR_TYPE ManagerAddress;
-static SOCKADDR_TYPE FromAddress;
-
-#ifdef SOCKLEN_FIELD
-#define ManagerAddressLen SOCKLEN_FIELD(ManagerAddress)
-#define FromAddressLen SOCKLEN_FIELD(FromAddress)
-#else
-static SOCKLEN_TYPE ManagerAddressLen, FromAddressLen;
-#endif
-
-#if defined(IPv6) && defined(AF_INET6)
-static struct multicastinfo {
- struct multicastinfo *next;
- struct addrinfo *ai;
- int hops;
-} *mcastlist;
-#endif
-
-static void XdmcpAddHost(
- struct sockaddr *from,
- int fromlen,
- ARRAY8Ptr AuthenticationName,
- ARRAY8Ptr hostname,
- ARRAY8Ptr status);
-
-static void XdmcpSelectHost(
- struct sockaddr *host_sockaddr,
- int host_len,
- ARRAY8Ptr AuthenticationName);
-
-static void get_xdmcp_sock(void);
-
-static void send_query_msg(void);
-
-static void recv_willing_msg(
- struct sockaddr * /*from*/,
- int /*fromlen*/,
- unsigned /*length*/);
-
-static void send_request_msg(void);
-
-static void recv_accept_msg(unsigned /*length*/);
-
-static void recv_decline_msg(unsigned /*length*/);
-
-static void send_manage_msg(void);
-
-static void recv_refuse_msg(unsigned /*length*/);
-
-static void recv_failed_msg(unsigned /*length*/);
-
-static void send_keepalive_msg(void);
-
-static void recv_alive_msg(unsigned /*length*/);
-
-static void XdmcpFatal(
- char * /*type*/,
- ARRAY8Ptr /*status*/);
-
-static void XdmcpWarning(char * /*str*/);
-
-static void get_manager_by_name(
- int /*argc*/,
- char ** /*argv*/,
- int /*i*/);
-
-static void get_fromaddr_by_name(int /*argc*/, char ** /*argv*/, int /*i*/);
-
-#if defined(IPv6) && defined(AF_INET6)
-static int get_mcast_options(int /*argc*/, char ** /*argv*/, int /*i*/);
-#endif
-
-static void receive_packet(int /*socketfd*/);
-
-static void send_packet(void);
-
-extern void XdmcpDeadSession(char * /*reason*/);
-
-static void timeout(void);
-
-static void restart(void);
-
-static void XdmcpBlockHandler(
- pointer /*data*/,
- struct timeval ** /*wt*/,
- pointer /*LastSelectMask*/);
-
-static void XdmcpWakeupHandler(
- pointer /*data*/,
- int /*i*/,
- pointer /*LastSelectMask*/);
-
-void XdmcpRegisterManufacturerDisplayID(
- char * /*name*/,
- int /*length*/);
-
-
-static unsigned short xdm_udp_port = XDM_UDP_PORT;
-static Bool OneSession = FALSE;
-static const char *xdm_from = NULL;
-
-void
-XdmcpUseMsg (void)
-{
- ErrorF("-query host-name contact named host for XDMCP\n");
- ErrorF("-broadcast broadcast for XDMCP\n");
-#if defined(IPv6) && defined(AF_INET6)
- ErrorF("-multicast [addr [hops]] IPv6 multicast for XDMCP\n");
-#endif
- ErrorF("-indirect host-name contact named host for indirect XDMCP\n");
- ErrorF("-port port-num UDP port number to send messages to\n");
- ErrorF("-from local-address specify the local address to connect from\n");
- ErrorF("-once Terminate server after one session\n");
- ErrorF("-class display-class specify display class to send in manage\n");
-#ifdef HASXDMAUTH
- ErrorF("-cookie xdm-auth-bits specify the magic cookie for XDMCP\n");
-#endif
- ErrorF("-displayID display-id manufacturer display ID for request\n");
-}
-
-int
-XdmcpOptions(int argc, char **argv, int i)
-{
- if (strcmp(argv[i], "-query") == 0) {
- get_manager_by_name(argc, argv, i++);
- XDM_INIT_STATE = XDM_QUERY;
- AccessUsingXdmcp ();
- return (i + 1);
- }
- if (strcmp(argv[i], "-broadcast") == 0) {
- XDM_INIT_STATE = XDM_BROADCAST;
- AccessUsingXdmcp ();
- return (i + 1);
- }
-#if defined(IPv6) && defined(AF_INET6)
- if (strcmp(argv[i], "-multicast") == 0) {
- i = get_mcast_options(argc, argv, ++i);
- XDM_INIT_STATE = XDM_MULTICAST;
- AccessUsingXdmcp ();
- return (i + 1);
- }
-#endif
- if (strcmp(argv[i], "-indirect") == 0) {
- get_manager_by_name(argc, argv, i++);
- XDM_INIT_STATE = XDM_INDIRECT;
- AccessUsingXdmcp ();
- return (i + 1);
- }
- if (strcmp(argv[i], "-port") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing port number in command line\n");
- }
- xdm_udp_port = (unsigned short) atoi(argv[i]);
- return (i + 1);
- }
- if (strcmp(argv[i], "-from") == 0) {
- get_fromaddr_by_name(argc, argv, ++i);
- return (i + 1);
- }
- if (strcmp(argv[i], "-once") == 0) {
- OneSession = TRUE;
- return (i + 1);
- }
- if (strcmp(argv[i], "-class") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing class name in command line\n");
- }
- defaultDisplayClass = argv[i];
- return (i + 1);
- }
-#ifdef HASXDMAUTH
- if (strcmp(argv[i], "-cookie") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing cookie data in command line\n");
- }
- xdmAuthCookie = argv[i];
- return (i + 1);
- }
-#endif
- if (strcmp(argv[i], "-displayID") == 0) {
- if (++i == argc) {
- FatalError("Xserver: missing displayID in command line\n");
- }
- XdmcpRegisterManufacturerDisplayID (argv[i], strlen (argv[i]));
- return (i + 1);
- }
- return (i);
-}
-
-/*
- * This section is a collection of routines for
- * registering server-specific data with the XDMCP
- * state machine.
- */
-
-
-/*
- * Save all broadcast addresses away so BroadcastQuery
- * packets get sent everywhere
- */
-
-#define MAX_BROADCAST 10
-
-/* This stays sockaddr_in since IPv6 doesn't support broadcast */
-static struct sockaddr_in BroadcastAddresses[MAX_BROADCAST];
-static int NumBroadcastAddresses;
-
-void
-XdmcpRegisterBroadcastAddress (struct sockaddr_in *addr)
-{
- struct sockaddr_in *bcast;
- if (NumBroadcastAddresses >= MAX_BROADCAST)
- return;
- bcast = &BroadcastAddresses[NumBroadcastAddresses++];
- bzero (bcast, sizeof (struct sockaddr_in));
-#ifdef BSD44SOCKETS
- bcast->sin_len = addr->sin_len;
-#endif
- bcast->sin_family = addr->sin_family;
- bcast->sin_port = htons (xdm_udp_port);
- bcast->sin_addr = addr->sin_addr;
-}
-
-/*
- * Each authentication type is registered here; Validator
- * will be called to check all access attempts using
- * the specified authentication type
- */
-
-static ARRAYofARRAY8 AuthenticationNames, AuthenticationDatas;
-typedef struct _AuthenticationFuncs {
- ValidatorFunc Validator;
- GeneratorFunc Generator;
- AddAuthorFunc AddAuth;
-} AuthenticationFuncsRec, *AuthenticationFuncsPtr;
-
-static AuthenticationFuncsPtr AuthenticationFuncsList;
-
-void
-XdmcpRegisterAuthentication (
- char *name,
- int namelen,
- char *data,
- int datalen,
- ValidatorFunc Validator,
- GeneratorFunc Generator,
- AddAuthorFunc AddAuth)
-{
- int i;
- ARRAY8 AuthenticationName, AuthenticationData;
- static AuthenticationFuncsPtr newFuncs;
-
- if (!XdmcpAllocARRAY8 (&AuthenticationName, namelen))
- return;
- if (!XdmcpAllocARRAY8 (&AuthenticationData, datalen))
- {
- XdmcpDisposeARRAY8 (&AuthenticationName);
- return;
- }
- for (i = 0; i < namelen; i++)
- AuthenticationName.data[i] = name[i];
- for (i = 0; i < datalen; i++)
- AuthenticationData.data[i] = data[i];
- if (!(XdmcpReallocARRAYofARRAY8 (&AuthenticationNames,
- AuthenticationNames.length + 1) &&
- XdmcpReallocARRAYofARRAY8 (&AuthenticationDatas,
- AuthenticationDatas.length + 1) &&
- (newFuncs = (AuthenticationFuncsPtr) xalloc (
- (AuthenticationNames.length + 1) * sizeof (AuthenticationFuncsRec)))))
- {
- XdmcpDisposeARRAY8 (&AuthenticationName);
- XdmcpDisposeARRAY8 (&AuthenticationData);
- return;
- }
- for (i = 0; i < AuthenticationNames.length - 1; i++)
- newFuncs[i] = AuthenticationFuncsList[i];
- newFuncs[AuthenticationNames.length-1].Validator = Validator;
- newFuncs[AuthenticationNames.length-1].Generator = Generator;
- newFuncs[AuthenticationNames.length-1].AddAuth = AddAuth;
- xfree (AuthenticationFuncsList);
- AuthenticationFuncsList = newFuncs;
- AuthenticationNames.data[AuthenticationNames.length-1] = AuthenticationName;
- AuthenticationDatas.data[AuthenticationDatas.length-1] = AuthenticationData;
-}
-
-/*
- * Select the authentication type to be used; this is
- * set by the manager of the host to be connected to.
- */
-
-ARRAY8 noAuthenticationName = {(CARD16) 0, (CARD8Ptr) 0};
-ARRAY8 noAuthenticationData = {(CARD16) 0, (CARD8Ptr) 0};
-ARRAY8Ptr AuthenticationName = &noAuthenticationName;
-ARRAY8Ptr AuthenticationData = &noAuthenticationData;
-AuthenticationFuncsPtr AuthenticationFuncs;
-
-void
-XdmcpSetAuthentication (ARRAY8Ptr name)
-{
- int i;
-
- for (i = 0; i < AuthenticationNames.length; i++)
- if (XdmcpARRAY8Equal (&AuthenticationNames.data[i], name))
- {
- AuthenticationName = &AuthenticationNames.data[i];
- AuthenticationData = &AuthenticationDatas.data[i];
- AuthenticationFuncs = &AuthenticationFuncsList[i];
- break;
- }
-}
-
-/*
- * Register the host address for the display
- */
-
-static ARRAY16 ConnectionTypes;
-static ARRAYofARRAY8 ConnectionAddresses;
-static long xdmcpGeneration;
-
-void
-XdmcpRegisterConnection (
- int type,
- char *address,
- int addrlen)
-{
- int i;
- CARD8 *newAddress;
-
- if (xdmcpGeneration != serverGeneration)
- {
- XdmcpDisposeARRAY16 (&ConnectionTypes);
- XdmcpDisposeARRAYofARRAY8 (&ConnectionAddresses);
- xdmcpGeneration = serverGeneration;
- }
- if (xdm_from != NULL) { /* Only register the requested address */
- const void *regAddr = address;
- const void *fromAddr = NULL;
- int regAddrlen = addrlen;
-
- if (addrlen == sizeof(struct in_addr)) {
- if (SOCKADDR_FAMILY(FromAddress) == AF_INET) {
- fromAddr = &((struct sockaddr_in *)&FromAddress)->sin_addr;
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if ((SOCKADDR_FAMILY(FromAddress) == AF_INET6) &&
- IN6_IS_ADDR_V4MAPPED(
- &((struct sockaddr_in6 *)&FromAddress)->sin6_addr)) {
- fromAddr = &((struct sockaddr_in6 *)&FromAddress)->sin6_addr.s6_addr[12];
- }
-#endif
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if (addrlen == sizeof(struct in6_addr)) {
- if (SOCKADDR_FAMILY(FromAddress) == AF_INET6) {
- fromAddr = &((struct sockaddr_in6 *)&FromAddress)->sin6_addr;
- } else if ((SOCKADDR_FAMILY(FromAddress) == AF_INET) &&
- IN6_IS_ADDR_V4MAPPED((struct in6_addr *) address)) {
- fromAddr = &((struct sockaddr_in *)&FromAddress)->sin_addr;
- regAddr = &((struct sockaddr_in6 *)&address)->sin6_addr.s6_addr[12];
- regAddrlen = sizeof(struct in_addr);
- }
- }
-#endif
- if (fromAddr && memcmp(regAddr, fromAddr, regAddrlen) != 0) {
- return;
- }
- }
- newAddress = (CARD8 *) xalloc (addrlen * sizeof (CARD8));
- if (!newAddress)
- return;
- if (!XdmcpReallocARRAY16 (&ConnectionTypes, ConnectionTypes.length + 1))
- {
- xfree (newAddress);
- return;
- }
- if (!XdmcpReallocARRAYofARRAY8 (&ConnectionAddresses,
- ConnectionAddresses.length + 1))
- {
- xfree (newAddress);
- return;
- }
- ConnectionTypes.data[ConnectionTypes.length - 1] = (CARD16) type;
- for (i = 0; i < addrlen; i++)
- newAddress[i] = address[i];
- ConnectionAddresses.data[ConnectionAddresses.length-1].data = newAddress;
- ConnectionAddresses.data[ConnectionAddresses.length-1].length = addrlen;
-}
-
-/*
- * Register an Authorization Name. XDMCP advertises this list
- * to the manager.
- */
-
-static ARRAYofARRAY8 AuthorizationNames;
-
-void
-XdmcpRegisterAuthorizations (void)
-{
- XdmcpDisposeARRAYofARRAY8 (&AuthorizationNames);
- RegisterAuthorizations ();
-}
-
-void
-XdmcpRegisterAuthorization (char *name, int namelen)
-{
- ARRAY8 authName;
- int i;
-
- authName.data = (CARD8 *) xalloc (namelen * sizeof (CARD8));
- if (!authName.data)
- return;
- if (!XdmcpReallocARRAYofARRAY8 (&AuthorizationNames, AuthorizationNames.length +1))
- {
- xfree (authName.data);
- return;
- }
- for (i = 0; i < namelen; i++)
- authName.data[i] = (CARD8) name[i];
- authName.length = namelen;
- AuthorizationNames.data[AuthorizationNames.length-1] = authName;
-}
-
-/*
- * Register the DisplayClass string
- */
-
-ARRAY8 DisplayClass;
-
-void
-XdmcpRegisterDisplayClass (char *name, int length)
-{
- int i;
-
- XdmcpDisposeARRAY8 (&DisplayClass);
- if (!XdmcpAllocARRAY8 (&DisplayClass, length))
- return;
- for (i = 0; i < length; i++)
- DisplayClass.data[i] = (CARD8) name[i];
-}
-
-/*
- * Register the Manufacturer display ID
- */
-
-ARRAY8 ManufacturerDisplayID;
-
-void
-XdmcpRegisterManufacturerDisplayID (char *name, int length)
-{
- int i;
-
- XdmcpDisposeARRAY8 (&ManufacturerDisplayID);
- if (!XdmcpAllocARRAY8 (&ManufacturerDisplayID, length))
- return;
- for (i = 0; i < length; i++)
- ManufacturerDisplayID.data[i] = (CARD8) name[i];
-}
-
-/*
- * initialize XDMCP; create the socket, compute the display
- * number, set up the state machine
- */
-
-void
-XdmcpInit(void)
-{
- state = XDM_INIT_STATE;
-#ifdef HASXDMAUTH
- if (xdmAuthCookie)
- XdmAuthenticationInit (xdmAuthCookie, strlen (xdmAuthCookie));
-#endif
- if (state != XDM_OFF)
- {
- XdmcpRegisterAuthorizations();
- XdmcpRegisterDisplayClass (defaultDisplayClass, strlen (defaultDisplayClass));
- AccessUsingXdmcp();
- RegisterBlockAndWakeupHandlers (XdmcpBlockHandler, XdmcpWakeupHandler,
- (pointer) 0);
- timeOutRtx = 0;
- DisplayNumber = (CARD16) atoi(display);
- get_xdmcp_sock();
- send_packet();
- }
-}
-
-void
-XdmcpReset (void)
-{
- state = XDM_INIT_STATE;
- if (state != XDM_OFF)
- {
- RegisterBlockAndWakeupHandlers (XdmcpBlockHandler, XdmcpWakeupHandler,
- (pointer) 0);
- timeOutRtx = 0;
- send_packet();
- }
-}
-
-/*
- * Called whenever a new connection is created; notices the
- * first connection and saves it to terminate the session
- * when it is closed
- */
-
-void
-XdmcpOpenDisplay(int sock)
-{
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- state = XDM_RUN_SESSION;
- sessionSocket = sock;
-}
-
-void
-XdmcpCloseDisplay(int sock)
-{
- if ((state != XDM_RUN_SESSION && state != XDM_AWAIT_ALIVE_RESPONSE)
- || sessionSocket != sock)
- return;
- state = XDM_INIT_STATE;
- if (OneSession)
- dispatchException |= DE_TERMINATE;
- else
- dispatchException |= DE_RESET;
- isItTimeToYield = TRUE;
-}
-
-/*
- * called before going to sleep, this routine
- * may modify the timeout value about to be sent
- * to select; in this way XDMCP can do appropriate things
- * dynamically while starting up
- */
-
-/*ARGSUSED*/
-static void
-XdmcpBlockHandler(
- pointer data, /* unused */
- struct timeval **wt,
- pointer pReadmask)
-{
- fd_set *LastSelectMask = (fd_set*)pReadmask;
- CARD32 millisToGo;
-
- if (state == XDM_OFF)
- return;
- FD_SET(xdmcpSocket, LastSelectMask);
-#if defined(IPv6) && defined(AF_INET6)
- if (xdmcpSocket6 >= 0)
- FD_SET(xdmcpSocket6, LastSelectMask);
-#endif
- if (timeOutTime == 0)
- return;
- millisToGo = timeOutTime - GetTimeInMillis();
- if ((int) millisToGo < 0)
- millisToGo = 0;
- AdjustWaitForDelay (wt, millisToGo);
-}
-
-/*
- * called after select returns; this routine will
- * recognise when XDMCP packets await and
- * process them appropriately
- */
-
-/*ARGSUSED*/
-static void
-XdmcpWakeupHandler(
- pointer data, /* unused */
- int i,
- pointer pReadmask)
-{
- fd_set* LastSelectMask = (fd_set*)pReadmask;
- fd_set devicesReadable;
-
- if (state == XDM_OFF)
- return;
- if (i > 0)
- {
- if (FD_ISSET(xdmcpSocket, LastSelectMask))
- {
- receive_packet(xdmcpSocket);
- FD_CLR(xdmcpSocket, LastSelectMask);
- }
-#if defined(IPv6) && defined(AF_INET6)
- if (xdmcpSocket6 >= 0 && FD_ISSET(xdmcpSocket6, LastSelectMask))
- {
- receive_packet(xdmcpSocket6);
- FD_CLR(xdmcpSocket6, LastSelectMask);
- }
-#endif
- XFD_ANDSET(&devicesReadable, LastSelectMask, &EnabledDevices);
- if (XFD_ANYSET(&devicesReadable))
- {
- if (state == XDM_AWAIT_USER_INPUT)
- restart();
- else if (state == XDM_RUN_SESSION)
- keepaliveDormancy = defaultKeepaliveDormancy;
- }
- if (XFD_ANYSET(&AllClients) && state == XDM_RUN_SESSION)
- timeOutTime = GetTimeInMillis() + keepaliveDormancy * 1000;
- }
- else if (timeOutTime && (int) (GetTimeInMillis() - timeOutTime) >= 0)
- {
- if (state == XDM_RUN_SESSION)
- {
- state = XDM_KEEPALIVE;
- send_packet();
- }
- else
- timeout();
- }
-}
-
-/*
- * This routine should be called from the routine that drives the
- * user's host menu when the user selects a host
- */
-
-static void
-XdmcpSelectHost(
- struct sockaddr *host_sockaddr,
- int host_len,
- ARRAY8Ptr AuthenticationName)
-{
- state = XDM_START_CONNECTION;
- memmove(&req_sockaddr, host_sockaddr, host_len);
- req_socklen = host_len;
- XdmcpSetAuthentication (AuthenticationName);
- send_packet();
-}
-
-/*
- * !!! this routine should be replaced by a routine that adds
- * the host to the user's host menu. the current version just
- * selects the first host to respond with willing message.
- */
-
-/*ARGSUSED*/
-static void
-XdmcpAddHost(
- struct sockaddr *from,
- int fromlen,
- ARRAY8Ptr AuthenticationName,
- ARRAY8Ptr hostname,
- ARRAY8Ptr status)
-{
- XdmcpSelectHost(from, fromlen, AuthenticationName);
-}
-
-/*
- * A message is queued on the socket; read it and
- * do the appropriate thing
- */
-
-ARRAY8 UnwillingMessage = { (CARD8) 14, (CARD8 *) "Host unwilling" };
-
-static void
-receive_packet(int socketfd)
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct sockaddr_storage from;
-#else
- struct sockaddr_in from;
-#endif
- int fromlen = sizeof(from);
- XdmcpHeader header;
-
- /* read message off socket */
- if (!XdmcpFill (socketfd, &buffer, (XdmcpNetaddr) &from, &fromlen))
- return;
-
- /* reset retransmission backoff */
- timeOutRtx = 0;
-
- if (!XdmcpReadHeader (&buffer, &header))
- return;
-
- if (header.version != XDM_PROTOCOL_VERSION)
- return;
-
- switch (header.opcode) {
- case WILLING:
- recv_willing_msg((struct sockaddr *) &from, fromlen, header.length);
- break;
- case UNWILLING:
- XdmcpFatal("Manager unwilling", &UnwillingMessage);
- break;
- case ACCEPT:
- recv_accept_msg(header.length);
- break;
- case DECLINE:
- recv_decline_msg(header.length);
- break;
- case REFUSE:
- recv_refuse_msg(header.length);
- break;
- case FAILED:
- recv_failed_msg(header.length);
- break;
- case ALIVE:
- recv_alive_msg(header.length);
- break;
- }
-}
-
-/*
- * send the appropriate message given the current state
- */
-
-static void
-send_packet(void)
-{
- int rtx;
- switch (state) {
- case XDM_QUERY:
- case XDM_BROADCAST:
- case XDM_INDIRECT:
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_MULTICAST:
-#endif
- send_query_msg();
- break;
- case XDM_START_CONNECTION:
- send_request_msg();
- break;
- case XDM_MANAGE:
- send_manage_msg();
- break;
- case XDM_KEEPALIVE:
- send_keepalive_msg();
- break;
- default:
- break;
- }
- rtx = (XDM_MIN_RTX << timeOutRtx);
- if (rtx > XDM_MAX_RTX)
- rtx = XDM_MAX_RTX;
- timeOutTime = GetTimeInMillis() + rtx * 1000;
-}
-
-/*
- * The session is declared dead for some reason; too many
- * timeouts, or Keepalive failure.
- */
-
-void
-XdmcpDeadSession (char *reason)
-{
- ErrorF ("XDM: %s, declaring session dead\n", reason);
- state = XDM_INIT_STATE;
- isItTimeToYield = TRUE;
- dispatchException |= DE_RESET;
- timeOutTime = 0;
- timeOutRtx = 0;
- send_packet();
-}
-
-/*
- * Timeout waiting for an XDMCP response.
- */
-
-static void
-timeout(void)
-{
- timeOutRtx++;
- if (state == XDM_AWAIT_ALIVE_RESPONSE && timeOutRtx >= XDM_KA_RTX_LIMIT )
- {
- XdmcpDeadSession ("too many keepalive retransmissions");
- return;
- }
- else if (timeOutRtx >= XDM_RTX_LIMIT)
- {
- /* Quit if "-once" specified, otherwise reset and try again. */
- if (OneSession) {
- dispatchException |= DE_TERMINATE;
- ErrorF("XDM: too many retransmissions\n");
- } else {
- XdmcpDeadSession("too many retransmissions");
- }
- return;
- }
-
-#if defined(IPv6) && defined(AF_INET6)
- if (state == XDM_COLLECT_QUERY || state == XDM_COLLECT_INDIRECT_QUERY) {
- /* Try next address */
- for (mgrAddr = mgrAddr->ai_next; ; mgrAddr = mgrAddr->ai_next) {
- if (mgrAddr == NULL) {
- mgrAddr = mgrAddrFirst;
- }
- if (mgrAddr->ai_family == AF_INET
- || mgrAddr->ai_family == AF_INET6)
- break;
- }
-#ifndef SIN6_LEN
- ManagerAddressLen = mgrAddr->ai_addrlen;
-#endif
- memcpy(&ManagerAddress, mgrAddr->ai_addr, mgrAddr->ai_addrlen);
- }
-#endif
-
- switch (state) {
- case XDM_COLLECT_QUERY:
- state = XDM_QUERY;
- break;
- case XDM_COLLECT_BROADCAST_QUERY:
- state = XDM_BROADCAST;
- break;
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_COLLECT_MULTICAST_QUERY:
- state = XDM_MULTICAST;
- break;
-#endif
- case XDM_COLLECT_INDIRECT_QUERY:
- state = XDM_INDIRECT;
- break;
- case XDM_AWAIT_REQUEST_RESPONSE:
- state = XDM_START_CONNECTION;
- break;
- case XDM_AWAIT_MANAGE_RESPONSE:
- state = XDM_MANAGE;
- break;
- case XDM_AWAIT_ALIVE_RESPONSE:
- state = XDM_KEEPALIVE;
- break;
- default:
- break;
- }
- send_packet();
-}
-
-static void
-restart(void)
-{
- state = XDM_INIT_STATE;
- timeOutRtx = 0;
- send_packet();
-}
-
-int
-XdmcpCheckAuthentication (
- ARRAY8Ptr Name,
- ARRAY8Ptr Data,
- int packet_type)
-{
- return (XdmcpARRAY8Equal (Name, AuthenticationName) &&
- (AuthenticationName->length == 0 ||
- (*AuthenticationFuncs->Validator) (AuthenticationData, Data, packet_type)));
-}
-
-int
-XdmcpAddAuthorization (
- ARRAY8Ptr name,
- ARRAY8Ptr data)
-{
- AddAuthorFunc AddAuth;
-
- if (AuthenticationFuncs && AuthenticationFuncs->AddAuth)
- AddAuth = AuthenticationFuncs->AddAuth;
- else
- AddAuth = AddAuthorization;
- return (*AddAuth) ((unsigned short)name->length,
- (char *)name->data,
- (unsigned short)data->length,
- (char *)data->data);
-}
-
-/*
- * from here to the end of this file are routines private
- * to the state machine.
- */
-
-static void
-get_xdmcp_sock(void)
-{
-#ifdef STREAMSCONN
- struct netconfig *nconf;
-
- if ((xdmcpSocket = t_open("/dev/udp", O_RDWR, 0)) < 0) {
- XdmcpWarning("t_open() of /dev/udp failed");
- return;
- }
-
- if( t_bind(xdmcpSocket,NULL,NULL) < 0 ) {
- XdmcpWarning("UDP socket creation failed");
- t_error("t_bind(xdmcpSocket) failed" );
- t_close(xdmcpSocket);
- return;
- }
-
- /*
- * This part of the code looks contrived. It will actually fit in nicely
- * when the CLTS part of Xtrans is implemented.
- */
-
- if( (nconf=getnetconfigent("udp")) == NULL ) {
- XdmcpWarning("UDP socket creation failed: getnetconfigent()");
- t_unbind(xdmcpSocket);
- t_close(xdmcpSocket);
- return;
- }
-
- if( netdir_options(nconf, ND_SET_BROADCAST, xdmcpSocket, NULL) ) {
- XdmcpWarning("UDP set broadcast option failed: netdir_options()");
- freenetconfigent(nconf);
- t_unbind(xdmcpSocket);
- t_close(xdmcpSocket);
- return;
- }
-
- freenetconfigent(nconf);
-#else
- int soopts = 1;
-
-#if defined(IPv6) && defined(AF_INET6)
- if ((xdmcpSocket6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
- XdmcpWarning("INET6 UDP socket creation failed");
-#endif
- if ((xdmcpSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
- XdmcpWarning("UDP socket creation failed");
-#ifdef SO_BROADCAST
- else if (setsockopt(xdmcpSocket, SOL_SOCKET, SO_BROADCAST, (char *)&soopts,
- sizeof(soopts)) < 0)
- XdmcpWarning("UDP set broadcast socket-option failed");
-#endif /* SO_BROADCAST */
- if (xdmcpSocket >= 0 && xdm_from != NULL) {
- if (bind(xdmcpSocket, (struct sockaddr *)&FromAddress,
- FromAddressLen) < 0) {
- FatalError("Xserver: failed to bind to -from address: %s\n", xdm_from);
- }
- }
-#endif /* STREAMSCONN */
-}
-
-static void
-send_query_msg(void)
-{
- XdmcpHeader header;
- Bool broadcast = FALSE;
-#if defined(IPv6) && defined(AF_INET6)
- Bool multicast = FALSE;
-#endif
- int i;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- switch(state){
- case XDM_QUERY:
- header.opcode = (CARD16) QUERY;
- state = XDM_COLLECT_QUERY;
- break;
- case XDM_BROADCAST:
- header.opcode = (CARD16) BROADCAST_QUERY;
- state = XDM_COLLECT_BROADCAST_QUERY;
- broadcast = TRUE;
- break;
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_MULTICAST:
- header.opcode = (CARD16) BROADCAST_QUERY;
- state = XDM_COLLECT_MULTICAST_QUERY;
- multicast = TRUE;
- break;
-#endif
- case XDM_INDIRECT:
- header.opcode = (CARD16) INDIRECT_QUERY;
- state = XDM_COLLECT_INDIRECT_QUERY;
- break;
- default:
- break;
- }
- header.length = 1;
- for (i = 0; i < AuthenticationNames.length; i++)
- header.length += 2 + AuthenticationNames.data[i].length;
-
- XdmcpWriteHeader (&buffer, &header);
- XdmcpWriteARRAYofARRAY8 (&buffer, &AuthenticationNames);
- if (broadcast)
- {
- int i;
-
- for (i = 0; i < NumBroadcastAddresses; i++)
- XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &BroadcastAddresses[i],
- sizeof (struct sockaddr_in));
- }
-#if defined(IPv6) && defined(AF_INET6)
- else if (multicast)
- {
- struct multicastinfo *mcl;
- struct addrinfo *ai;
-
- for (mcl = mcastlist; mcl != NULL; mcl = mcl->next) {
- for (ai = mcl->ai ; ai != NULL; ai = ai->ai_next) {
- if (ai->ai_family == AF_INET) {
- unsigned char hopflag = (unsigned char) mcl->hops;
- socketfd = xdmcpSocket;
- setsockopt(socketfd, IPPROTO_IP, IP_MULTICAST_TTL,
- &hopflag, sizeof(hopflag));
- } else if (ai->ai_family == AF_INET6) {
- int hopflag6 = mcl->hops;
- socketfd = xdmcpSocket6;
- setsockopt(socketfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
- &hopflag6, sizeof(hopflag6));
- } else {
- continue;
- }
- XdmcpFlush (socketfd, &buffer,
- (XdmcpNetaddr) ai->ai_addr, ai->ai_addrlen);
- break;
- }
- }
- }
-#endif
- else
- {
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(ManagerAddress) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &ManagerAddress,
- ManagerAddressLen);
- }
-}
-
-static void
-recv_willing_msg(
- struct sockaddr *from,
- int fromlen,
- unsigned length)
-{
- ARRAY8 authenticationName;
- ARRAY8 hostname;
- ARRAY8 status;
-
- authenticationName.data = 0;
- hostname.data = 0;
- status.data = 0;
- if (XdmcpReadARRAY8 (&buffer, &authenticationName) &&
- XdmcpReadARRAY8 (&buffer, &hostname) &&
- XdmcpReadARRAY8 (&buffer, &status))
- {
- if (length == 6 + authenticationName.length +
- hostname.length + status.length)
- {
- switch (state)
- {
- case XDM_COLLECT_QUERY:
- XdmcpSelectHost(from, fromlen, &authenticationName);
- break;
- case XDM_COLLECT_BROADCAST_QUERY:
-#if defined(IPv6) && defined(AF_INET6)
- case XDM_COLLECT_MULTICAST_QUERY:
-#endif
- case XDM_COLLECT_INDIRECT_QUERY:
- XdmcpAddHost(from, fromlen, &authenticationName, &hostname, &status);
- break;
- default:
- break;
- }
- }
- }
- XdmcpDisposeARRAY8 (&authenticationName);
- XdmcpDisposeARRAY8 (&hostname);
- XdmcpDisposeARRAY8 (&status);
-}
-
-static void
-send_request_msg(void)
-{
- XdmcpHeader header;
- int length;
- int i;
- CARD16 XdmcpConnectionType;
- ARRAY8 authenticationData;
- int socketfd = xdmcpSocket;
-
- switch (SOCKADDR_FAMILY(ManagerAddress))
- {
- case AF_INET: XdmcpConnectionType=FamilyInternet; break;
-#if defined(IPv6) && defined(AF_INET6)
- case AF_INET6: XdmcpConnectionType=FamilyInternet6; break;
-#endif
- default: XdmcpConnectionType=0xffff; break;
- }
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) REQUEST;
-
- length = 2; /* display number */
- length += 1 + 2 * ConnectionTypes.length; /* connection types */
- length += 1; /* connection addresses */
- for (i = 0; i < ConnectionAddresses.length; i++)
- length += 2 + ConnectionAddresses.data[i].length;
- authenticationData.length = 0;
- authenticationData.data = 0;
- if (AuthenticationFuncs)
- {
- (*AuthenticationFuncs->Generator) (AuthenticationData,
- &authenticationData,
- REQUEST);
- }
- length += 2 + AuthenticationName->length; /* authentication name */
- length += 2 + authenticationData.length; /* authentication data */
- length += 1; /* authorization names */
- for (i = 0; i < AuthorizationNames.length; i++)
- length += 2 + AuthorizationNames.data[i].length;
- length += 2 + ManufacturerDisplayID.length; /* display ID */
- header.length = length;
-
- if (!XdmcpWriteHeader (&buffer, &header))
- {
- XdmcpDisposeARRAY8 (&authenticationData);
- return;
- }
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteCARD8 (&buffer, ConnectionTypes.length);
-
- /* The connection array is send reordered, so that connections of */
- /* the same address type as the XDMCP manager connection are send */
- /* first. This works around a bug in xdm. mario@klebsch.de */
- for (i = 0; i < (int)ConnectionTypes.length; i++)
- if (ConnectionTypes.data[i]==XdmcpConnectionType)
- XdmcpWriteCARD16 (&buffer, ConnectionTypes.data[i]);
- for (i = 0; i < (int)ConnectionTypes.length; i++)
- if (ConnectionTypes.data[i]!=XdmcpConnectionType)
- XdmcpWriteCARD16 (&buffer, ConnectionTypes.data[i]);
-
- XdmcpWriteCARD8 (&buffer, ConnectionAddresses.length);
- for (i = 0; i < (int)ConnectionAddresses.length; i++)
- if ( (i<ConnectionTypes.length) &&
- (ConnectionTypes.data[i]==XdmcpConnectionType) )
- XdmcpWriteARRAY8 (&buffer, &ConnectionAddresses.data[i]);
- for (i = 0; i < (int)ConnectionAddresses.length; i++)
- if ( (i>=ConnectionTypes.length) ||
- (ConnectionTypes.data[i]!=XdmcpConnectionType) )
- XdmcpWriteARRAY8 (&buffer, &ConnectionAddresses.data[i]);
-
- XdmcpWriteARRAY8 (&buffer, AuthenticationName);
- XdmcpWriteARRAY8 (&buffer, &authenticationData);
- XdmcpDisposeARRAY8 (&authenticationData);
- XdmcpWriteARRAYofARRAY8 (&buffer, &AuthorizationNames);
- XdmcpWriteARRAY8 (&buffer, &ManufacturerDisplayID);
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- if (XdmcpFlush (socketfd, &buffer,
- (XdmcpNetaddr) &req_sockaddr, req_socklen))
- state = XDM_AWAIT_REQUEST_RESPONSE;
-}
-
-static void
-recv_accept_msg(unsigned length)
-{
- CARD32 AcceptSessionID;
- ARRAY8 AcceptAuthenticationName, AcceptAuthenticationData;
- ARRAY8 AcceptAuthorizationName, AcceptAuthorizationData;
-
- if (state != XDM_AWAIT_REQUEST_RESPONSE)
- return;
- AcceptAuthenticationName.data = 0;
- AcceptAuthenticationData.data = 0;
- AcceptAuthorizationName.data = 0;
- AcceptAuthorizationData.data = 0;
- if (XdmcpReadCARD32 (&buffer, &AcceptSessionID) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthenticationName) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthenticationData) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthorizationName) &&
- XdmcpReadARRAY8 (&buffer, &AcceptAuthorizationData))
- {
- if (length == 12 + AcceptAuthenticationName.length +
- AcceptAuthenticationData.length +
- AcceptAuthorizationName.length +
- AcceptAuthorizationData.length)
- {
- if (!XdmcpCheckAuthentication (&AcceptAuthenticationName,
- &AcceptAuthenticationData, ACCEPT))
- {
- XdmcpFatal ("Authentication Failure", &AcceptAuthenticationName);
- }
- /* permit access control manipulations from this host */
- AugmentSelf (&req_sockaddr, req_socklen);
- /* if the authorization specified in the packet fails
- * to be acceptable, enable the local addresses
- */
- if (!XdmcpAddAuthorization (&AcceptAuthorizationName,
- &AcceptAuthorizationData))
- {
- AddLocalHosts ();
- }
- SessionID = AcceptSessionID;
- state = XDM_MANAGE;
- send_packet();
- }
- }
- XdmcpDisposeARRAY8 (&AcceptAuthenticationName);
- XdmcpDisposeARRAY8 (&AcceptAuthenticationData);
- XdmcpDisposeARRAY8 (&AcceptAuthorizationName);
- XdmcpDisposeARRAY8 (&AcceptAuthorizationData);
-}
-
-static void
-recv_decline_msg(unsigned length)
-{
- ARRAY8 status, DeclineAuthenticationName, DeclineAuthenticationData;
-
- status.data = 0;
- DeclineAuthenticationName.data = 0;
- DeclineAuthenticationData.data = 0;
- if (XdmcpReadARRAY8 (&buffer, &status) &&
- XdmcpReadARRAY8 (&buffer, &DeclineAuthenticationName) &&
- XdmcpReadARRAY8 (&buffer, &DeclineAuthenticationData))
- {
- if (length == 6 + status.length +
- DeclineAuthenticationName.length +
- DeclineAuthenticationData.length &&
- XdmcpCheckAuthentication (&DeclineAuthenticationName,
- &DeclineAuthenticationData, DECLINE))
- {
- XdmcpFatal ("Session declined", &status);
- }
- }
- XdmcpDisposeARRAY8 (&status);
- XdmcpDisposeARRAY8 (&DeclineAuthenticationName);
- XdmcpDisposeARRAY8 (&DeclineAuthenticationData);
-}
-
-static void
-send_manage_msg(void)
-{
- XdmcpHeader header;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) MANAGE;
- header.length = 8 + DisplayClass.length;
-
- if (!XdmcpWriteHeader (&buffer, &header))
- return;
- XdmcpWriteCARD32 (&buffer, SessionID);
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteARRAY8 (&buffer, &DisplayClass);
- state = XDM_AWAIT_MANAGE_RESPONSE;
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen);
-}
-
-static void
-recv_refuse_msg(unsigned length)
-{
- CARD32 RefusedSessionID;
-
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- if (length != 4)
- return;
- if (XdmcpReadCARD32 (&buffer, &RefusedSessionID))
- {
- if (RefusedSessionID == SessionID)
- {
- state = XDM_START_CONNECTION;
- send_packet();
- }
- }
-}
-
-static void
-recv_failed_msg(unsigned length)
-{
- CARD32 FailedSessionID;
- ARRAY8 status;
-
- if (state != XDM_AWAIT_MANAGE_RESPONSE)
- return;
- status.data = 0;
- if (XdmcpReadCARD32 (&buffer, &FailedSessionID) &&
- XdmcpReadARRAY8 (&buffer, &status))
- {
- if (length == 6 + status.length &&
- SessionID == FailedSessionID)
- {
- XdmcpFatal ("Session failed", &status);
- }
- }
- XdmcpDisposeARRAY8 (&status);
-}
-
-static void
-send_keepalive_msg(void)
-{
- XdmcpHeader header;
- int socketfd = xdmcpSocket;
-
- header.version = XDM_PROTOCOL_VERSION;
- header.opcode = (CARD16) KEEPALIVE;
- header.length = 6;
-
- XdmcpWriteHeader (&buffer, &header);
- XdmcpWriteCARD16 (&buffer, DisplayNumber);
- XdmcpWriteCARD32 (&buffer, SessionID);
-
- state = XDM_AWAIT_ALIVE_RESPONSE;
-#if defined(IPv6) && defined(AF_INET6)
- if (SOCKADDR_FAMILY(req_sockaddr) == AF_INET6)
- socketfd = xdmcpSocket6;
-#endif
- XdmcpFlush (socketfd, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen);
-}
-
-static void
-recv_alive_msg (unsigned length)
-{
- CARD8 SessionRunning;
- CARD32 AliveSessionID;
-
- if (state != XDM_AWAIT_ALIVE_RESPONSE)
- return;
- if (length != 5)
- return;
- if (XdmcpReadCARD8 (&buffer, &SessionRunning) &&
- XdmcpReadCARD32 (&buffer, &AliveSessionID))
- {
- if (SessionRunning && AliveSessionID == SessionID)
- {
- /* backoff dormancy period */
- state = XDM_RUN_SESSION;
- if ((GetTimeInMillis() - lastDeviceEventTime.milliseconds) >
- keepaliveDormancy * 1000)
- {
- keepaliveDormancy <<= 1;
- if (keepaliveDormancy > XDM_MAX_DORMANCY)
- keepaliveDormancy = XDM_MAX_DORMANCY;
- }
- timeOutTime = GetTimeInMillis() + keepaliveDormancy * 1000;
- }
- else
- {
- XdmcpDeadSession ("Alive response indicates session dead");
- }
- }
-}
-
-static void
-XdmcpFatal (
- char *type,
- ARRAY8Ptr status)
-{
- FatalError ("XDMCP fatal error: %s %*.*s\n", type,
- status->length, status->length, status->data);
-}
-
-static void
-XdmcpWarning(char *str)
-{
- ErrorF("XDMCP warning: %s\n", str);
-}
-
-static void
-get_addr_by_name(
- char * argtype,
- char * namestr,
- int port,
- int socktype,
- SOCKADDR_TYPE *addr,
- SOCKLEN_TYPE *addrlen
-#if defined(IPv6) && defined(AF_INET6)
- ,
- struct addrinfo **aip,
- struct addrinfo **aifirstp
-#endif
- )
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo *ai;
- struct addrinfo hints;
- char portstr[6];
- char *pport = portstr;
- int gaierr;
-
- bzero(&hints, sizeof(hints));
- hints.ai_socktype = socktype;
-
- if (port == 0) {
- pport = NULL;
- } else if (port > 0 && port < 65535) {
- sprintf(portstr, "%d", port);
- } else {
- FatalError("Xserver: port out of range: %d\n", port);
- }
-
- if (*aifirstp != NULL) {
- freeaddrinfo(*aifirstp);
- *aifirstp = NULL;
- }
-
- if ((gaierr = getaddrinfo(namestr, pport, &hints, aifirstp)) == 0) {
- for (ai = *aifirstp; ai != NULL; ai = ai->ai_next) {
- if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)
- break;
- }
- if ((ai == NULL) || (ai->ai_addrlen > sizeof(SOCKADDR_TYPE))) {
- FatalError ("Xserver: %s host %s not on supported network type\n",
- argtype, namestr);
- } else {
- *aip = ai;
- *addrlen = ai->ai_addrlen;
- memcpy(addr, ai->ai_addr, ai->ai_addrlen);
- }
- } else {
- FatalError("Xserver: %s: %s %s\n", gai_strerror(gaierr), argtype, namestr);
- }
-#else
- struct hostent *hep;
-#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
- _Xgethostbynameparams hparams;
-#endif
-#if defined(WIN32) && (defined(TCPCONN) || defined(DNETCONN))
- _XSERVTransWSAStartup();
-#endif
- if (!(hep = _XGethostbyname(namestr, hparams)))
- {
- FatalError("Xserver: %s unknown host: %s\n", argtype, namestr);
- }
- if (hep->h_length == sizeof (struct in_addr))
- {
- memmove(&addr->sin_addr, hep->h_addr, hep->h_length);
- *addrlen = sizeof(struct sockaddr_in);
- addr->sin_family = AF_INET;
- addr->sin_port = htons (port);
- }
- else
- {
- FatalError("Xserver: %s host on strange network %s\n", argtype, namestr);
- }
-#endif
-}
-
-static void
-get_manager_by_name(
- int argc,
- char **argv,
- int i)
-{
-
- if ((i + 1) == argc)
- {
- FatalError("Xserver: missing %s host name in command line\n", argv[i]);
- }
-
- get_addr_by_name(argv[i], argv[i+1], xdm_udp_port, SOCK_DGRAM,
- &ManagerAddress, &ManagerAddressLen
-#if defined(IPv6) && defined(AF_INET6)
- , &mgrAddr, &mgrAddrFirst
-#endif
- );
-}
-
-
-static void
-get_fromaddr_by_name(
- int argc,
- char **argv,
- int i)
-{
-#if defined(IPv6) && defined(AF_INET6)
- struct addrinfo *ai = NULL;
- struct addrinfo *aifirst = NULL;
-#endif
- if (i == argc)
- {
- FatalError("Xserver: missing -from host name in command line\n");
- }
- get_addr_by_name("-from", argv[i], 0, 0, &FromAddress, &FromAddressLen
-#if defined(IPv6) && defined(AF_INET6)
- , &ai, &aifirst
-#endif
- );
- xdm_from = argv[i];
-}
-
-
-#if defined(IPv6) && defined(AF_INET6)
-static int
-get_mcast_options(argc, argv, i)
- int argc, i;
- char **argv;
-{
- char *address = XDM_DEFAULT_MCAST_ADDR6;
- int hopcount = 1;
- struct addrinfo hints;
- char portstr[6];
- int gaierr;
- struct addrinfo *ai, *firstai;
-
- if ((i < argc) && (argv[i][0] != '-') && (argv[i][0] != '+')) {
- address = argv[i++];
- if ((i < argc) && (argv[i][0] != '-') && (argv[i][0] != '+')) {
- hopcount = strtol(argv[i++], NULL, 10);
- if ((hopcount < 1) || (hopcount > 255)) {
- FatalError("Xserver: multicast hop count out of range: %d\n",
- hopcount);
- }
- }
- }
-
- if (xdm_udp_port > 0 && xdm_udp_port < 65535) {
- sprintf(portstr, "%d", xdm_udp_port);
- } else {
- FatalError("Xserver: port out of range: %d\n", xdm_udp_port);
- }
- bzero(&hints, sizeof(hints));
- hints.ai_socktype = SOCK_DGRAM;
-
- if ((gaierr = getaddrinfo(address, portstr, &hints, &firstai)) == 0) {
- for (ai = firstai; ai != NULL; ai = ai->ai_next) {
- if (((ai->ai_family == AF_INET) &&
- IN_MULTICAST(((struct sockaddr_in *) ai->ai_addr)
- ->sin_addr.s_addr))
- || ((ai->ai_family == AF_INET6) &&
- IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *) ai->ai_addr)
- ->sin6_addr)))
- break;
- }
- if (ai == NULL) {
- FatalError ("Xserver: address not supported multicast type %s\n",
- address);
- } else {
- struct multicastinfo *mcastinfo, *mcl;
-
- mcastinfo = malloc(sizeof(struct multicastinfo));
- mcastinfo->next = NULL;
- mcastinfo->ai = firstai;
- mcastinfo->hops = hopcount;
-
- if (mcastlist == NULL) {
- mcastlist = mcastinfo;
- } else {
- for (mcl = mcastlist; mcl->next != NULL; mcl = mcl->next) {
- /* Do nothing - just find end of list */
- }
- mcl->next = mcastinfo;
- }
- }
- } else {
- FatalError("Xserver: %s: %s\n", gai_strerror(gaierr), address);
- }
- return i;
-}
-#endif
-
-#else
-static int xdmcp_non_empty; /* avoid complaint by ranlib */
-#endif /* XDMCP */
diff --git a/nx-X11/programs/Xserver/os/xprintf.c.NX.original b/nx-X11/programs/Xserver/os/xprintf.c.NX.original
deleted file mode 100644
index 54bbeefe2..000000000
--- a/nx-X11/programs/Xserver/os/xprintf.c.NX.original
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * printf routines which xalloc their buffer
- */
-/*
- * Copyright (c) 2004 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * 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 ABOVE LISTED COPYRIGHT HOLDER(S) 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(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xos.h>
-#include "os.h"
-#include <stdarg.h>
-#include <stdio.h>
-
-#ifndef va_copy
-# ifdef __va_copy
-# define va_copy __va_copy
-# else
-# error "no working va_copy was found"
-# endif
-#endif
-
-#ifdef NX_TRANS_SOCKET
-
-#define PANIC
-#define WARNING
-#undef TEST
-#undef DEBUG
-
-#define START_SIZE 256
-#define END_SIZE 2048
-
-char *
-Xvprintf(const char *format, va_list va)
-{
- char *ret;
- char *newret;
- int size;
- int r;
-
- size = 0;
-
- for (;;)
- {
- if (size == 0)
- {
- ret = (char *)malloc(START_SIZE);
- if (ret == NULL)
- return NULL;
- size = START_SIZE;
- }
- else if (size < END_SIZE &&
- (newret = (char *) realloc(ret, 2 * size)) != NULL)
- {
- ret = newret;
- size = 2 * size;
- }
- else
- {
- free(ret);
- return NULL;
- }
-
- r = vsnprintf(ret, size, format, va);
-
- if (r == -1 || r == size || r > size || r == size - 1)
- {
- continue;
- }
- else
- {
- ret[r] = 0;
- return ret;
- }
- }
-}
-
-#else
-
-char *
-Xvprintf(const char *format, va_list va)
-{
- char *ret;
- int size;
- va_list va2;
-
- va_copy(va2, va);
- size = vsnprintf(NULL, 0, format, va2);
- va_end(va2);
-
- ret = (char *)Xalloc(size + 1);
- if (ret == NULL)
- return NULL;
-
- vsnprintf(ret, size + 1, format, va);
- ret[size] = 0;
- return ret;
-}
-
-#endif
-
-char *Xprintf(const char *format, ...)
-{
- char *ret;
- va_list va;
- va_start(va, format);
- ret = Xvprintf(format, va);
- va_end(va);
- return ret;
-}
-
-char *
-XNFvprintf(const char *format, va_list va)
-{
- char *ret;
- int size;
- va_list va2;
-
- va_copy(va2, va);
- size = vsnprintf(NULL, 0, format, va2);
- va_end(va2);
-
- ret = (char *)XNFalloc(size + 1);
- if (ret == NULL)
- return NULL;
-
- vsnprintf(ret, size + 1, format, va);
- ret[size] = 0;
- return ret;
-}
-
-char *XNFprintf(const char *format, ...)
-{
- char *ret;
- va_list va;
- va_start(va, format);
- ret = XNFvprintf(format, va);
- va_end(va);
- return ret;
-}
diff --git a/nx-X11/programs/Xserver/os/xprintf.c.X.original b/nx-X11/programs/Xserver/os/xprintf.c.X.original
deleted file mode 100644
index 07eaa1f58..000000000
--- a/nx-X11/programs/Xserver/os/xprintf.c.X.original
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * printf routines which xalloc their buffer
- */
-/*
- * Copyright (c) 2004 Alexander Gottwald
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * 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 ABOVE LISTED COPYRIGHT HOLDER(S) 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(s) of the above copyright
- * holders shall not be used in advertising or otherwise to promote the sale,
- * use or other dealings in this Software without prior written authorization.
- */
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xos.h>
-#include "os.h"
-#include <stdarg.h>
-#include <stdio.h>
-
-#ifndef va_copy
-# ifdef __va_copy
-# define va_copy __va_copy
-# else
-# error "no working va_copy was found"
-# endif
-#endif
-
-char *
-Xvprintf(const char *format, va_list va)
-{
- char *ret;
- int size;
- va_list va2;
-
- va_copy(va2, va);
- size = vsnprintf(NULL, 0, format, va2);
- va_end(va2);
-
- ret = (char *)Xalloc(size + 1);
- if (ret == NULL)
- return NULL;
-
- vsnprintf(ret, size + 1, format, va);
- ret[size] = 0;
- return ret;
-}
-
-char *Xprintf(const char *format, ...)
-{
- char *ret;
- va_list va;
- va_start(va, format);
- ret = Xvprintf(format, va);
- va_end(va);
- return ret;
-}
-
-char *
-XNFvprintf(const char *format, va_list va)
-{
- char *ret;
- int size;
- va_list va2;
-
- va_copy(va2, va);
- size = vsnprintf(NULL, 0, format, va2);
- va_end(va2);
-
- ret = (char *)XNFalloc(size + 1);
- if (ret == NULL)
- return NULL;
-
- vsnprintf(ret, size + 1, format, va);
- ret[size] = 0;
- return ret;
-}
-
-char *XNFprintf(const char *format, ...)
-{
- char *ret;
- va_list va;
- va_start(va, format);
- ret = XNFvprintf(format, va);
- va_end(va);
- return ret;
-}