diff options
Diffstat (limited to 'os')
-rw-r--r-- | os/WaitFor.c | 182 | ||||
-rw-r--r-- | os/access.c | 569 | ||||
-rw-r--r-- | os/auth.c | 189 | ||||
-rw-r--r-- | os/connection.c | 310 | ||||
-rw-r--r-- | os/io.c | 163 | ||||
-rw-r--r-- | os/k5auth.c | 3 | ||||
-rw-r--r-- | os/lbxio.c | 42 | ||||
-rw-r--r-- | os/mitauth.c | 54 | ||||
-rw-r--r-- | os/oscolor.c | 32 | ||||
-rw-r--r-- | os/osdep.h | 189 | ||||
-rw-r--r-- | os/osinit.c | 42 | ||||
-rw-r--r-- | os/rpcauth.c | 41 | ||||
-rw-r--r-- | os/secauth.c | 30 | ||||
-rw-r--r-- | os/utils.c | 1179 | ||||
-rw-r--r-- | os/xdmauth.c | 9 | ||||
-rw-r--r-- | os/xdmcp.c | 377 |
16 files changed, 2563 insertions, 848 deletions
diff --git a/os/WaitFor.c b/os/WaitFor.c index fbc05399c..76fa67327 100644 --- a/os/WaitFor.c +++ b/os/WaitFor.c @@ -1,3 +1,4 @@ +/* $XFree86: xc/programs/Xserver/os/WaitFor.c,v 3.38 2002/05/31 18:46:05 dawes Exp $ */ /*********************************************************** Copyright 1987, 1998 The Open Group @@ -59,48 +60,42 @@ SOFTWARE. #include <X11/Xwinsock.h> #endif #include "Xos.h" /* for strings, fcntl, time */ - #include <errno.h> -#ifdef X_NOT_STDC_ENV -extern int errno; -#endif - #include <stdio.h> #include "X.h" #include "misc.h" -#include <X11/Xpoll.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 "dpms.h" -extern void DPMSSet(); -extern void DPMSGet(); -extern CARD32 DPMSStandbyTime; -extern CARD32 DPMSSuspendTime; -extern CARD32 DPMSOffTime; -extern BOOL DPMSEnabled; -extern CARD16 DPMSPowerLevel; +#include "dpmsproc.h" #endif -extern fd_set AllSockets; -extern fd_set AllClients; -extern fd_set LastSelectMask; -extern fd_set WellKnownConnections; -extern fd_set EnabledDevices; -extern fd_set ClientsWithInput; -extern fd_set ClientsWriteBlocked; -extern fd_set OutputPending; - -extern int ConnectionTranslation[]; - -extern Bool NewOutputPending; -extern Bool AnyClientsWriteBlocked; +/* modifications by raphael */ +int +mffs(fd_mask mask) +{ + int i; -extern WorkQueuePtr workQueue; + if (!mask) return 0; + i = 1; + while (!(mask & 1)) + { + i++; + mask >>= 1; + } + return i; +} +#ifdef DPMSExtension +#define DPMS_SERVER +#include "dpms.h" +#endif #ifdef XTESTEXT1 /* @@ -116,7 +111,7 @@ struct _OsTimerRec { pointer arg; }; -static void DoTimer(); +static void DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev); static OsTimerPtr timers; /***************** @@ -144,9 +139,9 @@ WaitForSomething(pClientsReady) { int i; struct timeval waittime, *wt; - INT32 timeout; + INT32 timeout = 0; #ifdef DPMSExtension - INT32 standbyTimeout, suspendTimeout, offTimeout; + INT32 standbyTimeout = 0, suspendTimeout = 0, offTimeout = 0; #endif fd_set clientsReadable; fd_set clientsWritable; @@ -154,7 +149,10 @@ WaitForSomething(pClientsReady) int selecterr; int nready; fd_set devicesReadable; - CARD32 now; + CARD32 now = 0; +#ifdef SMART_SCHEDULE + Bool someReady = FALSE; +#endif FD_ZERO(&clientsReadable); @@ -165,12 +163,32 @@ WaitForSomething(pClientsReady) /* deal with any blocked jobs */ if (workQueue) ProcessWorkQueue(); - if (XFD_ANYSET (&ClientsWithInput)) { - XFD_COPYSET (&ClientsWithInput, &clientsReadable); - break; +#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 #ifdef DPMSExtension if (ScreenSaverTime > 0 || DPMSEnabled || timers) #else @@ -180,7 +198,7 @@ WaitForSomething(pClientsReady) wt = NULL; if (timers) { - while (timers && timers->expires <= now) + while (timers && (int) (timers->expires - now) <= 0) DoTimer(timers, now, &timers); if (timers) { @@ -193,8 +211,8 @@ WaitForSomething(pClientsReady) } if (ScreenSaverTime > 0 #ifdef DPMSExtension - || (DPMSEnabled && - (DPMSStandbyTime > 0 || DPMSSuspendTime > 0 || DPMSOffTime > 0)) + || (DPMSEnabled && + (DPMSStandbyTime > 0 || DPMSSuspendTime > 0 || DPMSOffTime > 0)) #endif ) { #ifdef DPMSExtension @@ -214,11 +232,12 @@ WaitForSomething(pClientsReady) (now - lastDeviceEventTime.milliseconds)); #endif /* DPMSExtension */ - if (timeout <= 0 + if ( + timeout <= 0 #ifdef DPMSExtension && ScreenSaverTime > 0 #endif /* DPMSExtension */ - ) { + ) { INT32 timeSinceSave; timeSinceSave = -timeout; @@ -250,15 +269,18 @@ WaitForSomething(pClientsReady) #ifdef DPMSExtension if (DPMSEnabled) { - if (standbyTimeout > 0 && timeout > standbyTimeout) + if (standbyTimeout > 0 + && (timeout <= 0 || timeout > standbyTimeout)) timeout = standbyTimeout; - if (suspendTimeout > 0 && timeout > suspendTimeout) + if (suspendTimeout > 0 + && (timeout <= 0 || timeout > suspendTimeout)) timeout = suspendTimeout; - if (offTimeout > 0 && timeout > offTimeout) + if (offTimeout > 0 + && (timeout <= 0 || timeout > offTimeout)) timeout = offTimeout; } #endif - if (timeout > 0 && (!wt || timeout < (timers->expires - now))) + if (timeout > 0 && (!wt || timeout < (int) (timers->expires - now))) { waittime.tv_sec = timeout / MILLI_PER_SECOND; waittime.tv_usec = (timeout % MILLI_PER_SECOND) * @@ -301,6 +323,10 @@ WaitForSomething(pClientsReady) #endif } XFD_COPYSET(&AllSockets, &LastSelectMask); +#ifdef SMART_SCHEDULE + } + SmartScheduleIdle = TRUE; +#endif BlockHandler((pointer)&wt, (pointer)&LastSelectMask); if (NewOutputPending) FlushAllOutput(); @@ -317,10 +343,12 @@ WaitForSomething(pClientsReady) else if (AnyClientsWriteBlocked) { XFD_COPYSET(&ClientsWriteBlocked, &clientsWritable); - i = Select (MAXSOCKS, &LastSelectMask, &clientsWritable, NULL, wt); + i = Select (MaxClients, &LastSelectMask, &clientsWritable, NULL, wt); + } + else + { + i = Select (MaxClients, &LastSelectMask, NULL, NULL, wt); } - else - i = Select (MAXSOCKS, &LastSelectMask, NULL, NULL, wt); selecterr = errno; WakeupHandler(i, (pointer)&LastSelectMask); #ifdef XTESTEXT1 @@ -328,13 +356,21 @@ WaitForSomething(pClientsReady) 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; - FD_ZERO(&clientsWritable); if (i < 0) + { if (selecterr == EBADF) /* Some client disconnected */ { CheckConnections (); @@ -351,10 +387,22 @@ WaitForSomething(pClientsReady) 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 (timers) { now = GetTimeInMillis(); - while (timers && timers->expires <= now) + while (timers && (int) (timers->expires - now) <= 0) DoTimer(timers, now, &timers); } if (*checkForInput[0] != *checkForInput[1]) @@ -362,9 +410,11 @@ WaitForSomething(pClientsReady) } else { -#ifdef WIN32 fd_set tmp_set; -#endif +#ifdef SMART_SCHEDULE + if (someReady) + XFD_ORSET(&LastSelectMask, &ClientsWithInput, &LastSelectMask); +#endif if (AnyClientsWriteBlocked && XFD_ANYSET (&clientsWritable)) { NewOutputPending = TRUE; @@ -376,12 +426,8 @@ WaitForSomething(pClientsReady) XFD_ANDSET(&devicesReadable, &LastSelectMask, &EnabledDevices); XFD_ANDSET(&clientsReadable, &LastSelectMask, &AllClients); -#ifndef WIN32 - if (LastSelectMask.fds_bits[0] & WellKnownConnections.fds_bits[0]) -#else XFD_ANDSET(&tmp_set, &LastSelectMask, &WellKnownConnections); if (XFD_ANYSET(&tmp_set)) -#endif QueueWorkProc(EstablishNewConnections, NULL, (pointer)&LastSelectMask); #ifdef DPMSExtension @@ -399,16 +445,17 @@ WaitForSomething(pClientsReady) #ifndef WIN32 for (i=0; i<howmany(XFD_SETSIZE, NFDBITS); i++) { - int highest_priority; + int highest_priority = 0; while (clientsReadable.fds_bits[i]) { int client_priority, client_index; curclient = ffs (clientsReadable.fds_bits[i]) - 1; - client_index = ConnectionTranslation[curclient + (i << 5)]; + client_index = /* raphael: modified */ + ConnectionTranslation[curclient + (i * (sizeof(fd_mask) * 8))]; #else - int highest_priority; + int highest_priority = 0; fd_set savedClientsReadable; XFD_COPYSET(&clientsReadable, &savedClientsReadable); for (i = 0; i < XFD_SETCOUNT(&savedClientsReadable); i++) @@ -450,7 +497,7 @@ WaitForSomething(pClientsReady) pClientsReady[nready++] = client_index; } #ifndef WIN32 - clientsReadable.fds_bits[i] &= ~(((fd_mask)1) << curclient); + clientsReadable.fds_bits[i] &= ~(((fd_mask)1L) << curclient); } #else FD_CLR(curclient, &clientsReadable); @@ -476,11 +523,9 @@ ANYSET(src) } #endif + static void -DoTimer(timer, now, prev) - register OsTimerPtr timer; - CARD32 now; - OsTimerPtr *prev; +DoTimer(OsTimerPtr timer, CARD32 now, OsTimerPtr *prev) { CARD32 newTime; @@ -536,7 +581,7 @@ TimerSet(timer, flags, millis, func, arg) return timer; } for (prev = &timers; - *prev && millis > (*prev)->expires; + *prev && (int) ((*prev)->expires - millis) <= 0; prev = &(*prev)->next) ; timer->next = *prev; @@ -549,7 +594,6 @@ TimerForce(timer) register OsTimerPtr timer; { register OsTimerPtr *prev; - register CARD32 newTime; for (prev = &timers; *prev; prev = &(*prev)->next) { @@ -596,7 +640,7 @@ TimerCheck() { register CARD32 now = GetTimeInMillis(); - while (timers && timers->expires <= now) + while (timers && (int) (timers->expires - now) <= 0) DoTimer(timers, now, &timers); } @@ -605,7 +649,7 @@ TimerInit() { OsTimerPtr timer; - while (timer = timers) + while ((timer = timers)) { timers = timer->next; xfree(timer); diff --git a/os/access.c b/os/access.c index abca79e9d..f12c5c081 100644 --- a/os/access.c +++ b/os/access.c @@ -45,6 +45,7 @@ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ +/* $XFree86: xc/programs/Xserver/os/access.c,v 3.42 2002/07/07 20:11:52 herrb Exp $ */ #ifdef WIN32 #include <X11/Xwinsock.h> @@ -53,60 +54,111 @@ SOFTWARE. #include <stdio.h> #include <X11/Xtrans.h> #include <X11/Xauth.h> -#include "X.h" -#include "Xproto.h" +#include <X.h> +#include <Xproto.h> #include "misc.h" #include "site.h" #include <errno.h> - +#include <sys/types.h> #ifndef WIN32 -#ifdef ESIX -#include <lan/socket.h> -#else +#ifndef Lynx #include <sys/socket.h> +#else +#include <socket.h> #endif #include <sys/ioctl.h> #include <ctype.h> -#if defined(TCPCONN) || defined(STREAMSCONN) || defined(ISC) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(ISC) || defined(SCO) #include <netinet/in.h> -#endif /* TCPCONN || STREAMSCONN || ISC */ +#endif /* TCPCONN || STREAMSCONN || ISC || SCO */ #ifdef DNETCONN #include <netdnet/dn.h> #include <netdnet/dnetdb.h> #endif -#ifdef hpux + +#if defined(DGUX) +#include <sys/ioctl.h> +#include <sys/socket.h> +#include <net/if.h> +#include <netinet/in.h> +#include <ctype.h> +#include <sys/utsname.h> +#include <sys/stream.h> +#include <sys/stropts.h> +#include <sys/param.h> +#include <sys/sockio.h> +#endif + + +#if defined(hpux) || defined(QNX4) # include <sys/utsname.h> # ifdef HAS_IFREQ # include <net/if.h> # endif #else -#if defined(SVR4) || (defined(SYSV) && defined(i386)) +#if defined(SVR4) || (defined(SYSV) && defined(i386)) || defined(__GNU__) # include <sys/utsname.h> #endif #if defined(SYSV) && defined(i386) # include <sys/stream.h> +# ifdef ISC +# include <sys/stropts.h> +# include <sys/sioctl.h> +# endif /* ISC */ #endif -#ifdef ESIX -# include <lan/if.h> -#else +#ifdef __GNU__ +#undef SIOCGIFCONF +#include <netdb.h> +#else /*!__GNU__*/ # include <net/if.h> -#endif +#endif /*__GNU__ */ #endif /* hpux */ #ifdef SVR4 +#ifndef SCO #include <sys/sockio.h> #endif +#include <sys/stropts.h> +#endif -#ifdef ESIX -#include <lan/netdb.h> -#else #include <netdb.h> + +#ifdef CSRG_BASED +#include <sys/param.h> +#if (BSD >= 199103) +#define VARIABLE_IFREQ +#endif +#endif + +#ifdef BSD44SOCKETS +#ifndef VARIABLE_IFREQ +#define VARIABLE_IFREQ +#endif +#endif + +#ifdef HAS_GETIFADDRS +#include <ifaddrs.h> #endif #endif /* WIN32 */ +#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 + #define X_INCLUDE_NETDB_H #include <X11/Xos_r.h> @@ -127,29 +179,17 @@ Bool defeatAccessControl = FALSE; (length) == (host)->len &&\ !acmp (address, (host)->addr, length)) -static int ConvertAddr( -#if NeedFunctionPrototypes - struct sockaddr */*saddr*/, - int */*len*/, - pointer */*addr*/ -#endif -); +static int ConvertAddr(struct sockaddr */*saddr*/, + int */*len*/, + pointer */*addr*/); -static int CheckAddr( -#if NeedFunctionPrototypes - int /*family*/, - pointer /*pAddr*/, - unsigned /*length*/ -#endif -); +static int CheckAddr(int /*family*/, + pointer /*pAddr*/, + unsigned /*length*/); -static Bool NewHost( -#if NeedFunctionPrototypes - int /*family*/, - pointer /*addr*/, - int /*len*/ -#endif -); +static Bool NewHost(int /*family*/, + pointer /*addr*/, + int /*len*/); typedef struct _host { short family; @@ -175,7 +215,7 @@ static int UsingXdmcp = FALSE; */ void -EnableLocalHost () +EnableLocalHost (void) { if (!UsingXdmcp) { @@ -188,7 +228,7 @@ EnableLocalHost () * called when authorization is enabled to keep us secure */ void -DisableLocalHost () +DisableLocalHost (void) { HOST *self; @@ -203,13 +243,66 @@ DisableLocalHost () */ void -AccessUsingXdmcp () +AccessUsingXdmcp (void) { UsingXdmcp = TRUE; LocalHostEnabled = FALSE; } +#if ((defined(SVR4) && !defined(DGUX) && !defined(SCO325) && !defined(sun) && !defined(NCR)) || defined(ISC)) && defined(SIOCGIFCONF) + +/* Deal with different SIOCGIFCONF ioctl semantics on these OSs */ + +static int +ifioctl (int fd, int cmd, char *arg) +{ + struct strioctl ioc; + int ret; + + bzero((char *) &ioc, sizeof(ioc)); + ioc.ic_cmd = cmd; + ioc.ic_timout = 0; + if (cmd == SIOCGIFCONF) + { + ioc.ic_len = ((struct ifconf *) arg)->ifc_len; + ioc.ic_dp = ((struct ifconf *) arg)->ifc_buf; +#ifdef ISC + /* SIOCGIFCONF is somewhat brain damaged on ISC. The argument + * buffer must contain the ifconf structure as header. Ifc_req + * is also not a pointer but a one element array of ifreq + * structures. On return this array is extended by enough + * ifreq fields to hold all interfaces. The return buffer length + * is placed in the buffer header. + */ + ((struct ifconf *) ioc.ic_dp)->ifc_len = + ioc.ic_len - sizeof(struct ifconf); +#endif + } + else + { + ioc.ic_len = sizeof(struct ifreq); + ioc.ic_dp = arg; + } + ret = ioctl(fd, I_STR, (char *) &ioc); + if (ret >= 0 && cmd == SIOCGIFCONF) +#ifdef SVR4 + ((struct ifconf *) arg)->ifc_len = ioc.ic_len; +#endif +#ifdef ISC + { + ((struct ifconf *) arg)->ifc_len = + ((struct ifconf *)ioc.ic_dp)->ifc_len; + ((struct ifconf *) arg)->ifc_buf = + (caddr_t)((struct ifconf *)ioc.ic_dp)->ifc_req; + } +#endif + return(ret); +} +#else /* Case DGUX, sun, SCO325 NCR and others */ +#define ifioctl ioctl +#endif /* ((SVR4 && !DGUX !sun !SCO325 !NCR) || ISC) && SIOCGIFCONF */ + /* * DefineSelf (fd): * @@ -231,8 +324,7 @@ AccessUsingXdmcp () #include <netinet/in_var.h> void -DefineSelf (fd) - int fd; +DefineSelf (int fd) { /* * The Wolongong drivers used by NCR SVR4/MP-RAS don't understand the @@ -249,7 +341,7 @@ DefineSelf (fd) int family, len; if ((fd = open ("/dev/ip", O_RDWR, 0 )) < 0) - Error ("Getting interface configuration"); + Error ("Getting interface configuration (1)"); /* Indicate that we want to start at the begining */ ifnet.ib_next = (struct ipb *) 1; @@ -264,7 +356,7 @@ DefineSelf (fd) if (ioctl (fd, (int) I_STR, (char *) &str) < 0) { close (fd); - Error ("Getting interface configuration"); + Error ("Getting interface configuration (2)"); } ifaddr.ia_next = (struct in_ifaddr *) ifnet.if_addrlist; @@ -276,7 +368,7 @@ DefineSelf (fd) if (ioctl (fd, (int) I_STR, (char *) &str) < 0) { close (fd); - Error ("Getting interface configuration"); + Error ("Getting interface configuration (3)"); } len = sizeof(struct sockaddr_in); @@ -354,12 +446,11 @@ DefineSelf (fd) #else /* WINTCP */ -#if !defined(SIOCGIFCONF) || (defined (hpux) && ! defined (HAS_IFREQ)) +#if !defined(SIOCGIFCONF) || (defined (hpux) && ! defined (HAS_IFREQ)) || defined(QNX4) void -DefineSelf (fd) - int fd; +DefineSelf (int fd) { -#if !defined(TCPCONN) && !defined(UNIXCONN) +#if !defined(TCPCONN) && !defined(STREAMSCONN) && !defined(UNIXCONN) && !defined(MNX_TCPCONN) return; #else register int n; @@ -368,12 +459,7 @@ DefineSelf (fd) int family; register HOST *host; -#if defined(__386BSD__) || defined(__NetBSD__) || defined(__FreeBSD__) \ - || defined(WIN32) - char name[100]; -#else struct utsname name; -#endif register struct hostent *hp; union { @@ -383,23 +469,26 @@ DefineSelf (fd) struct sockaddr_in *inetaddr; struct sockaddr_in broad_addr; +#ifdef XTHREADS_NEEDS_BYNAMEPARAMS _Xgethostbynameparams hparams; +#endif -#if defined(__386BSD__) || defined(__NetBSD__) || defined(__FreeBSD__) \ - || defined(WIN32) - if (gethostname (name, sizeof name) < 0) - hp = NULL; - else - hp = _XGethostbyname(name, hparams); -#else /* Why not use gethostname()? Well, at least on my system, I've had to * make an ugly kernel patch to get a name longer than 8 characters, and * uname() lets me access to the whole string (it smashes release, you * see), whereas gethostname() kindly truncates it for me. */ +#ifndef QNX4 uname(&name); - hp = _XGethostbyname(name.nodename, hparams); +#else + /* QNX4's uname returns node number in name.nodename, not the hostname + have to overwrite it */ + char hname[1024]; + gethostname(hname, 1024); + name.nodename = hname; #endif + + hp = _XGethostbyname(name.nodename, hparams); if (hp != NULL) { saddr.sa.sa_family = hp->h_addrtype; @@ -463,22 +552,44 @@ DefineSelf (fd) selfhosts = host; } } -#endif /* !TCPCONN && !UNIXCONN */ +#endif /* !TCPCONN && !STREAMSCONN && !UNIXCONN && !MNX_TCPCONN */ } #else + +#ifdef VARIABLE_IFREQ +#define ifr_size(p) (sizeof (struct ifreq) + \ + (p->ifr_addr.sa_len > sizeof (p->ifr_addr) ? \ + p->ifr_addr.sa_len - sizeof (p->ifr_addr) : 0)) +#define ifraddr_size(a) (a.sa_len) +#else +#ifdef QNX4 +#define ifr_size(p) (p->ifr_addr.sa_len + IFNAMSIZ) +#define ifraddr_size(a) (a.sa_len) +#else +#define ifr_size(p) (sizeof (struct ifreq)) +#define ifraddr_size(a) (sizeof (a)) +#endif +#endif + +#ifdef DEF_SELF_DEBUG +#include <arpa/inet.h> +#endif + void -DefineSelf (fd) - int fd; +DefineSelf (int fd) { - char buf[2048]; +#ifndef HAS_GETIFADDRS + char buf[2048], *cp, *cplim; struct ifconf ifc; - register int n; + register struct ifreq *ifr; +#else + struct ifaddrs * ifap, *ifr; +#endif int len; unsigned char * addr; int family; register HOST *host; - register struct ifreq *ifr; #ifdef DNETCONN struct dn_naddr *dnaddr = getnodeadd(); @@ -508,23 +619,25 @@ DefineSelf (fd) } } } -#endif +#endif /* DNETCONN */ +#ifndef HAS_GETIFADDRS ifc.ifc_len = sizeof (buf); ifc.ifc_buf = buf; - if (ioctl (fd, (int) SIOCGIFCONF, (pointer) &ifc) < 0) - Error ("Getting interface configuration"); - for (ifr = ifc.ifc_req -#ifdef BSD44SOCKETS - ; (char *)ifr < ifc.ifc_buf + ifc.ifc_len; - ifr = (struct ifreq *)((char *)ifr + sizeof (struct ifreq) + - (ifr->ifr_addr.sa_len > sizeof (ifr->ifr_addr) ? - ifr->ifr_addr.sa_len - sizeof (ifr->ifr_addr) : 0)) + if (ifioctl (fd, SIOCGIFCONF, (pointer) &ifc) < 0) + Error ("Getting interface configuration (4)"); + +#ifdef ISC +#define IFC_IFC_REQ (struct ifreq *) ifc.ifc_buf #else - , n = ifc.ifc_len / sizeof (struct ifreq); --n >= 0; ifr++ -#endif - ) +#define IFC_IFC_REQ ifc.ifc_req +#endif /* ISC */ + + cplim = (char *) IFC_IFC_REQ + ifc.ifc_len; + + for (cp = (char *) IFC_IFC_REQ; cp < cplim; cp += ifr_size (ifr)) { - len = sizeof(ifr->ifr_addr); + ifr = (struct ifreq *) cp; + len = ifraddr_size (ifr->ifr_addr); #ifdef DNETCONN /* * DECnet was handled up above. @@ -535,6 +648,11 @@ DefineSelf (fd) family = ConvertAddr (&ifr->ifr_addr, &len, (pointer *)&addr); if (family == -1 || family == FamilyLocal) continue; +#ifdef DEF_SELF_DEBUG + if (family == FamilyInternet) + ErrorF("Xserver: DefineSelf(): ifname = %s, addr = %d.%d.%d.%d\n", + ifr->ifr_name, addr[0], addr[1], addr[2], addr[3]); +#endif /* DEF_SELF_DEBUG */ for (host = selfhosts; host && !addrEqual (family, addr, len, host); host = host->next) @@ -578,13 +696,13 @@ DefineSelf (fd) struct ifreq broad_req; broad_req = *ifr; - if (ioctl (fd, SIOCGIFFLAGS, (char *) &broad_req) != -1 && + if (ifioctl (fd, SIOCGIFFLAGS, (char *) &broad_req) != -1 && (broad_req.ifr_flags & IFF_BROADCAST) && (broad_req.ifr_flags & IFF_UP) ) { broad_req = *ifr; - if (ioctl (fd, SIOCGIFBRDADDR, &broad_req) != -1) + if (ifioctl (fd, SIOCGIFBRDADDR, &broad_req) != -1) broad_addr = broad_req.ifr_addr; else continue; @@ -592,11 +710,84 @@ DefineSelf (fd) else continue; } -#endif +#endif /* SIOCGIFBRDADDR */ +#ifdef DEF_SELF_DEBUG + ErrorF("Xserver: DefineSelf(): ifname = %s, baddr = %s\n", + ifr->ifr_name, + inet_ntoa(((struct sockaddr_in *) &broad_addr)->sin_addr)); +#endif /* DEF_SELF_DEBUG */ XdmcpRegisterBroadcastAddress ((struct sockaddr_in *) &broad_addr); } -#endif +#endif /* XDMCP */ + } +#else /* HAS_GETIFADDRS */ + if (getifaddrs(&ifap) < 0) { + ErrorF("Warning: getifaddrs returns %s\n", strerror(errno)); + return; } + for (ifr = ifap; ifr != NULL; ifr = ifr->ifa_next) { +#ifdef DNETCONN + if (ifr->ifa_addr.sa_family == AF_DECnet) + continue; +#endif /* DNETCONN */ + family = ConvertAddr(ifr->ifa_addr, &len, (pointer *)&addr); + if (family == -1 || family == FamilyLocal) + continue; +#ifdef DEF_SELF_DEBUG + if (family == FamilyInternet) + ErrorF("Xserver: DefineSelf(): ifname = %s, addr = %d.%d.%d.%d\n", + ifr->ifa_name, addr[0], addr[1], addr[2], addr[3]); +#endif /* DEF_SELF_DEBUG */ + for (host = selfhosts; + host != NULL && !addrEqual(family, addr, len, host); + host = host->next) + ; + if (host != NULL) + continue; + MakeHost(host, len); + if (host != NULL) { + host->family = family; + host->len = len; + acopy(addr, host->addr, len); + host->next = selfhosts; + selfhosts = host; + } +#ifdef XDMCP + { + struct sockaddr broad_addr; + /* + * If this isn't an Internet Address, don't register it. + */ + if (family != FamilyInternet) + continue; + /* + * ignore 'localhost' entries as they're not usefule + * on the other end of the wire + */ + if (len == 4 && + addr[0] == 127 && addr[1] == 0 && + addr[2] == 0 && addr[2] == 1) + continue; + XdmcpRegisterConnection(family, (char *)addr, len); + if ((ifr->ifa_flags & IFF_BROADCAST) && + (ifr->ifa_flags & IFF_UP)) + broad_addr = *ifr->ifa_broadaddr; + else + continue; +#ifdef DEF_SELF_DEBUG + ErrorF("Xserver: DefineSelf(): ifname = %s, baddr = %s\n", + ifr->ifa_name, + inet_ntoa(((struct sockaddr_in *) &broad_addr)->sin_addr)); +#endif /* DEF_SELF_DEBUG */ + XdmcpRegisterBroadcastAddress((struct sockaddr_in *) + &broad_addr); + } +#endif /* XDMCP */ + + } /* for */ + freeifaddrs(ifap); +#endif /* HAS_GETIFADDRS */ + /* * add something of FamilyLocalHost */ @@ -621,9 +812,7 @@ DefineSelf (fd) #ifdef XDMCP void -AugmentSelf(from, len) - pointer from; - int len; +AugmentSelf(pointer from, int len) { int family; pointer addr; @@ -649,7 +838,7 @@ AugmentSelf(from, len) #endif void -AddLocalHosts () +AddLocalHosts (void) { HOST *self; @@ -657,25 +846,21 @@ AddLocalHosts () (void) NewHost (self->family, self->addr, self->len); } -static char* etcx_hosts = NULL; - /* Reset access control list to initial hosts */ void -ResetHosts (display) - char *display; +ResetHosts (char *display) { register HOST *host; char lhostname[120], ohostname[120]; char *hostname = ohostname; + char fname[PATH_MAX + 1]; int fnamelen; - char* etcstr = "/etc/X"; - char* dothoststr = ".hosts"; FILE *fd; char *ptr; int i, hostlen; union { struct sockaddr sa; -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) struct sockaddr_in in; #endif /* TCPCONN || STREAMSCONN */ #ifdef DNETCONN @@ -690,42 +875,41 @@ ResetHosts (display) krb5_principal princ; krb5_data kbuf; #endif - int family; + int family = 0; pointer addr; int len; register struct hostent *hp; AccessEnabled = defeatAccessControl ? FALSE : DEFAULT_ACCESS_CONTROL; LocalHostEnabled = FALSE; - while (host = validhosts) + while ((host = validhosts) != 0) { validhosts = host->next; FreeHost (host); } - if (etcx_hosts == NULL) { - fnamelen = strlen (display); - fnamelen += strlen (etcstr); - fnamelen += strlen (dothoststr); - etcx_hosts = (char*) xalloc (fnamelen + 1); /* A memory leak? No! */ - /* eventually could use snprintf, when more systems have it */ - sprintf (etcx_hosts, "%s%s%s", etcstr, display, dothoststr); -#ifndef WIN32 -#ifdef PATH_MAX - if (fnamelen > PATH_MAX) { - /* punish stupid hackers */ - strcpy (etcx_hosts, "/dev/zero"); - } -#endif -#endif - } - if (fd = fopen (etcx_hosts, "r")) +#define ETC_HOST_PREFIX "/etc/X" +#define ETC_HOST_SUFFIX ".hosts" + fnamelen = strlen(ETC_HOST_PREFIX) + strlen(ETC_HOST_SUFFIX) + + strlen(display) + 1; + if (fnamelen > sizeof(fname)) + FatalError("Display name `%s' is too long\n", display); + sprintf(fname, ETC_HOST_PREFIX "%s" ETC_HOST_SUFFIX, display); +#ifdef __UNIXOS2__ + strcpy(fname, (char*)__XOS2RedirRoot(fname)); +#endif /* __UNIXOS2__ */ + + if ((fd = fopen (fname, "r")) != 0) { while (fgets (ohostname, sizeof (ohostname), fd)) { if (*ohostname == '#') continue; - if (ptr = strchr(ohostname, '\n')) + if ((ptr = strchr(ohostname, '\n')) != 0) + *ptr = 0; +#ifdef __UNIXOS2__ + if ((ptr = strchr(ohostname, '\r')) != 0) *ptr = 0; +#endif hostlen = strlen(ohostname) + 1; for (i = 0; i < hostlen; i++) lhostname[i] = tolower(ohostname[i]); @@ -735,7 +919,7 @@ ResetHosts (display) family = FamilyLocalHost; NewHost(family, "", 0); } -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) else if (!strncmp("inet:", lhostname, 5)) { family = FamilyInternet; @@ -807,14 +991,16 @@ ResetHosts (display) } else #endif /* SECURE_RPC */ -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) { +#ifdef XTHREADS_NEEDS_BYNAMEPARAMS _Xgethostbynameparams hparams; +#endif /* host name */ - if (family == FamilyInternet && - (hp = _XGethostbyname(hostname, hparams)) || - (hp = _XGethostbyname(hostname, hparams))) + if ((family == FamilyInternet && + ((hp = _XGethostbyname(hostname, hparams)) != 0)) || + ((hp = _XGethostbyname(hostname, hparams)) != 0)) { saddr.sa.sa_family = hp->h_addrtype; len = sizeof(saddr.sa); @@ -840,8 +1026,7 @@ ResetHosts (display) } /* Is client on the local host */ -Bool LocalClient(client) - ClientPtr client; +Bool LocalClient(ClientPtr client) { int alen, family, notused; Xtransaddr *from = NULL; @@ -886,9 +1071,57 @@ Bool LocalClient(client) return FALSE; } +/* + * Return the uid and gid of a connected local client + * or the uid/gid for nobody those ids cannot be determinded + * + * Used by XShm to test access rights to shared memory segments + */ +int +LocalClientCred(ClientPtr client, int *pUid, int *pGid) +{ + int fd; + XtransConnInfo ci; +#ifdef HAS_GETPEEREID + uid_t uid; + gid_t gid; +#elif defined(SO_PEERCRED) + struct ucred peercred; + socklen_t so_len = sizeof(peercred); +#endif + + if (client == NULL) + return -1; + ci = ((OsCommPtr)client->osPrivate)->trans_conn; + /* We can only determine peer credentials for Unix domain sockets */ + if (!_XSERVTransIsLocal(ci)) { + return -1; + } + fd = _XSERVTransGetConnectionNumber(ci); +#ifdef HAS_GETPEEREID + if (getpeereid(fd, &uid, &gid) == -1) + return -1; + if (pUid != NULL) + *pUid = uid; + if (pGid != NULL) + *pGid = gid; + return 0; +#elif defined(SO_PEERCRED) + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1) + return -1; + if (pUid != NULL) + *pUid = peercred.uid; + if (pGid != NULL) + *pGid = peercred.gid; + return 0; +#else + /* No system call available to get the credentials of the peer */ + return -1; +#endif +} + static Bool -AuthorizedClient(client) - ClientPtr client; +AuthorizedClient(ClientPtr client) { if (!client || defeatAccessControl) return TRUE; @@ -899,11 +1132,10 @@ AuthorizedClient(client) * called from the dispatcher */ int -AddHost (client, family, length, pAddr) - ClientPtr client; - int family; - unsigned length; /* of bytes in pAddr */ - pointer pAddr; +AddHost (ClientPtr client, + int family, + unsigned length, /* of bytes in pAddr */ + pointer pAddr) { int len; @@ -945,10 +1177,12 @@ AddHost (client, family, length, pAddr) } Bool -ForEachHostInFamily (family, func, closure) - int family; - Bool (*func)(); - pointer closure; +ForEachHostInFamily (int family, + Bool (*func)( + unsigned char * /* addr */, + short /* len */, + pointer /* closure */), + pointer closure) { HOST *host; @@ -961,10 +1195,9 @@ ForEachHostInFamily (family, func, closure) /* Add a host to the access control list. This is the internal interface * called when starting or resetting the server */ static Bool -NewHost (family, addr, len) - int family; - pointer addr; - int len; +NewHost (int family, + pointer addr, + int len) { register HOST *host; @@ -987,11 +1220,11 @@ NewHost (family, addr, len) /* Remove a host from the access control list */ int -RemoveHost (client, family, length, pAddr) - ClientPtr client; - int family; - unsigned length; /* of bytes in pAddr */ - pointer pAddr; +RemoveHost ( + ClientPtr client, + int family, + unsigned length, /* of bytes in pAddr */ + pointer pAddr) { int len; register HOST *host, **prev; @@ -1041,11 +1274,11 @@ RemoveHost (client, family, length, pAddr) /* Get all hosts in the access control list */ int -GetHosts (data, pnHosts, pLen, pEnabled) - pointer *data; - int *pnHosts; - int *pLen; - BOOL *pEnabled; +GetHosts ( + pointer *data, + int *pnHosts, + int *pLen, + BOOL *pEnabled) { int len; register int n = 0; @@ -1087,16 +1320,16 @@ GetHosts (data, pnHosts, pLen, pEnabled) /*ARGSUSED*/ static int -CheckAddr (family, pAddr, length) - int family; - pointer pAddr; - unsigned length; +CheckAddr ( + int family, + pointer pAddr, + unsigned length) { int len; switch (family) { -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(AMTCPCONN) || defined(MNX_TCPCONN) case FamilyInternet: if (length == sizeof (struct in_addr)) len = length; @@ -1128,9 +1361,10 @@ CheckAddr (family, pAddr, length) /* Check if a host is not in the access control list. * Returns 1 if host is invalid, 0 if we've found it. */ -InvalidHost (saddr, len) - register struct sockaddr *saddr; - int len; +int +InvalidHost ( + register struct sockaddr *saddr, + int len) { int family; pointer addr; @@ -1171,21 +1405,21 @@ InvalidHost (saddr, len) } static int -ConvertAddr (saddr, len, addr) - register struct sockaddr *saddr; - int *len; - pointer *addr; +ConvertAddr ( + register struct sockaddr *saddr, + int *len, + pointer *addr) { if (*len == 0) return (FamilyLocal); switch (saddr->sa_family) { case AF_UNSPEC: -#if defined(UNIXCONN) || defined(LOCALCONN) +#if defined(UNIXCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) case AF_UNIX: #endif return FamilyLocal; -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) case AF_INET: *len = sizeof (struct in_addr); *addr = (pointer) &(((struct sockaddr_in *) saddr)->sin_addr); @@ -1213,9 +1447,9 @@ ConvertAddr (saddr, len, addr) } int -ChangeAccessControl(client, fEnabled) - ClientPtr client; - int fEnabled; +ChangeAccessControl( + ClientPtr client, + int fEnabled) { if (!AuthorizedClient(client)) return BadAccess; @@ -1225,8 +1459,7 @@ ChangeAccessControl(client, fEnabled) /* returns FALSE if xhost + in effect, else TRUE */ int -GetAccessControl() +GetAccessControl(void) { return AccessEnabled; } - @@ -26,6 +26,7 @@ other dealings in this Software without prior written authorization from The Open Group. */ +/* $XFree86: xc/programs/Xserver/os/auth.c,v 1.12 2002/12/09 02:56:03 dawes Exp $ */ /* * authorization hooks for the server @@ -35,9 +36,10 @@ from The Open Group. #ifdef K5AUTH # include <krb5/krb5.h> #endif -# include "X.h" -# include "Xauth.h" +# 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> @@ -52,50 +54,17 @@ from The Open Group. struct protocol { unsigned short name_length; char *name; - int (*Add)(); /* new authorization data */ - XID (*Check)(); /* verify client authorization data */ - int (*Reset)(); /* delete all authorization data entries */ - XID (*ToID)(); /* convert cookie to ID */ - int (*FromID)(); /* convert ID to cookie */ - int (*Remove)(); /* remove a specific cookie */ + 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 - XID (*Generate)(); + AuthGenCFunc Generate; #endif }; -extern int MitAddCookie (); -extern XID MitCheckCookie (); -extern int MitResetCookie (); -extern XID MitToID (); -extern int MitFromID (), MitRemoveCookie (); -extern XID MitGenerateCookie(); - -#ifdef HASXDMAUTH -extern int XdmAddCookie (); -extern XID XdmCheckCookie (); -extern int XdmResetCookie (); -extern XID XdmToID (); -extern int XdmFromID (), XdmRemoveCookie (); -#endif - -#ifdef SECURE_RPC -extern int SecureRPCAdd(); -extern XID SecureRPCCheck(); -extern int SecureRPCReset(); -extern XID SecureRPCToID(); -extern int SecureRPCFromID(), SecureRPCRemove(); -#endif - -#ifdef K5AUTH -extern int K5Add(); -extern XID K5Check(); -extern int K5Reset(); -extern XID K5ToID(); -extern int K5FromID(), K5Remove(); -#endif - -extern XID AuthSecurityCheck(); - static struct protocol protocols[] = { { (unsigned short) 18, "MIT-MAGIC-COOKIE-1", MitAddCookie, MitCheckCookie, MitResetCookie, @@ -154,27 +123,39 @@ static char *authorization_file = (char *)NULL; static Bool ShouldLoadAuth = TRUE; void -InitAuthorization (file_name) -char *file_name; +InitAuthorization (char *file_name) { authorization_file = file_name; } int -LoadAuthorization () +LoadAuthorization (void) { FILE *f; Xauth *auth; int i; int count = 0; +#if !defined(WIN32) && !defined(__UNIXOS2__) + char *buf; +#endif ShouldLoadAuth = FALSE; if (!authorization_file) return 0; +#if !defined(WIN32) && !defined(__UNIXOS2__) + buf = xalloc (strlen(authorization_file) + 5); + if (!buf) + return -1; + sprintf (buf, "cat %s", authorization_file); + f = Popen (buf, "r"); + xfree (buf); +#else f = fopen (authorization_file, "r"); +#endif if (!f) - return 0; - while (auth = XauReadAuth (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 && @@ -187,7 +168,13 @@ LoadAuthorization () } XauDisposeAuth (auth); } + +#if !defined(WIN32) && !defined(__UNIXOS2__) + if (Pclose (f) != 0) + return -1; +#else fclose (f); +#endif return count; } @@ -197,7 +184,7 @@ LoadAuthorization () * schemes supported by the display */ void -RegisterAuthorizations () +RegisterAuthorizations (void) { int i; @@ -208,17 +195,18 @@ RegisterAuthorizations () #endif XID -CheckAuthorization (name_length, name, data_length, data, client, reason) - unsigned int name_length; - char *name; - unsigned int data_length; - char *data; - ClientPtr client; - char **reason; /* failure message. NULL for default msg */ +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)) { @@ -234,24 +222,45 @@ CheckAuthorization (name_length, name, data_length, data, client, reason) } if (ShouldLoadAuth) { - if (LoadAuthorization()) + 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 */ - else + loaded = TRUE; + } + else if (loadauth == 0 || !loaded) EnableLocalHost (); } - if (name_length) + 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 () +ResetAuthorization (void) { int i; @@ -262,11 +271,11 @@ ResetAuthorization () } XID -AuthorizationToID (name_length, name, data_length, data) -unsigned short name_length; -char *name; -unsigned short data_length; -char *data; +AuthorizationToID ( + unsigned short name_length, + char *name, + unsigned short data_length, + char *data) { int i; @@ -282,12 +291,12 @@ char *data; } int -AuthorizationFromID (id, name_lenp, namep, data_lenp, datap) -XID id; -unsigned short *name_lenp; -char **namep; -unsigned short *data_lenp; -char **datap; +AuthorizationFromID ( + XID id, + unsigned short *name_lenp, + char **namep, + unsigned short *data_lenp, + char **datap) { int i; @@ -303,11 +312,11 @@ char **datap; } int -RemoveAuthorization (name_length, name, data_length, data) -unsigned short name_length; -char *name; -unsigned short data_length; -char *data; +RemoveAuthorization ( + unsigned short name_length, + char *name, + unsigned short data_length, + char *data) { int i; @@ -323,11 +332,7 @@ char *data; } int -AddAuthorization (name_length, name, data_length, data) -unsigned int name_length; -char *name; -unsigned int data_length; -char *data; +AddAuthorization (unsigned name_length, char *name, unsigned data_length, char *data) { int i; @@ -345,14 +350,13 @@ char *data; #ifdef XCSECURITY XID -GenerateAuthorization(name_length, name, data_length, data, - data_length_return, data_return) -unsigned int name_length; -char *name; -unsigned int data_length; -char *data; -unsigned int *data_length_return; -char **data_return; +GenerateAuthorization( + unsigned name_length, + char *name, + unsigned data_length, + char *data, + unsigned *data_length_return, + char **data_return) { int i; @@ -375,23 +379,20 @@ char **data_return; static unsigned long int next = 1; static int -xdm_rand() +xdm_rand(void) { next = next * 1103515245 + 12345; return (unsigned int)(next/65536) % 32768; } static void -xdm_srand(seed) - unsigned int seed; +xdm_srand(unsigned int seed) { next = seed; } void -GenerateRandomData (len, buf) -int len; -char *buf; +GenerateRandomData (int len, char *buf) { static int seed; int value; diff --git a/os/connection.c b/os/connection.c index 7c4b9fef3..46cfd4dfb 100644 --- a/os/connection.c +++ b/os/connection.c @@ -45,6 +45,7 @@ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ +/* $XFree86: xc/programs/Xserver/os/connection.c,v 3.56 2002/05/31 18:46:05 dawes Exp $ */ /***************************************************************** * Stuff to create connections --- OS dependent * @@ -69,43 +70,78 @@ SOFTWARE. #include "Xproto.h" #include <X11/Xtrans.h> #include <errno.h> -#ifdef X_NOT_STDC_ENV -extern int errno; -#endif - #include <signal.h> #include <stdio.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> -# ifndef hpux +# include <arpa/inet.h> +# if !defined(hpux) # ifdef apollo # ifndef NO_TCP_H # include <netinet/tcp.h> # endif # else -# include <netinet/tcp.h> +# ifdef CSRG_BASED +# include <sys/param.h> +# endif +# ifndef __UNIXOS2__ +# include <netinet/tcp.h> +# endif # endif # endif #endif +#ifdef AMTCPCONN +#include <server/ip/types.h> +#include <server/ip/gen/in.h> +#include <server/ip/gen/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 <X11/Xpoll.h> #include "osdep.h" +#include <X11/Xpoll.h> #include "opaque.h" #include "dixstruct.h" #ifdef XAPPGROUP @@ -116,6 +152,8 @@ extern int errno; #include "extensions/security.h" #endif #ifdef LBX +#include "colormapst.h" +#include "propertyst.h" #include "lbxserve.h" #endif @@ -129,7 +167,6 @@ extern int errno; #include <netdnet/dn.h> #endif /* DNETCONN */ -extern char *display; /* The display number */ int lastfdesc; /* maximum file descriptor */ fd_set WellKnownConnections; /* Listener mask */ @@ -140,16 +177,13 @@ 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 */ -#ifndef _SC_OPEN_MAX -int MaxClients = MAXSOCKS; /* use MAXSOCKS if sysconf(_SC_OPEN_MAX) is not supported */ -#else int MaxClients = 0; -#endif 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 */ +char *protNoListen; /* don't listen on this protocol */ static Pid_t ParentProcess; static Bool debug_conns = FALSE; @@ -161,9 +195,8 @@ static fd_set SavedAllSockets; static fd_set SavedClientsWithInput; int GrabInProgress = 0; -#ifndef WIN32 -int ConnectionTranslation[MAXSOCKS]; -#else +int *ConnectionTranslation = NULL; +#if defined(WIN32) /* SPAM ALERT !!! * 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. @@ -171,15 +204,12 @@ int ConnectionTranslation[MAXSOCKS]; * as a direct index should really be implemented for NT. */ #define MAXFD 500 -int ConnectionTranslation[MAXFD]; #endif XtransConnInfo *ListenTransConns = NULL; int *ListenTransFds = NULL; int ListenTransCount; -extern int auditTrailLevel; - static void ErrorConnMax( #if NeedFunctionPrototypes XtransConnInfo /* trans_conn */ @@ -201,7 +231,6 @@ void CloseDownFileDescriptor( #ifdef LBX extern int LbxFlushClient(); -extern void LbxCloseClient(); #endif /* LBX */ static XtransConnInfo @@ -219,10 +248,64 @@ lookup_trans_conn (fd) return (NULL); } -#ifdef XDMCP -void XdmcpOpenDisplay(), XdmcpInit(), XdmcpReset(), XdmcpCloseDisplay(); +/* Set MaxClients and lastfdesc, and allocate ConnectionTranslation */ + +void +InitConnectionLimits() +{ + 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 + ConnectionTranslation = (int *)xnfalloc(sizeof(int)*(MAXFD)); +#endif +} + + /***************** * CreateWellKnownSockets * At initialization, create the sockets to listen on for new clients. @@ -231,7 +314,7 @@ void XdmcpOpenDisplay(), XdmcpInit(), XdmcpReset(), XdmcpCloseDisplay(); void CreateWellKnownSockets() { - int request, i; + int i; int partial; char port[20]; @@ -240,33 +323,22 @@ CreateWellKnownSockets() FD_ZERO(&LastSelectMask); FD_ZERO(&ClientsWithInput); -#ifndef WIN32 - for (i=0; i<MAXSOCKS; i++) ConnectionTranslation[i] = 0; +#if !defined(WIN32) + for (i=0; i<MaxClients; i++) ConnectionTranslation[i] = 0; #else for (i=0; i<MAXFD; i++) ConnectionTranslation[i] = 0; #endif -#ifdef XNO_SYSCONF /* should only be on FreeBSD 1.x and NetBSD 0.x */ -#undef _SC_OPEN_MAX -#endif -#ifdef _SC_OPEN_MAX - lastfdesc = sysconf(_SC_OPEN_MAX) - 1; -#else -#ifdef hpux - lastfdesc = _NFILE - 1; -#else - lastfdesc = getdtablesize() - 1; -#endif -#endif - - if (lastfdesc > MAXSOCKS) - { - lastfdesc = MAXSOCKS; - } FD_ZERO (&WellKnownConnections); sprintf (port, "%d", atoi (display)); + if (protNoListen) + if (_XSERVTransNoListen(protNoListen)) + { + FatalError ("Failed to disable listen for %s", protNoListen); + } + if ((_XSERVTransMakeAllCOTSServerListeners (port, &partial, &ListenTransCount, &ListenTransConns) >= 0) && (ListenTransCount >= 1)) @@ -277,7 +349,7 @@ CreateWellKnownSockets() } else { - ListenTransFds = (int *) malloc (ListenTransCount * sizeof (int)); + ListenTransFds = (int *) xalloc (ListenTransCount * sizeof (int)); for (i = 0; i < ListenTransCount; i++) { @@ -296,7 +368,7 @@ CreateWellKnownSockets() if (!XFD_ANYSET (&WellKnownConnections)) FatalError ("Cannot establish any listening sockets - Make sure an X server isn't already running"); -#ifndef WIN32 +#if !defined(WIN32) OsSignal (SIGPIPE, SIG_IGN); OsSignal (SIGHUP, AutoResetServer); #endif @@ -319,12 +391,12 @@ CreateWellKnownSockets() * in the second case, the signal will be quite * useful */ -#ifndef WIN32 +#if !defined(WIN32) if (OsSignal (SIGUSR1, SIG_IGN) == SIG_IGN) RunFromSmartParent = TRUE; ParentProcess = getppid (); if (RunFromSmartParent) { - if (ParentProcess > 0) { + if (ParentProcess > 1) { kill (ParentProcess, SIGUSR1); } } @@ -380,9 +452,9 @@ ResetWellKnownSockets () /* * See above in CreateWellKnownSockets about SIGUSR1 */ -#ifndef WIN32 +#if !defined(WIN32) if (RunFromSmartParent) { - if (ParentProcess > 0) { + if (ParentProcess > 1) { kill (ParentProcess, SIGUSR1); } } @@ -395,6 +467,15 @@ ResetWellKnownSockets () #endif } +void +CloseWellKnownConnections() +{ + int i; + + for (i = 0; i < ListenTransCount; i++) + _XSERVTransClose (ListenTransConns[i]); +} + static void AuthAudit (client, letin, saddr, len, proto_n, auth_proto, auth_id) ClientPtr client; @@ -418,16 +499,16 @@ AuthAudit (client, letin, saddr, len, proto_n, auth_proto, auth_id) switch (saddr->sa_family) { case AF_UNSPEC: -#if defined(UNIXCONN) || defined(LOCALCONN) +#if defined(UNIXCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) case AF_UNIX: #endif strcpy(out, "local host"); break; -#if defined(TCPCONN) || defined(STREAMSCONN) +#if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) case AF_INET: sprintf(out, "IP %s port %d", inet_ntoa(((struct sockaddr_in *) saddr)->sin_addr), - ((struct sockaddr_in *) saddr)->sin_port); + ntohs(((struct sockaddr_in *) saddr)->sin_port)); break; #endif #ifdef DNETCONN @@ -436,6 +517,16 @@ AuthAudit (client, letin, saddr, len, proto_n, auth_proto, auth_id) dnet_ntoa(&((struct sockaddr_dn *) saddr)->sdn_add)); break; #endif +#ifdef AMRPCCONN + case FamilyAmoeba: + sprintf(addr, "AM %s", saddr); + break; +#endif +#if defined(AMTCPCONN) && !(defined(TCPCONN) || defined(STREAMSCONN)) + case AF_INET: + sprintf(addr, "AMIP %s", inet_ntoa(*((ipaddr_t *) saddr))); + break; +#endif default: strcpy(out, "unknown address"); } @@ -491,7 +582,7 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) char *reason = NULL; XtransConnInfo trans_conn; int restore_trans_conn = 0; - ClientPtr lbxpc; + ClientPtr lbxpc = NULL; priv = (OsCommPtr)client->osPrivate; trans_conn = priv->trans_conn; @@ -538,24 +629,7 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) string_n, auth_string, client, &reason); #ifdef LBX - if (restore_trans_conn) { - /* - * Restore client's trans_conn state - */ - priv = (OsCommPtr)client->osPrivate; - priv->trans_conn = NULL; - - trans_conn = NULL; - } - -#endif - -#ifdef LBX - if (!trans_conn) { - /* - * Use the proxy's trans_conn - */ - trans_conn = ((OsCommPtr)lbxpc->osPrivate)->trans_conn; + if (! priv->trans_conn) { if (auth_id == (XID) ~0L && !GetAccessControl()) auth_id = ((OsCommPtr)lbxpc->osPrivate)->auth_id; #ifdef XCSECURITY @@ -576,9 +650,16 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) _XSERVTransGetPeerAddr (trans_conn, &family, &fromlen, &from) != -1) { +#ifdef AMRPCCONN + /* Amoeba RPC connections are already checked by the capability. */ + if (family == FamilyAmoeba) { + auth_id = (XID) 0; + } + else +#endif if ( #ifdef LBX - !priv->trans_conn || + !trans_conn || #endif InvalidHost ((struct sockaddr *) from, fromlen)) AuthAudit(client, FALSE, (struct sockaddr *) from, @@ -592,14 +673,23 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) proto_n, auth_proto, auth_id); } - free ((char *) from); + xfree ((char *) from); } - if (auth_id == (XID) ~0L) + 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) { @@ -609,7 +699,7 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) AuthAudit(client, TRUE, (struct sockaddr *) from, fromlen, proto_n, auth_proto, auth_id); - free ((char *) from); + xfree ((char *) from); } } priv->auth_id = auth_id; @@ -629,6 +719,11 @@ ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) * 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); } @@ -697,6 +792,12 @@ AllocNewConnection (trans_conn, fd, conn_time) FD_SET(fd, &AllSockets); } } + +#ifdef DEBUG + ErrorF("AllocNewConnection: client index = %d, socket fd = %d\n", + client->index, fd); +#endif + return client; } @@ -751,11 +852,7 @@ EstablishNewConnections(clientUnused, closure) ClientPtr clientUnused; pointer closure; { -#ifndef WIN32 - fd_mask readyconnections; /* mask of listeners that are ready */ -#else fd_set readyconnections; /* set of listeners that are ready */ -#endif int curconn; /* fd of listener that's ready */ register int newconn; /* fd of new client */ CARD32 connect_time; @@ -765,40 +862,37 @@ EstablishNewConnections(clientUnused, closure) fd_set tmask; XFD_ANDSET (&tmask, (fd_set*)closure, &WellKnownConnections); -#ifndef WIN32 - readyconnections = tmask.fds_bits[0]; - if (!readyconnections) - return TRUE; -#else XFD_COPYSET(&tmask, &readyconnections); if (!XFD_ANYSET(&readyconnections)) return TRUE; -#endif connect_time = GetTimeInMillis(); /* kill off stragglers */ for (i=1; i<currentMaxClients; i++) { - if (client = clients[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) + if ((oc && (oc->conn_time != 0) && + (connect_time - oc->conn_time) >= TimeOutValue) || + (client->noClientException != Success && !client->clientGone)) CloseDownClient(client); } } #ifndef WIN32 - while (readyconnections) + for (i = 0; i < howmany(XFD_SETSIZE, NFDBITS); i++) + { + while (readyconnections.fds_bits[i]) #else - for (i = 0; i < XFD_SETCOUNT(&readyconnections); i++) + for (i = 0; i < XFD_SETCOUNT(&readyconnections); i++) #endif - { + { XtransConnInfo trans_conn, new_trans_conn; int status; #ifndef WIN32 - curconn = ffs (readyconnections) - 1; - readyconnections &= ~(1 << curconn); + 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 @@ -831,7 +925,10 @@ EstablishNewConnections(clientUnused, closure) ErrorConnMax(new_trans_conn); _XSERVTransClose(new_trans_conn); } + } +#ifndef WIN32 } +#endif return TRUE; } @@ -912,11 +1009,11 @@ CloseDownFileDescriptor(oc) _XSERVTransDisconnect(oc->trans_conn); _XSERVTransClose(oc->trans_conn); } -#ifdef LBX - ConnectionTranslation[connection] = 0; -#else +#ifndef LBX FreeOsBuffers(oc); + xfree(oc); #endif + ConnectionTranslation[connection] = 0; FD_CLR(connection, &AllSockets); FD_CLR(connection, &AllClients); FD_CLR(connection, &ClientsWithInput); @@ -931,13 +1028,10 @@ CloseDownFileDescriptor(oc) if (!XFD_ANYSET(&ClientsWriteBlocked)) AnyClientsWriteBlocked = FALSE; FD_CLR(connection, &OutputPending); -#ifndef LBX - xfree(oc); -#endif } /***************** - * CheckConections + * 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 @@ -970,13 +1064,13 @@ CheckConnections() while (mask) { curoff = ffs (mask) - 1; - curclient = curoff + (i << 5); + curclient = curoff + (i * (sizeof(fd_mask)*8)); FD_ZERO(&tmask); FD_SET(curclient, &tmask); r = Select (curclient + 1, &tmask, NULL, NULL, ¬ime); if (r < 0) CloseDownClient(clients[ConnectionTranslation[curclient]]); - mask &= ~(1 << curoff); + mask &= ~((fd_mask)1 << curoff); } } #else @@ -1022,20 +1116,24 @@ CloseDownConnection(client) AuditF("client %d disconnected\n", client->index); } - +void AddEnabledDevice(fd) int fd; { FD_SET(fd, &EnabledDevices); FD_SET(fd, &AllSockets); + if (GrabInProgress) + FD_SET(fd, &SavedAllSockets); } - +void RemoveEnabledDevice(fd) int fd; { FD_CLR(fd, &EnabledDevices); FD_CLR(fd, &AllSockets); + if (GrabInProgress) + FD_CLR(fd, &SavedAllSockets); } /***************** @@ -1048,6 +1146,7 @@ RemoveEnabledDevice(fd) * This routine is "undone" by ListenToAllClients() *****************/ +void OnlyListenToOneClient(client) ClientPtr client; { @@ -1080,6 +1179,7 @@ OnlyListenToOneClient(client) * Undoes OnlyListentToOneClient() ****************/ +void ListenToAllClients() { if (GrabInProgress) @@ -1097,6 +1197,7 @@ ListenToAllClients() * Must have cooresponding call to AttendClient. ****************/ +void IgnoreClient (client) ClientPtr client; { @@ -1141,6 +1242,7 @@ IgnoreClient (client) * Adds one client back into the input masks. ****************/ +void AttendClient (client) ClientPtr client; { @@ -1174,6 +1276,7 @@ AttendClient (client) /* make client impervious to grabs; assume only executing client calls this */ +void MakeClientGrabImpervious(client) ClientPtr client; { @@ -1193,6 +1296,7 @@ MakeClientGrabImpervious(client) /* make client pervious to grabs; assume only executing client calls this */ +void MakeClientGrabPervious(client) ClientPtr client; { @@ -43,6 +43,7 @@ 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: io.c,v 1.6 2001/02/09 02:05:23 xorgcvs Exp $ */ /***************************************************************** @@ -52,30 +53,37 @@ SOFTWARE. * InsertFakeRequest, ResetCurrentRequest * *****************************************************************/ +/* $XFree86: xc/programs/Xserver/os/io.c,v 3.34 2002/05/31 18:46:05 dawes Exp $ */ +#if 0 +#define DEBUG_COMMUNICATION +#endif #ifdef WIN32 #include <X11/Xwinsock.h> #endif #include <stdio.h> #include <X11/Xtrans.h> -#ifdef X_NOT_STDC_ENV -extern int errno; -#endif #include "Xmd.h" #include <errno.h> -#ifndef WIN32 +#if !defined(__UNIXOS2__) && !defined(WIN32) +#ifndef Lynx #include <sys/uio.h> +#else +#include <uio.h> +#endif #endif #include "X.h" #define NEED_REPLIES #include "Xproto.h" #include "os.h" -#include "Xpoll.h" #include "osdep.h" +#include "Xpoll.h" #include "opaque.h" #include "dixstruct.h" #include "misc.h" #ifdef LBX +#include "colormapst.h" +#include "propertyst.h" #include "lbxserve.h" #endif @@ -85,6 +93,7 @@ CallbackListPtr FlushCallback; /* check for both EAGAIN and EWOULDBLOCK, because some supposedly POSIX * systems are broken and return EWOULDBLOCK when they should return EAGAIN */ +#ifndef __UNIXOS2__ #if defined(EAGAIN) && defined(EWOULDBLOCK) #define ETEST(err) (err == EAGAIN || err == EWOULDBLOCK) #else @@ -94,13 +103,9 @@ CallbackListPtr FlushCallback; #define ETEST(err) (err == EWOULDBLOCK) #endif #endif - -extern fd_set ClientsWithInput, IgnoredClientsWithInput, AllClients; -extern fd_set ClientsWriteBlocked; -extern fd_set OutputPending; -extern int ConnectionTranslation[]; -extern Bool NewOutputPending; -extern Bool AnyClientsWriteBlocked; +#else /* __UNIXOS2__ Writing to full pipes may return ENOSPC */ +#define ETEST(err) (err == EAGAIN || err == EWOULDBLOCK || err == ENOSPC) +#endif Bool CriticalOutputPending; int timesThisConnection = 0; @@ -251,7 +256,7 @@ ReadRequestFromClient(client) if (!oci) { - if (oci = FreeInputs) + if ((oci = FreeInputs)) { FreeInputs = oci->next; } @@ -371,8 +376,23 @@ ReadRequestFromClient(client) { if ((result < 0) && ETEST(errno)) { - YieldControlNoInput(); - return 0; +#if defined(SVR4) && defined(i386) && !defined(sun) +#if defined(LBX) && 0 + /* + * For LBX connections, we can get a valid EWOULDBLOCK + * There is probably a better way of distinguishing LBX + * connections, but this works. (DHD) + */ + extern int LbxRead(); + if (oc->Read == LbxRead) +#else + if (0) +#endif +#endif + { + YieldControlNoInput(); + return 0; + } } YieldControlDeath(); return -1; @@ -451,14 +471,29 @@ ReadRequestFromClient(client) ) FD_SET(fd, &ClientsWithInput); else - YieldControlNoInput(); + { +#ifdef SMART_SCHEDULE + if (!SmartScheduleDisable) + FD_CLR(fd, &ClientsWithInput); + else +#endif + YieldControlNoInput(); + } } else { if (!gotnow) AvailableInput = oc; - YieldControlNoInput(); +#ifdef SMART_SCHEDULE + if (!SmartScheduleDisable) + FD_CLR(fd, &ClientsWithInput); + else +#endif + YieldControlNoInput(); } +#ifdef SMART_SCHEDULE + if (SmartScheduleDisable) +#endif if (++timesThisConnection >= MAX_TIMES_PER) YieldControl(); #ifdef BIGREQS @@ -472,6 +507,13 @@ ReadRequestFromClient(client) } #endif client->requestBuffer = (pointer)oci->bufptr; +#ifdef DEBUG_COMMUNICATION + { + xReq *req = client->requestBuffer; + ErrorF("REQUEST: ClientIDX: %i, type: 0x%x data: 0x%x len: %i\n", + client->index,req->reqType,req->data,req->length); + } +#endif return needed; } @@ -513,7 +555,7 @@ InsertFakeRequest(client, data, count) } if (!oci) { - if (oci = FreeInputs) + if ((oci = FreeInputs)) FreeInputs = oci->next; else if (!(oci = AllocateInputBuffer())) return FALSE; @@ -558,6 +600,7 @@ InsertFakeRequest(client, data, count) * **********************/ +void ResetCurrentRequest(client) ClientPtr client; { @@ -567,7 +610,6 @@ ResetCurrentRequest(client) register xReq *request; int gotnow, needed; #ifdef LBX - Bool part; LbxClientPtr lbxClient = LbxClient(client); if (lbxClient) { @@ -769,11 +811,12 @@ static int padlength[4] = {0, 3, 2, 1}; void FlushAllOutput() { - register int index, base, mask; + register int index, base; + register fd_mask mask; /* raphael */ OsCommPtr oc; register ClientPtr client; Bool newoutput = NewOutputPending; -#ifdef WIN32 +#if defined(WIN32) fd_set newOutputPending; #endif @@ -800,7 +843,7 @@ FlushAllOutput() { index = ffs(mask) - 1; mask &= ~lowbit(mask); - if ((index = ConnectionTranslation[(base << 5) + index]) == 0) + if ((index = ConnectionTranslation[(base * (sizeof(fd_mask)*8)) + index]) == 0) continue; client = clients[index]; if (client->clientGone) @@ -879,13 +922,54 @@ WriteToClient (who, count, buf) OsCommPtr oc = (OsCommPtr)who->osPrivate; register ConnectionOutputPtr oco = oc->output; int padBytes; - +#ifdef DEBUG_COMMUNICATION + Bool multicount = FALSE; +#endif if (!count) return(0); +#ifdef DEBUG_COMMUNICATION + { + char info[128]; + xError *err; + xGenericReply *rep; + xEvent *ev; + + if (!who->replyBytesRemaining) { + switch(buf[0]) { + case X_Reply: + rep = (xGenericReply*)buf; + if (rep->sequenceNumber == who->sequence) { + snprintf(info,127,"Xreply: type: 0x%x data: 0x%x " + "len: %i seq#: 0x%x", rep->type, rep->data1, + rep->length, rep->sequenceNumber); + multicount = TRUE; + } + break; + case X_Error: + err = (xError*)buf; + snprintf(info,127,"Xerror: Code: 0x%x resID: 0x%x maj: 0x%x " + "min: %x", err->errorCode,err->resourceID, + err->minorCode,err->majorCode); + break; + default: + if ((buf[0] & 0x7f) == KeymapNotify) + snprintf(info,127,"KeymapNotifyEvent: %i",buf[0]); + else { + ev = (xEvent*)buf; + snprintf(info,127,"XEvent: type: 0x%x detail: 0x%x " + "seq#: 0x%x", ev->u.u.type, ev->u.u.detail, + ev->u.u.sequenceNumber); + } + } + ErrorF("REPLY: ClientIDX: %i %s\n",who->index, info); + } else + multicount = TRUE; + } +#endif if (!oco) { - if (oco = FreeOutputs) + if ((oco = FreeOutputs)) { FreeOutputs = oco->next; } @@ -933,14 +1017,25 @@ WriteToClient (who, count, buf) replyinfo.bytesRemaining = who->replyBytesRemaining = bytesleft; CallCallbacks((&ReplyCallback), (pointer)&replyinfo); } - } - + } +#ifdef DEBUG_COMMUNICATION + else if (multicount) { + if (who->replyBytesRemaining) { + who->replyBytesRemaining -= (count + padBytes); + } else { + CARD32 replylen; + replylen = ((xGenericReply *)buf)->length; + who->replyBytesRemaining = + (replylen * 4) + SIZEOF(xReply) - count - padBytes; + } + } +#endif if (oco->count + count + padBytes > oco->size) { FD_CLR(oc->fd, &OutputPending); if(!XFD_ANYSET(&OutputPending)) { - CriticalOutputPending = FALSE; - NewOutputPending = FALSE; + CriticalOutputPending = FALSE; + NewOutputPending = FALSE; } return FlushClient(who, oc, buf, count); } @@ -1007,7 +1102,7 @@ FlushClient(who, oc, extraBuf, extraCount) long remain = todo; /* amount to try this time, <= notWritten */ int i = 0; long len; - + /* You could be very general here and have "in" and "out" iovecs * and write a loop without using a macro, but what the heck. This * translates to: @@ -1203,7 +1298,7 @@ FreeOsBuffers(oc) if (AvailableInput == oc) AvailableInput = (OsCommPtr)NULL; - if (oci = oc->input) + if ((oci = oc->input)) { if (FreeInputs) { @@ -1219,7 +1314,7 @@ FreeOsBuffers(oc) oci->lenLastReq = 0; } } - if (oco = oc->output) + if ((oco = oc->output)) { if (FreeOutputs) { @@ -1234,7 +1329,7 @@ FreeOsBuffers(oc) } } #ifdef LBX - if (oci = oc->largereq) { + if ((oci = oc->largereq)) { xfree(oci->buffer); xfree(oci); } @@ -1247,13 +1342,13 @@ ResetOsBuffers() register ConnectionInputPtr oci; register ConnectionOutputPtr oco; - while (oci = FreeInputs) + while ((oci = FreeInputs)) { FreeInputs = oci->next; xfree(oci->buffer); xfree(oci); } - while (oco = FreeOutputs) + while ((oco = FreeOutputs)) { FreeOutputs = oco->next; xfree(oco->buf); diff --git a/os/k5auth.c b/os/k5auth.c index c6a2e3cc9..8c59fe8ab 100644 --- a/os/k5auth.c +++ b/os/k5auth.c @@ -26,6 +26,7 @@ other dealings in this Software without prior written authorization from The Open Group. */ +/* $XFree86: xc/programs/Xserver/os/k5auth.c,v 3.5 2001/12/14 20:00:34 dawes Exp $ */ /* * Kerberos V5 authentication scheme @@ -303,7 +304,7 @@ int k5_stage1(client) return(SendConnSetup(client, "Krb5 stage1: getpeername failed")); } if (cli_net_addr.sa_family == AF_UNSPEC -#if defined(UNIXCONN) || defined(LOCALCONN) +#if defined(UNIXCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) || cli_net_addr.sa_family == AF_UNIX #endif ) /* assume local host */ diff --git a/os/lbxio.c b/os/lbxio.c index c72ac2c05..2991681de 100644 --- a/os/lbxio.c +++ b/os/lbxio.c @@ -1,3 +1,4 @@ +/* $XFree86: xc/programs/Xserver/os/lbxio.c,v 3.17 2002/05/31 18:46:06 dawes Exp $ */ /* Copyright 1996, 1998 The Open Group @@ -50,13 +51,16 @@ SOFTWARE. #include <stdio.h> #include <X11/Xtrans.h> -#ifdef X_NOT_STDC_ENV -extern int errno; -#endif #include "Xmd.h" #include <errno.h> +#ifndef Lynx #include <sys/param.h> +#ifndef __UNIXOS2__ #include <sys/uio.h> +#endif +#else +#include <uio.h> +#endif #include "X.h" #include "Xproto.h" #include "os.h" @@ -65,6 +69,8 @@ extern int errno; #include "opaque.h" #include "dixstruct.h" #include "misc.h" +#include "colormapst.h" +#include "propertyst.h" #include "lbxserve.h" /* check for both EAGAIN and EWOULDBLOCK, because some supposedly POSIX @@ -80,19 +86,6 @@ extern int errno; #endif #endif -extern fd_set ClientsWithInput, IgnoredClientsWithInput; -extern fd_set AllClients, AllSockets; -extern fd_set ClientsWriteBlocked; -extern fd_set OutputPending; -extern int ConnectionTranslation[]; -extern Bool NewOutputPending; -extern Bool AnyClientsWriteBlocked; -extern Bool CriticalOutputPending; -extern int timesThisConnection; -extern ConnectionInputPtr FreeInputs; -extern ConnectionOutputPtr FreeOutputs; -extern OsCommPtr AvailableInput; - #define get_req_len(req,cli) ((cli)->swapped ? \ lswaps((req)->length) : (req)->length) @@ -166,7 +159,7 @@ AppendFakeRequest (client, data, count) if (!oci) { - if (oci = FreeInputs) + if ((oci = FreeInputs)) FreeInputs = oci->next; else if (!(oci = AllocateInputBuffer())) return FALSE; @@ -288,7 +281,7 @@ LbxAppendOutput(proxy, client, oco) int n; if (!noco || (noco->size - noco->count) < sz_xLbxSwitchEvent) { - if (noco = FreeOutputs) + if ((noco = FreeOutputs)) FreeOutputs = noco->next; else noco = AllocateOutputBuffer(); @@ -334,7 +327,7 @@ LbxClientOutput(client, oc, extraBuf, extraCount, nocompress) ConnectionOutputPtr oco; int len; - if (oco = oc->output) { + if ((oco = oc->output)) { oc->output = NULL; if (!LbxAppendOutput(oc->proxy, client, oco)) return -1; @@ -387,7 +380,7 @@ LbxForceOutput(proxy) if (!lbxClient) continue; coc = (OsCommPtr)lbxClient->client->osPrivate; - if (oco = coc->output) { + if ((oco = coc->output)) { coc->output = NULL; LbxAppendOutput(proxy, lbxClient->client, oco); } @@ -404,7 +397,7 @@ LbxFlushClient(who, oc, extraBuf, extraCount) LbxProxyPtr proxy; ConnectionOutputPtr oco; int n; - XtransConnInfo trans_conn; + XtransConnInfo trans_conn = NULL; if (extraBuf) return LbxClientOutput(who, oc, extraBuf, extraCount, FALSE); @@ -414,7 +407,7 @@ LbxFlushClient(who, oc, extraBuf, extraCount) LbxForceOutput(proxy); if (!proxy->compHandle) trans_conn = ((OsCommPtr)LbxProxyClient(proxy)->osPrivate)->trans_conn; - while (oco = proxy->ofirst) { + while ((oco = proxy->ofirst)) { /* XXX bundle up into writev someday */ if (proxy->compHandle) { if (oco->nocompress) @@ -474,12 +467,13 @@ UncompressedWriteToClient (who, count, buf) return LbxClientOutput(who, (OsCommPtr)who->osPrivate, buf, count, TRUE); } +void LbxFreeOsBuffers(proxy) LbxProxyPtr proxy; { ConnectionOutputPtr oco; - while (oco = proxy->ofirst) { + while ((oco = proxy->ofirst)) { proxy->ofirst = oco->next; xfree(oco->buf); xfree(oco); @@ -495,7 +489,7 @@ AllocateLargeReqBuffer(client, size) register ConnectionInputPtr oci; if (!(oci = oc->largereq)) { - if (oci = FreeInputs) + if ((oci = FreeInputs)) FreeInputs = oci->next; else { oci = (ConnectionInputPtr)xalloc(sizeof(ConnectionInput)); diff --git a/os/mitauth.c b/os/mitauth.c index 274ab5829..bddbdf1d6 100644 --- a/os/mitauth.c +++ b/os/mitauth.c @@ -26,6 +26,7 @@ other dealings in this Software without prior written authorization from The Open Group. */ +/* $XFree86: xc/programs/Xserver/os/mitauth.c,v 1.5 2001/12/14 20:00:34 dawes Exp $ */ /* * MIT-MAGIC-COOKIE-1 authorization scheme @@ -34,6 +35,7 @@ from The Open Group. #include "X.h" #include "os.h" +#include "osdep.h" #include "dixstruct.h" static struct auth { @@ -44,10 +46,10 @@ static struct auth { } *mit_auth; int -MitAddCookie (data_length, data, id) -unsigned short data_length; -char *data; -XID id; +MitAddCookie ( + unsigned short data_length, + char *data, + XID id) { struct auth *new; @@ -68,11 +70,11 @@ XID id; } XID -MitCheckCookie (data_length, data, client, reason) - unsigned short data_length; - char *data; - ClientPtr client; - char **reason; +MitCheckCookie ( + unsigned short data_length, + char *data, + ClientPtr client, + char **reason) { struct auth *auth; @@ -86,7 +88,7 @@ MitCheckCookie (data_length, data, client, reason) } int -MitResetCookie () +MitResetCookie (void) { struct auth *auth, *next; @@ -100,9 +102,9 @@ MitResetCookie () } XID -MitToID (data_length, data) -unsigned short data_length; -char *data; +MitToID ( + unsigned short data_length, + char *data) { struct auth *auth; @@ -115,10 +117,10 @@ char *data; } int -MitFromID (id, data_lenp, datap) -XID id; -unsigned short *data_lenp; -char **datap; +MitFromID ( + XID id, + unsigned short *data_lenp, + char **datap) { struct auth *auth; @@ -133,9 +135,9 @@ char **datap; } int -MitRemoveCookie (data_length, data) -unsigned short data_length; -char *data; +MitRemoveCookie ( + unsigned short data_length, + char *data) { struct auth *auth, *prev; @@ -161,12 +163,12 @@ char *data; static char cookie[16]; /* 128 bits */ XID -MitGenerateCookie (data_length, data, id, data_length_return, data_return) - unsigned int data_length; - char *data; - XID id; - unsigned int *data_length_return; - char **data_return; +MitGenerateCookie ( + unsigned data_length, + char *data, + XID id, + unsigned *data_length_return, + char **data_return) { int i = 0; int status; diff --git a/os/oscolor.c b/os/oscolor.c index f5fd61bc5..62676f84b 100644 --- a/os/oscolor.c +++ b/os/oscolor.c @@ -1,3 +1,4 @@ +/* $XFree86: xc/programs/Xserver/os/oscolor.c,v 3.8 2002/05/31 18:46:06 dawes Exp $ */ /*********************************************************** Copyright 1987, 1998 The Open Group @@ -107,11 +108,11 @@ OsLookupColor(screen, name, len, pred, pgreen, pblue) if(!rgb_dbm) return(0); - /* we use Xalloc here so that we can compile with cc without alloca + /* 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))) + else if (!(lowername = (char *)xalloc(len + 1))) return(0); CopyISOLatin1Lowered ((unsigned char *) lowername, (unsigned char *) name, (int)len); @@ -125,7 +126,7 @@ OsLookupColor(screen, name, len, pred, pgreen, pblue) #endif if (len >= sizeof(buf)) - Xfree(lowername); + xfree(lowername); if(dbent.dptr) { @@ -175,7 +176,7 @@ lookup(name, len, create) Bool create; { unsigned int h = 0, g; - dbEntryPtr entry, *prev; + dbEntryPtr entry, *prev = NULL; char *str = name; if (!(name = (char*)ALLOCATE_LOCAL(len +1))) return NULL; @@ -189,7 +190,7 @@ lookup(name, len, create) } h %= HASHSIZE; - if ( entry = hashTab[h] ) + if ( (entry = hashTab[h]) ) { for( ; entry; prev = (dbEntryPtr*)entry, entry = entry->link ) if (! strcmp(name, entry->name) ) break; @@ -197,7 +198,7 @@ lookup(name, len, create) else prev = &(hashTab[h]); - if (!entry && create && (entry = (dbEntryPtr)Xalloc(sizeof(dbEntry) +len))) + if (!entry && create && (entry = (dbEntryPtr)xalloc(sizeof(dbEntry) +len))) { *prev = entry; entry->link = NULL; @@ -224,10 +225,16 @@ OsInitColors() 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 ); @@ -238,13 +245,17 @@ OsInitColors() 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)) + if ((entry = lookup(name, strlen(name), TRUE))) { entry->red = (red * 65535) / 255; entry->green = (green * 65535) / 255; @@ -252,8 +263,7 @@ OsInitColors() } } else - ErrorF("Value for \"%s\" out of range: %s:%d\n", - name, path, lineno); + ErrorF("Value out of range: %s:%d\n", path, lineno); } else if (*line && *line != '#' && *line != '!') ErrorF("Syntax Error: %s:%d\n", path, lineno); @@ -280,7 +290,7 @@ OsLookupColor(screen, name, len, pred, pgreen, pblue) { dbEntryPtr entry; - if (entry = lookup(name, len, FALSE)) + if ((entry = lookup(name, len, FALSE))) { *pred = entry->red; *pgreen = entry->green; diff --git a/os/osdep.h b/os/osdep.h index c7c730740..a1fe2bfed 100644 --- a/os/osdep.h +++ b/os/osdep.h @@ -1,3 +1,4 @@ +/* $XFree86: xc/programs/Xserver/os/osdep.h,v 3.17 2002/05/31 18:46:06 dawes Exp $ */ /*********************************************************** Copyright 1987, 1998 The Open Group @@ -46,10 +47,17 @@ SOFTWARE. ******************************************************************/ /* $Xorg: osdep.h,v 1.5 2001/02/09 02:05:23 xorgcvs Exp $ */ +#ifndef _OSDEP_H_ +#define _OSDEP_H_ 1 + #define BOTIMEOUT 200 /* in milliseconds */ #define BUFSIZE 4096 #define BUFWATERMARK 8192 +#ifndef MAXBUFSIZE #define MAXBUFSIZE (1 << 22) +#endif + +#include <X11/Xdmcp.h> #ifndef sgi /* SGI defines OPEN_MAX in a useless way */ #ifndef X_NOT_POSIX @@ -69,6 +77,9 @@ SOFTWARE. #endif /* X_NOT_POSIX */ #endif +#ifdef __QNX__ +#define NOFILES_MAX 256 +#endif #ifndef OPEN_MAX #ifdef SVR4 #define OPEN_MAX 256 @@ -78,11 +89,22 @@ SOFTWARE. #if defined(NOFILE) && !defined(NOFILES_MAX) #define OPEN_MAX NOFILE #else +#ifndef __UNIXOS2__ #define OPEN_MAX NOFILES_MAX +#else +#define OPEN_MAX 256 #endif #endif #endif #endif +#endif + +#include <X11/Xpoll.h> + +/* + * MAXSOCKS is used only for initialising MaxClients when no other method + * like sysconf(_SC_OPEN_MAX) is not supported. + */ #if OPEN_MAX <= 256 #define MAXSOCKS (OPEN_MAX - 1) @@ -90,10 +112,19 @@ SOFTWARE. #define MAXSOCKS 256 #endif -#ifndef NULL -#define NULL 0 +/* MAXSELECT is the number of fds that select() can handle */ +#define MAXSELECT (sizeof(fd_set) * NBBY) + +#if !defined(hpux) && !defined(SVR4) && !defined(SYSV) +#define HAS_GETDTABLESIZE #endif +#include <stddef.h> + +typedef Bool (*ValidatorFunc)(ARRAY8Ptr Auth, ARRAY8Ptr Data, int packet_type); +typedef Bool (*GeneratorFunc)(ARRAY8Ptr Auth, ARRAY8Ptr Data, int packet_type); +typedef Bool (*AddAuthorFunc)(unsigned name_length, char *name, unsigned data_length, char *data); + typedef struct _connectionInput { struct _connectionInput *next; char *buffer; /* contains current client input */ @@ -127,6 +158,36 @@ typedef struct _k5_state { typedef struct _LbxProxy *OsProxyPtr; #endif +struct _osComm; + +#define AuthInitArgs void +typedef void (*AuthInitFunc) (AuthInitArgs); + +#define AuthAddCArgs unsigned short data_length, char *data, XID id +typedef int (*AuthAddCFunc) (AuthAddCArgs); + +#define AuthCheckArgs unsigned short data_length, char *data, ClientPtr client, char **reason +typedef XID (*AuthCheckFunc) (AuthCheckArgs); + +#define AuthFromIDArgs XID id, unsigned short *data_lenp, char **datap +typedef int (*AuthFromIDFunc) (AuthFromIDArgs); + +#define AuthGenCArgs unsigned data_length, char *data, XID id, unsigned *data_length_return, char **data_return +typedef XID (*AuthGenCFunc) (AuthGenCArgs); + +#define AuthRemCArgs unsigned short data_length, char *data +typedef int (*AuthRemCFunc) (AuthRemCArgs); + +#define AuthRstCArgs void +typedef int (*AuthRstCFunc) (AuthRstCArgs); + +#define AuthToIDArgs unsigned short data_length, char *data +typedef XID (*AuthToIDFunc) (AuthToIDArgs); + +typedef void (*OsCloseFunc)(ClientPtr); + +typedef int (*OsFlushFunc)(ClientPtr who, struct _osComm * oc, char* extraBuf, int extraCount); + typedef struct _osComm { int fd; ConnectionInputPtr input; @@ -140,8 +201,8 @@ typedef struct _osComm { #ifdef LBX OsProxyPtr proxy; ConnectionInputPtr largereq; - void (*Close) (); - int (*Flush) (); + OsCloseFunc Close; + OsFlushFunc Flush; #endif } OsCommRec, *OsCommPtr; @@ -149,38 +210,130 @@ typedef struct _osComm { #define FlushClient(who, oc, extraBuf, extraCount) \ (*(oc)->Flush)(who, oc, extraBuf, extraCount) extern int StandardFlushClient( -#if NeedFunctionPrototypes ClientPtr /*who*/, OsCommPtr /*oc*/, char* /*extraBuf*/, int /*extraCount*/ -#endif ); #else extern int FlushClient( -#if NeedFunctionPrototypes ClientPtr /*who*/, OsCommPtr /*oc*/, char* /*extraBuf*/, int /*extraCount*/ -#endif ); #endif extern void FreeOsBuffers( -#if NeedFunctionPrototypes OsCommPtr /*oc*/ -#endif ); -extern ConnectionInputPtr AllocateInputBuffer( -#if NeedFunctionPrototypes - void +#include "dix.h" + +extern ConnectionInputPtr AllocateInputBuffer(void); + +extern ConnectionOutputPtr AllocateOutputBuffer(void); + +extern fd_set AllSockets; +extern fd_set AllClients; +extern fd_set LastSelectMask; +extern fd_set WellKnownConnections; +extern fd_set EnabledDevices; +extern fd_set ClientsWithInput; +extern fd_set ClientsWriteBlocked; +extern fd_set OutputPending; +extern fd_set IgnoredClientsWithInput; + +extern int *ConnectionTranslation; + +extern Bool NewOutputPending; +extern Bool AnyClientsWriteBlocked; +extern Bool CriticalOutputPending; + +extern int timesThisConnection; +extern ConnectionInputPtr FreeInputs; +extern ConnectionOutputPtr FreeOutputs; +extern OsCommPtr AvailableInput; + +extern WorkQueuePtr workQueue; + +/* added by raphael */ +#define ffs mffs +extern int mffs(fd_mask); + +/* in auth.c */ +extern void GenerateRandomData (int len, char *buf); + +/* in mitauth.c */ +extern XID MitCheckCookie (AuthCheckArgs); +extern XID MitGenerateCookie (AuthGenCArgs); +extern XID MitToID (AuthToIDArgs); +extern int MitAddCookie (AuthAddCArgs); +extern int MitFromID (AuthFromIDArgs); +extern int MitRemoveCookie (AuthRemCArgs); +extern int MitResetCookie (AuthRstCArgs); + +/* in xdmauth.c */ +#ifdef HASXDMAUTH +extern XID XdmCheckCookie (AuthCheckArgs); +extern XID XdmToID (AuthToIDArgs); +extern int XdmAddCookie (AuthAddCArgs); +extern int XdmFromID (AuthFromIDArgs); +extern int XdmRemoveCookie (AuthRemCArgs); +extern int XdmResetCookie (AuthRstCArgs); #endif -); -extern ConnectionOutputPtr AllocateOutputBuffer( -#if NeedFunctionPrototypes - void +/* in rpcauth.c */ +#ifdef SECURE_RPC +extern void SecureRPCInit (AuthInitArgs); +extern XID SecureRPCCheck (AuthCheckArgs); +extern XID SecureRPCToID (AuthToIDArgs); +extern int SecureRPCAdd (AuthAddCArgs); +extern int SecureRPCFromID (AuthFromIDArgs); +extern int SecureRPCRemove (AuthRemCArgs); +extern int SecureRPCReset (AuthRstCArgs); #endif -); + +/* in k5auth.c */ +#ifdef K5AUTH +extern XID K5Check (AuthCheckArgs); +extern XID K5ToID (AuthToIDArgs); +extern int K5Add (AuthAddCArgs); +extern int K5FromID (AuthFromIDArgs); +extern int K5Remove (AuthRemCArgs); +extern int K5Reset (AuthRstCArgs); +#endif + +/* in secauth.c */ +extern XID AuthSecurityCheck (AuthCheckArgs); + +/* in xdmcp.c */ +extern void XdmcpUseMsg (void); +extern int XdmcpOptions(int argc, char **argv, int i); +extern void XdmcpSetAuthentication (ARRAY8Ptr name); +extern void XdmcpRegisterConnection ( + int type, + char *address, + int addrlen); +extern void XdmcpRegisterAuthorizations (void); +extern void XdmcpRegisterAuthorization (char *name, int namelen); +extern void XdmcpRegisterDisplayClass (char *name, int length); +extern void XdmcpInit (void); +extern void XdmcpReset (void); +extern void XdmcpOpenDisplay(int sock); +extern void XdmcpCloseDisplay(int sock); +extern void XdmcpRegisterAuthentication ( + char *name, + int namelen, + char *data, + int datalen, + ValidatorFunc Validator, + GeneratorFunc Generator, + AddAuthorFunc AddAuth); +extern int XdmcpCheckAuthentication (ARRAY8Ptr Name, ARRAY8Ptr Data, int packet_type); +extern int XdmcpAddAuthorization (ARRAY8Ptr name, ARRAY8Ptr data); + +struct sockaddr_in; +extern void XdmcpRegisterBroadcastAddress (struct sockaddr_in *addr); + +#endif /* _OSDEP_H_ */ diff --git a/os/osinit.c b/os/osinit.c index f240ea42c..9d9fcda4e 100644 --- a/os/osinit.c +++ b/os/osinit.c @@ -1,3 +1,4 @@ +/* $XFree86: xc/programs/Xserver/os/osinit.c,v 3.27 2002/06/17 08:04:18 alanh Exp $ */ /*********************************************************** Copyright 1987, 1998 The Open Group @@ -52,6 +53,10 @@ SOFTWARE. #include "osdep.h" #include "Xos.h" +#ifdef SMART_SCHEDULE +#include "dixstruct.h" +#endif + #ifndef PATH_MAX #ifdef MAXPATHLEN #define PATH_MAX MAXPATHLEN @@ -60,10 +65,12 @@ SOFTWARE. #endif #endif -#ifndef WIN32 -#ifndef SYSV -#include <sys/resource.h> +#if defined(Lynx) || defined(SCO) || defined(SCO325) +#include <sys/wait.h> #endif + +#if !defined(SYSV) && !defined(WIN32) && !defined(Lynx) && !defined(QNX4) +#include <sys/resource.h> #endif #ifndef ADMPATH @@ -83,6 +90,10 @@ int limitNoFile = -1; Bool OsDelayInitColors = FALSE; +#ifdef XFree86LOADER +extern void xf86WrapperInit(void); +#endif + void OsInit() { @@ -96,8 +107,13 @@ OsInit() #endif if (!been_here) { +#ifdef XFree86LOADER + xf86WrapperInit(); +#endif +#if !defined(SCO) && !defined(__CYGWIN__) fclose(stdin); fclose(stdout); +#endif /* * If a write of zero bytes to stderr returns non-zero, i.e. -1, * then writing to stderr failed, and we'll write somewhere else @@ -122,7 +138,7 @@ OsInit() dup2 (fileno (err), 2); fclose (err); } -#if defined(SYSV) || defined(SVR4) || defined(WIN32) +#if defined(SYSV) || defined(SVR4) || defined(__UNIXOS2__) || defined(WIN32) || defined(__CYGWIN__) { static char buf[BUFSIZ]; setvbuf (stderr, buf, _IOLBF, BUFSIZ); @@ -183,18 +199,36 @@ OsInit() rlim.rlim_cur = limitNoFile; else rlim.rlim_cur = rlim.rlim_max; +#if 0 if (rlim.rlim_cur > MAXSOCKS) rlim.rlim_cur = MAXSOCKS; +#endif (void)setrlimit(RLIMIT_NOFILE, &rlim); } } #endif +#ifdef SERVER_LOCK + LockServer(); +#endif been_here = TRUE; } TimerInit(); #ifdef DDXOSINIT OsVendorInit(); #endif +#ifdef SMART_SCHEDULE + if (!SmartScheduleDisable) + if (!SmartScheduleInit ()) + SmartScheduleDisable = TRUE; +#endif OsInitAllocator(); if (!OsDelayInitColors) OsInitColors(); } + +void +OsCleanup() +{ +#ifdef SERVER_LOCK + UnlockServer(); +#endif +} diff --git a/os/rpcauth.c b/os/rpcauth.c index 15111921f..7ee53b52d 100644 --- a/os/rpcauth.c +++ b/os/rpcauth.c @@ -26,6 +26,7 @@ other dealings in this Software without prior written authorization from The Open Group. */ +/* $XFree86: xc/programs/Xserver/os/rpcauth.c,v 3.7 2001/12/14 20:00:35 dawes Exp $ */ /* * SUN-DES-1 authentication mechanism @@ -43,6 +44,16 @@ from The Open Group. #include <rpc/rpc.h> +#ifdef sun +/* <rpc/auth.h> only includes this if _KERNEL is #defined... */ +extern bool_t xdr_opaque_auth(XDR *, struct opaque_auth *); +#endif + +#if defined(DGUX) +#include <time.h> +#include <rpc/auth_des.h> +#endif /* DGUX */ + #ifdef ultrix #include <time.h> #include <rpc/auth_des.h> @@ -104,7 +115,7 @@ int len; return (((struct authdes_cred *) r.rq_clntcred)->adc_fullname.name); bad2: - Xfree(r.rq_clntcred); + xfree(r.rq_clntcred); bad1: return ((char *)0); /* ((struct authdes_cred *) NULL); */ } @@ -112,10 +123,11 @@ bad1: static XID rpc_id = (XID) ~0L; static Bool -CheckNetName (addr, len, closure) - unsigned char *addr; - int len; - pointer closure; +CheckNetName ( + unsigned char *addr, + short len, + pointer closure +) { return (len == strlen ((char *) closure) && strncmp ((char *) addr, (char *) closure, len) == 0); @@ -140,21 +152,18 @@ SecureRPCCheck (data_length, data, client, reason) sprintf(rpc_error, "Unable to authenticate secure RPC client (why=%d)", why); *reason = rpc_error; } else { - if (ForEachHostInFamily (FamilyNetname, CheckNetName, - (pointer) fullname)) + if (ForEachHostInFamily (FamilyNetname, CheckNetName, fullname)) return rpc_id; - else { - sprintf(rpc_error, "Principal \"%s\" is not authorized to connect", + sprintf(rpc_error, "Principal \"%s\" is not authorized to connect", fullname); - *reason = rpc_error; - } + *reason = rpc_error; } } return (XID) ~0L; } - -SecureRPCInit () +void +SecureRPCInit (void) { if (rpc_id == ~0L) AddAuthorization (9, "SUN-DES-1", 0, (char *) 0); @@ -169,12 +178,14 @@ XID id; if (data_length) AddHost ((pointer) 0, FamilyNetname, data_length, data); rpc_id = id; + return 1; } int -SecureRPCReset () +SecureRPCReset (void) { rpc_id = (XID) ~0L; + return 1; } XID @@ -185,6 +196,7 @@ SecureRPCToID (data_length, data) return rpc_id; } +int SecureRPCFromID (id, data_lenp, datap) XID id; unsigned short *data_lenp; @@ -193,6 +205,7 @@ SecureRPCFromID (id, data_lenp, datap) return 0; } +int SecureRPCRemove (data_length, data) unsigned short data_length; char *data; diff --git a/os/secauth.c b/os/secauth.c index a73f4e718..4f90fe9a9 100644 --- a/os/secauth.c +++ b/os/secauth.c @@ -1,6 +1,6 @@ -/* $Xorg: secauth.c,v 1.5 2001/02/15 02:06:01 coskrey Exp $ */ +/* $Xorg: secauth.c,v 1.4 2001/02/09 02:05:23 xorgcvs Exp $ */ /* -Copyright 1996, 1998, 2001 The Open Group +Copyright 1996, 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 @@ -24,11 +24,13 @@ 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: xc/programs/Xserver/os/secauth.c,v 1.11 2001/12/14 20:00:35 dawes Exp $ */ #include "X.h" #include "os.h" #include "osdep.h" #include "dixstruct.h" +#include "swaprep.h" #ifdef XCSECURITY #define _SECURITY_SERVER @@ -39,11 +41,11 @@ static char InvalidPolicyReason[] = "invalid policy specification"; static char PolicyViolationReason[] = "policy violation"; static Bool -AuthCheckSitePolicy(data_lengthP, dataP, client, reason) - unsigned short *data_lengthP; - char **dataP; - ClientPtr client; - char **reason; +AuthCheckSitePolicy( + unsigned short *data_lengthP, + char **dataP, + ClientPtr client, + char **reason) { CARD8 *policy = *(CARD8 **)dataP; int length; @@ -65,7 +67,7 @@ AuthCheckSitePolicy(data_lengthP, dataP, client, reason) sitePolicies = SecurityGetSitePolicyStrings(&nSitePolicies); - while (nPolicies > 0) { + while (nPolicies) { int strLen, sitePolicy; if (length == 0) { @@ -110,15 +112,13 @@ AuthCheckSitePolicy(data_lengthP, dataP, client, reason) } XID -AuthSecurityCheck (data_length, data, client, reason) - unsigned short data_length; - char *data; - ClientPtr client; - char **reason; +AuthSecurityCheck ( + unsigned short data_length, + char *data, + ClientPtr client, + char **reason) { #ifdef XCSECURITY - OsCommPtr oc = (OsCommPtr)client->osPrivate; - register ConnectionInputPtr oci = oc->input; xConnSetupPrefix csp; xReq freq; diff --git a/os/utils.c b/os/utils.c index 2c3d0ba63..4bbe9eb8c 100644 --- a/os/utils.c +++ b/os/utils.c @@ -49,8 +49,14 @@ 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.85 2002/12/24 17:43:00 tsi Exp $ */ -#ifdef WIN32 +#ifdef __CYGWIN__ +#include <stdlib.h> +#include <signal.h> +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) #include <X11/Xwinsock.h> #endif #include "Xos.h" @@ -58,7 +64,8 @@ OR PERFORMANCE OF THIS SOFTWARE. #include "misc.h" #include "X.h" #include "input.h" -#include "opaque.h" +#include "dixfont.h" +#include "osdep.h" #ifdef X_POSIX_C_SOURCE #define _POSIX_C_SOURCE X_POSIX_C_SOURCE #include <signal.h> @@ -72,74 +79,69 @@ OR PERFORMANCE OF THIS SOFTWARE. #undef _POSIX_SOURCE #endif #endif -#ifndef WIN32 -#ifndef SYSV +#include <sys/wait.h> +#if !defined(SYSV) && !defined(WIN32) && !defined(Lynx) && !defined(QNX4) #include <sys/resource.h> #endif -#endif #include <time.h> #include <sys/stat.h> #include <ctype.h> /* for isspace */ -#if NeedVarargsPrototypes #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 -#define X_INCLUDE_NETDB_H -#include <X11/Xos_r.h> - -extern char *display; +#include "opaque.h" -extern CARD32 defaultScreenSaverTime; /* for parsing command line */ -extern CARD32 defaultScreenSaverInterval; -extern int defaultScreenSaverBlanking; -extern int defaultBackingStore; -extern Bool disableBackingStore; -extern Bool disableSaveUnders; -extern Bool PartialNetwork; -#ifndef NOLOGOHACK -extern int logoScreenSaver; -#endif -#ifdef RLIMIT_DATA -extern int limitDataSpace; +#ifdef SMART_SCHEDULE +#include "dixstruct.h" #endif -#ifdef RLIMIT_STACK -extern int limitStackSpace; + +#ifdef XKB +#include "XKBsrv.h" #endif -#ifdef RLIMIT_NOFILE -extern int limitNoFile; +#ifdef XCSECURITY +#define _SECURITY_SERVER +#include "security.h" #endif -extern int defaultColorVisualClass; -extern Bool permitOldBugs; -extern int monitorResolution; -extern Bool defeatAccessControl; -#ifdef DPMSExtension -extern BOOL DPMSEnabledSwitch; -extern BOOL DPMSDisabledSwitch; +#ifdef RENDER +#include "picture.h" #endif +#define X_INCLUDE_NETDB_H +#include <X11/Xos_r.h> + +#include <errno.h> + Bool CoreDump; Bool noTestExtensions; -Bool noPanoramiXExtension = TRUE; #ifdef PANORAMIX +Bool noPanoramiXExtension = TRUE; Bool PanoramiXVisibilityNotifySent = FALSE; Bool PanoramiXMapped = FALSE; Bool PanoramiXWindowExposureSent = FALSE; Bool PanoramiXOneExposeRequest = FALSE; #endif +#ifdef DDXOSVERRORF +void (*OsVendorVErrorFProc)(const char *, va_list args) = NULL; +#endif + int auditTrailLevel = 1; -void ddxUseMsg(); -#if NeedVarargsPrototypes -void VErrorF(char*, va_list); -#endif +Bool Must_have_memory = FALSE; #ifdef AIXV3 int SyncOn = 0; @@ -155,15 +157,13 @@ extern int SelectWaitTime; #ifdef MEMBUG #define MEM_FAIL_SCALE 100000 long Memory_fail = 0; - +#include <stdlib.h> /* for random() */ #endif #ifdef sgi int userdefinedfontpath = 0; #endif /* sgi */ -Bool Must_have_memory = FALSE; - char *dev_tty_from_init = NULL; /* since we need to parse it anyway */ OsSigHandlerPtr @@ -185,6 +185,206 @@ OsSignal(sig, handler) 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() +{ + char tmp[PATH_MAX], pid_str[12]; + int lfd, i, haslock, l_pid, t; + char *tmppath = NULL; + int len; + + 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 + + len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : + strlen(LOCK_TMP_PREFIX); + len += strlen(tmppath) + strlen(display) + strlen(LOCK_SUFFIX) + 1; + if (len > sizeof(LockFile)) + FatalError("Display name `%s' is too long\n"); + (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, display); + (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, display); + + /* + * 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", + display, "\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() +{ + 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 */ @@ -193,6 +393,8 @@ SIGVAL AutoResetServer (sig) int sig; { + int olderrno = errno; + dispatchException |= DE_RESET; isItTimeToYield = TRUE; #ifdef GPROF @@ -202,6 +404,7 @@ AutoResetServer (sig) #if defined(SYSV) && defined(X_NOT_POSIX) OsSignal (SIGHUP, AutoResetServer); #endif + errno = olderrno; } /* Force connections to close and then exit on SIGTERM, SIGINT */ @@ -211,20 +414,25 @@ SIGVAL GiveUp(sig) 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; } +#ifdef __GNUC__ +static void AbortServer() __attribute__((noreturn)); +#endif static void AbortServer() { - extern void AbortDDX(); - + OsCleanup(); AbortDDX(); fflush(stderr); if (CoreDump) @@ -250,6 +458,7 @@ GetTimeInMillis() } #endif +void AdjustWaitForDelay (waitTime, newdelay) pointer waitTime; unsigned long newdelay; @@ -287,6 +496,8 @@ void UseMsg() 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"); @@ -317,14 +528,22 @@ void UseMsg() #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("-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"); @@ -338,11 +557,11 @@ void UseMsg() 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"); #ifdef PANORAMIX ErrorF("+xinerama Enable XINERAMA extension\n"); ErrorF("-xinerama Disable XINERAMA extension\n"); #endif - ErrorF("-x string loads named extension at init time \n"); #ifdef XDMCP XdmcpUseMsg(); #endif @@ -353,6 +572,24 @@ void UseMsg() 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 + */ +int VerifyDisplayName( d ) +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 parses the command line. Handles device-independent fields * and allows ddx to handle additional fields. It is not allowed to modify @@ -368,10 +605,14 @@ char *argv[]; defaultKeyboardControl.autoRepeat = TRUE; +#ifdef PART_NET + 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)) + if((skip = ddxProcessArgument(argc, argv, i))) { i += (skip - 1); } @@ -380,6 +621,11 @@ char *argv[]; /* initialize display */ display = argv[i]; display++; + if( ! VerifyDisplayName( display ) ) { + ErrorF("Bad display name: %s\n", display); + UseMsg(); + exit(1); + } } else if ( strcmp( argv[i], "-a") == 0) { @@ -417,6 +663,10 @@ char *argv[]; } 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) @@ -544,6 +794,17 @@ char *argv[]; 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) { @@ -554,6 +815,19 @@ char *argv[]; logoScreenSaver = 0; } #endif + else if ( strcmp( argv[i], "-nolisten") == 0) + { + if(++i < argc) + protNoListen = argv[i]; + else + UseMsg(); + } + else if ( strcmp( argv[i], "-noreset") == 0) + { + extern char dispatchExceptionAtReset; + + dispatchExceptionAtReset = 0; + } else if ( strcmp( argv[i], "-p") == 0) { if(++i < argc) @@ -564,6 +838,8 @@ char *argv[]; } 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) @@ -587,9 +863,9 @@ char *argv[]; } else if ( strcmp( argv[i], "-terminate") == 0) { - extern Bool terminateAtReset; + extern char dispatchExceptionAtReset; - terminateAtReset = TRUE; + dispatchExceptionAtReset = DE_TERMINATE; } else if ( strcmp( argv[i], "-to") == 0) { @@ -665,8 +941,50 @@ char *argv[]; 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 { + ErrorF("Unrecognized option: %s\n", argv[i]); UseMsg(); exit (1); } @@ -771,6 +1089,12 @@ ExpandCommandLine(pargc, pargv) 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)) ) @@ -803,7 +1127,9 @@ pointer client; char hname[1024], *hnameptr; struct hostent *host; int len; +#ifdef XTHREADS_NEEDS_BYNAMEPARAMS _Xgethostbynameparams hparams; +#endif gethostname(hname, 1024); host = _XGethostbyname(hname, hparams); @@ -843,15 +1169,17 @@ pointer client; * expectations of malloc, but this makes lint happier. */ -unsigned long * +#ifndef INTERNAL_MALLOC + +void * Xalloc (amount) unsigned long amount; { - char *malloc(); register pointer ptr; - if ((long)amount <= 0) + if ((long)amount <= 0) { return (unsigned long *)NULL; + } /* aligned extra on long word boundary */ amount = (amount + (sizeof(long) - 1)) & ~(sizeof(long) - 1); #ifdef MEMBUG @@ -859,8 +1187,9 @@ Xalloc (amount) ((random() % MEM_FAIL_SCALE) < Memory_fail)) return (unsigned long *)NULL; #endif - if (ptr = (pointer)malloc(amount)) + if ((ptr = (pointer)malloc(amount))) { return (unsigned long *)ptr; + } if (Must_have_memory) FatalError("Out of memory"); return (unsigned long *)NULL; @@ -871,11 +1200,10 @@ Xalloc (amount) * "no failure" realloc, alternate interface to Xalloc w/o Must_have_memory *****************/ -unsigned long * +void * XNFalloc (amount) unsigned long amount; { - char *malloc(); register pointer ptr; if ((long)amount <= 0) @@ -896,7 +1224,7 @@ XNFalloc (amount) * Xcalloc *****************/ -unsigned long * +void * Xcalloc (amount) unsigned long amount; { @@ -909,17 +1237,32 @@ Xcalloc (amount) } /***************** + * XNFcalloc + *****************/ + +void * +XNFcalloc (amount) + 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 *****************/ -unsigned long * +void * Xrealloc (ptr, amount) register pointer ptr; unsigned long amount; { - char *malloc(); - char *realloc(); - #ifdef MEMBUG if (!Must_have_memory && Memory_fail && ((random() % MEM_FAIL_SCALE) < Memory_fail)) @@ -948,14 +1291,15 @@ Xrealloc (ptr, amount) * "no failure" realloc, alternate interface to Xrealloc w/o Must_have_memory *****************/ -unsigned long * +void * XNFrealloc (ptr, amount) register pointer ptr; unsigned long amount; { if (( ptr = (pointer)Xrealloc( ptr, amount ) ) == NULL) { - FatalError( "Out of memory" ); + if ((long)amount > 0) + FatalError( "Out of memory" ); } return ((unsigned long *)ptr); } @@ -973,6 +1317,7 @@ Xfree(ptr) free((char *)ptr); } +void OsInitAllocator () { #ifdef MEMBUG @@ -985,24 +1330,51 @@ OsInitAllocator () 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; +} + void AuditPrefix(f) - char *f; + const char *f; { -#ifdef X_NOT_STDC_ENV - long tm; -#else time_t tm; -#endif char *autime, *s; if (*f != ' ') { time(&tm); autime = ctime(&tm); - if (s = strchr(autime, '\n')) + if ((s = strchr(autime, '\n'))) *s = '\0'; - if (s = strrchr(argvGlobal[0], '/')) + if ((s = strrchr(argvGlobal[0], '/'))) s++; else s = argvGlobal[0]; @@ -1010,96 +1382,669 @@ AuditPrefix(f) } } -/*VARARGS1*/ void -AuditF( -#if NeedVarargsPrototypes - char * f, ...) -#else - f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9) /* limit of ten args */ - char *f; - char *s0, *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9; -#endif +AuditF(const char * f, ...) { -#if NeedVarargsPrototypes va_list args; -#endif AuditPrefix(f); -#if NeedVarargsPrototypes va_start(args, f); VErrorF(f, args); va_end(args); -#else - ErrorF(f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9); -#endif } -/*VARARGS1*/ void -FatalError( -#if NeedVarargsPrototypes - char *f, ...) -#else -f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9) /* limit of ten args */ - char *f; - char *s0, *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9; -#endif +FatalError(const char *f, ...) { -#if NeedVarargsPrototypes va_list args; -#endif - ErrorF("\nFatal server error:\n"); -#if NeedVarargsPrototypes + 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); -#else - ErrorF(f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9); -#endif ErrorF("\n"); - AbortServer(); +#ifdef DDXOSFATALERROR + if (!beenhere) + OsVendorFatalError(); +#endif +#ifdef ABORTONFATALERROR + abort(); +#endif + if (!beenhere) { + beenhere = TRUE; + AbortServer(); + } else + abort(); /*NOTREACHED*/ } -#if NeedVarargsPrototypes void VErrorF(f, args) - char *f; + const char *f; va_list args; { #ifdef AIXV3 if (SyncOn) sync(); #else +#ifdef DDXOSVERRORF + if (OsVendorVErrorFProc) + OsVendorVErrorFProc(f, args); + else + vfprintf(stderr, f, args); +#else vfprintf(stderr, f, args); +#endif #endif /* AIXV3 */ } -#endif -/*VARARGS1*/ void -ErrorF( -#if NeedVarargsPrototypes - char * f, ...) -#else - f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9) /* limit of ten args */ - char *f; - char *s0, *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9; +VFatalError(const char *msg, va_list args) +{ + VErrorF(msg, args); + ErrorF("\n"); +#ifdef DDXOSFATALERROR + OsVendorFatalError(); #endif + AbortServer(); + /*NOTREACHED*/ +} + +void +ErrorF(const char * f, ...) { -#if NeedVarargsPrototypes va_list args; va_start(args, f); VErrorF(f, args); va_end(args); +} + +#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 + +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 +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 -#ifdef AIXV3 - if (SyncOn) - sync(); -#else /* not AIXV3 */ - fprintf( stderr, f, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9); -#endif /* AIXV3 */ + 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 + 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(command) + 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 */ + setgid(getgid()); + setuid(getuid()); + 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(command, type) + 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 */ + setgid(getgid()); + setuid(getuid()); + 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; +} + +int +Pclose(iop) + 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; +} +#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 +#define CHECK_EUID 1 +#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 +}; + +#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" \ + "XFree86@XFree86.org. 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" \ + "XFree86@XFree86.org. 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 (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); + break; + case ArgTooLong: + ErrorF("Command line argument number %d is too long\n", i); + ErrorF(ARGMSG); + break; + case UnprintableArg: + ErrorF("Command line argument number %d contains unprintable" + " characters\n", i); + ErrorF(ARGMSG); + break; + case EnvTooLong: + ErrorF("Environment variable `%s' is too long\n", e); + ErrorF(ENVMSG); + 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); + ErrorF(ENVMSG); + 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() +{ +#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 } diff --git a/os/xdmauth.c b/os/xdmauth.c index d6abd6a14..eb1385408 100644 --- a/os/xdmauth.c +++ b/os/xdmauth.c @@ -26,6 +26,7 @@ other dealings in this Software without prior written authorization from The Open Group. */ +/* $XFree86: xc/programs/Xserver/os/xdmauth.c,v 1.7 2002/11/05 05:50:34 keithp Exp $ */ /* * XDM-AUTHENTICATION-1 (XDMCP authentication) and @@ -348,6 +349,7 @@ XID id; switch (data_length) { case 16: /* auth from files is 16 bytes long */ +#ifdef XDMCP if (authFromXDMCP) { /* R5 xdm sent bogus authorization data in the accept packet, @@ -357,15 +359,18 @@ XID id; key_bits[0] = '\0'; } else +#endif { rho_bits = (unsigned char *) data; key_bits = (unsigned char *) (data + 8); } break; +#ifdef XDMCP case 8: /* auth from XDMCP is 8 bytes long */ rho_bits = rho.data; key_bits = (unsigned char *) data; break; +#endif default: return 0; } @@ -415,7 +420,7 @@ XdmCheckCookie (cookie_length, cookie, xclient, reason) } int -XdmResetCookie () +XdmResetCookie (void) { XdmAuthorizationPtr auth, next_auth; XdmClientAuthPtr client, next_client; @@ -493,10 +498,12 @@ char *data; rho_bits = (XdmAuthKeyPtr) data; key_bits = (XdmAuthKeyPtr) (data + 8); break; +#ifdef XDMCP case 8: rho_bits = ρ key_bits = (XdmAuthKeyPtr) data; break; +#endif default: return 0; } diff --git a/os/xdmcp.c b/os/xdmcp.c index 6d683b66d..b6a5db35f 100644 --- a/os/xdmcp.c +++ b/os/xdmcp.c @@ -13,6 +13,7 @@ * without express or implied warranty. * */ +/* $XFree86: xc/programs/Xserver/os/xdmcp.c,v 3.21 2002/03/11 16:22:28 keithp Exp $ */ #ifdef WIN32 /* avoid conflicting definitions */ @@ -27,13 +28,20 @@ #undef RT_FONT #undef RT_CURSOR #endif + #include "Xos.h" -#ifndef WIN32 + +#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 "X.h" #include "Xmd.h" @@ -44,6 +52,11 @@ #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> @@ -52,14 +65,11 @@ #ifdef XDMCP #undef REQUEST -#include "Xdmcp.h" +#include <X11/Xdmcp.h> #define X_INCLUDE_NETDB_H #include <X11/Xos_r.h> -extern char *display; -extern fd_set EnabledDevices; -extern fd_set AllClients; extern char *defaultDisplayClass; static int xdmcpSocket, sessionSocket; @@ -80,6 +90,19 @@ static char *xdmAuthCookie; static XdmcpBuffer buffer; static struct sockaddr_in ManagerAddress; +static struct sockaddr_in FromAddress; + +static void XdmcpAddHost( + struct sockaddr_in *from, + int fromlen, + ARRAY8Ptr AuthenticationName, + ARRAY8Ptr hostname, + ARRAY8Ptr status); + +static void XdmcpSelectHost( + struct sockaddr_in *host_sockaddr, + int host_len, + ARRAY8Ptr AuthenticationName); static void get_xdmcp_sock( #if NeedFunctionPrototypes @@ -149,20 +172,20 @@ static void recv_alive_msg( #endif ); -static XdmcpFatal( +static void XdmcpFatal( #if NeedFunctionPrototypes char */*type*/, ARRAY8Ptr /*status*/ #endif ); -static XdmcpWarning( +static void XdmcpWarning( #if NeedFunctionPrototypes char */*str*/ #endif ); -static get_manager_by_name( +static void get_manager_by_name( #if NeedFunctionPrototypes int /*argc*/, char **/*argv*/, @@ -170,19 +193,21 @@ static get_manager_by_name( #endif ); +static void get_fromaddr_by_name(int /*argc*/, char **/*argv*/, int /*i*/); + static void receive_packet( #if NeedFunctionPrototypes void #endif ); -static send_packet( +static void send_packet( #if NeedFunctionPrototypes void #endif ); -extern int XdmcpDeadSession( +extern void XdmcpDeadSession( #if NeedFunctionPrototypes char */*reason*/ #endif @@ -194,7 +219,7 @@ static void timeout( #endif ); -static restart( +static void restart( #if NeedFunctionPrototypes void #endif @@ -223,15 +248,19 @@ void XdmcpRegisterManufacturerDisplayID( #endif ); + static short xdm_udp_port = XDM_UDP_PORT; static Bool OneSession = FALSE; +static const char *xdm_from = NULL; -XdmcpUseMsg () +void +XdmcpUseMsg (void) { ErrorF("-query host-name contact named host for XDMCP\n"); ErrorF("-broadcast broadcast for XDMCP\n"); 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 @@ -241,9 +270,7 @@ XdmcpUseMsg () } int -XdmcpOptions(argc, argv, i) - int argc, i; - char **argv; +XdmcpOptions(int argc, char **argv, int i) { if (strcmp(argv[i], "-query") == 0) { get_manager_by_name(argc, argv, ++i); @@ -263,28 +290,44 @@ XdmcpOptions(argc, argv, i) return (i + 1); } if (strcmp(argv[i], "-port") == 0) { - ++i; + if (++i == argc) { + ErrorF("Xserver: missing port number in command line\n"); + exit(1); + } xdm_udp_port = 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) { - ++i; + if (++i == argc) { + ErrorF("Xserver: missing class name in command line\n"); + exit(1); + } defaultDisplayClass = argv[i]; return (i + 1); } #ifdef HASXDMAUTH if (strcmp(argv[i], "-cookie") == 0) { - ++i; + if (++i == argc) { + ErrorF("Xserver: missing cookie data in command line\n"); + exit(1); + } xdmAuthCookie = argv[i]; return (i + 1); } #endif if (strcmp(argv[i], "-displayID") == 0) { - ++i; + if (++i == argc) { + ErrorF("Xserver: missing displayID in command line\n"); + exit(1); + } XdmcpRegisterManufacturerDisplayID (argv[i], strlen (argv[i])); return (i + 1); } @@ -309,8 +352,7 @@ static struct sockaddr_in BroadcastAddresses[MAX_BROADCAST]; static int NumBroadcastAddresses; void -XdmcpRegisterBroadcastAddress (addr) - struct sockaddr_in *addr; +XdmcpRegisterBroadcastAddress (struct sockaddr_in *addr) { struct sockaddr_in *bcast; if (NumBroadcastAddresses >= MAX_BROADCAST) @@ -333,22 +375,22 @@ XdmcpRegisterBroadcastAddress (addr) static ARRAYofARRAY8 AuthenticationNames, AuthenticationDatas; typedef struct _AuthenticationFuncs { - Bool (*Validator)(); - Bool (*Generator)(); - Bool (*AddAuth)(); + ValidatorFunc Validator; + GeneratorFunc Generator; + AddAuthorFunc AddAuth; } AuthenticationFuncsRec, *AuthenticationFuncsPtr; static AuthenticationFuncsPtr AuthenticationFuncsList; void -XdmcpRegisterAuthentication (name, namelen, data, datalen, Validator, Generator, AddAuth) - char *name; - int namelen; - char *data; - int datalen; - Bool (*Validator)(); - Bool (*Generator)(); - Bool (*AddAuth)(); +XdmcpRegisterAuthentication ( + char *name, + int namelen, + char *data, + int datalen, + ValidatorFunc Validator, + GeneratorFunc Generator, + AddAuthorFunc AddAuth) { int i; ARRAY8 AuthenticationName, AuthenticationData; @@ -399,8 +441,7 @@ ARRAY8Ptr AuthenticationData = &noAuthenticationData; AuthenticationFuncsPtr AuthenticationFuncs; void -XdmcpSetAuthentication (name) - ARRAY8Ptr name; +XdmcpSetAuthentication (ARRAY8Ptr name) { int i; @@ -423,10 +464,10 @@ static ARRAYofARRAY8 ConnectionAddresses; static long xdmcpGeneration; void -XdmcpRegisterConnection (type, address, addrlen) - int type; - char *address; - int addrlen; +XdmcpRegisterConnection ( + int type, + char *address, + int addrlen) { int i; CARD8 *newAddress; @@ -437,6 +478,13 @@ XdmcpRegisterConnection (type, address, addrlen) XdmcpDisposeARRAYofARRAY8 (&ConnectionAddresses); xdmcpGeneration = serverGeneration; } + if (addrlen == sizeof(struct in_addr) && xdm_from != NULL) + { + /* Only register the requested address */ + if (memcmp(address, &FromAddress.sin_addr, addrlen) != 0) { + return; + } + } newAddress = (CARD8 *) xalloc (addrlen * sizeof (CARD8)); if (!newAddress) return; @@ -466,16 +514,14 @@ XdmcpRegisterConnection (type, address, addrlen) static ARRAYofARRAY8 AuthorizationNames; void -XdmcpRegisterAuthorizations () +XdmcpRegisterAuthorizations (void) { XdmcpDisposeARRAYofARRAY8 (&AuthorizationNames); RegisterAuthorizations (); } void -XdmcpRegisterAuthorization (name, namelen) - char *name; - int namelen; +XdmcpRegisterAuthorization (char *name, int namelen) { ARRAY8 authName; int i; @@ -501,9 +547,7 @@ XdmcpRegisterAuthorization (name, namelen) ARRAY8 DisplayClass; void -XdmcpRegisterDisplayClass (name, length) - char *name; - int length; +XdmcpRegisterDisplayClass (char *name, int length) { int i; @@ -521,9 +565,7 @@ XdmcpRegisterDisplayClass (name, length) ARRAY8 ManufacturerDisplayID; void -XdmcpRegisterManufacturerDisplayID (name, length) - char *name; - int length; +XdmcpRegisterManufacturerDisplayID (char *name, int length) { int i; @@ -540,7 +582,7 @@ XdmcpRegisterManufacturerDisplayID (name, length) */ void -XdmcpInit() +XdmcpInit(void) { state = XDM_INIT_STATE; #ifdef HASXDMAUTH @@ -562,7 +604,7 @@ XdmcpInit() } void -XdmcpReset () +XdmcpReset (void) { state = XDM_INIT_STATE; if (state != XDM_OFF) @@ -581,8 +623,7 @@ XdmcpReset () */ void -XdmcpOpenDisplay(sock) - int sock; +XdmcpOpenDisplay(int sock) { if (state != XDM_AWAIT_MANAGE_RESPONSE) return; @@ -591,8 +632,7 @@ XdmcpOpenDisplay(sock) } void -XdmcpCloseDisplay(sock) - int sock; +XdmcpCloseDisplay(int sock) { if ((state != XDM_RUN_SESSION && state != XDM_AWAIT_ALIVE_RESPONSE) || sessionSocket != sock) @@ -614,40 +654,23 @@ XdmcpCloseDisplay(sock) /*ARGSUSED*/ static void -XdmcpBlockHandler(data, wt, pReadmask) - pointer data; /* unused */ - struct timeval **wt; - pointer pReadmask; +XdmcpBlockHandler( + pointer data, /* unused */ + struct timeval **wt, + pointer pReadmask) { fd_set *LastSelectMask = (fd_set*)pReadmask; - CARD32 millisToGo, wtMillis; - static struct timeval waittime; + CARD32 millisToGo; if (state == XDM_OFF) return; FD_SET(xdmcpSocket, LastSelectMask); if (timeOutTime == 0) return; - millisToGo = GetTimeInMillis(); - if (millisToGo < timeOutTime) - millisToGo = timeOutTime - millisToGo; - else + millisToGo = timeOutTime - GetTimeInMillis(); + if ((int) millisToGo < 0) millisToGo = 0; - if (*wt == NULL) - { - waittime.tv_sec = (millisToGo) / 1000; - waittime.tv_usec = 1000 * (millisToGo % 1000); - *wt = &waittime; - } - else - { - wtMillis = (*wt)->tv_sec * 1000 + (*wt)->tv_usec / 1000; - if (millisToGo < wtMillis) - { - (*wt)->tv_sec = (millisToGo) / 1000; - (*wt)->tv_usec = 1000 * (millisToGo % 1000); - } - } + AdjustWaitForDelay (wt, millisToGo); } /* @@ -658,10 +681,10 @@ XdmcpBlockHandler(data, wt, pReadmask) /*ARGSUSED*/ static void -XdmcpWakeupHandler(data, i, pReadmask) - pointer data; /* unused */ - int i; - pointer pReadmask; +XdmcpWakeupHandler( + pointer data, /* unused */ + int i, + pointer pReadmask) { fd_set* LastSelectMask = (fd_set*)pReadmask; fd_set devicesReadable; @@ -686,7 +709,7 @@ XdmcpWakeupHandler(data, i, pReadmask) if (XFD_ANYSET(&AllClients) && state == XDM_RUN_SESSION) timeOutTime = GetTimeInMillis() + keepaliveDormancy * 1000; } - else if (timeOutTime && GetTimeInMillis() >= timeOutTime) + else if (timeOutTime && (int) (GetTimeInMillis() - timeOutTime) >= 0) { if (state == XDM_RUN_SESSION) { @@ -703,10 +726,11 @@ XdmcpWakeupHandler(data, i, pReadmask) * user's host menu when the user selects a host */ -XdmcpSelectHost(host_sockaddr, host_len, AuthenticationName) - struct sockaddr_in *host_sockaddr; - int host_len; - ARRAY8Ptr AuthenticationName; +static void +XdmcpSelectHost( + struct sockaddr_in *host_sockaddr, + int host_len, + ARRAY8Ptr AuthenticationName) { state = XDM_START_CONNECTION; memmove(&req_sockaddr, host_sockaddr, host_len); @@ -722,9 +746,13 @@ XdmcpSelectHost(host_sockaddr, host_len, AuthenticationName) */ /*ARGSUSED*/ -XdmcpAddHost(from, fromlen, AuthenticationName, hostname, status) - struct sockaddr_in *from; - ARRAY8Ptr AuthenticationName, hostname, status; +static void +XdmcpAddHost( + struct sockaddr_in *from, + int fromlen, + ARRAY8Ptr AuthenticationName, + ARRAY8Ptr hostname, + ARRAY8Ptr status) { XdmcpSelectHost(from, fromlen, AuthenticationName); } @@ -737,14 +765,14 @@ XdmcpAddHost(from, fromlen, AuthenticationName, hostname, status) ARRAY8 UnwillingMessage = { (CARD8) 14, (CARD8 *) "Host unwilling" }; static void -receive_packet() +receive_packet(void) { struct sockaddr_in from; int fromlen = sizeof(struct sockaddr_in); XdmcpHeader header; /* read message off socket */ - if (!XdmcpFill (xdmcpSocket, &buffer, (struct sockaddr *) &from, &fromlen)) + if (!XdmcpFill (xdmcpSocket, &buffer, (XdmcpNetaddr) &from, &fromlen)) return; /* reset retransmission backoff */ @@ -785,8 +813,8 @@ receive_packet() * send the appropriate message given the current state */ -static -send_packet() +static void +send_packet(void) { int rtx; switch (state) { @@ -804,6 +832,8 @@ send_packet() case XDM_KEEPALIVE: send_keepalive_msg(); break; + default: + break; } rtx = (XDM_MIN_RTX << timeOutRtx); if (rtx > XDM_MAX_RTX) @@ -816,8 +846,8 @@ send_packet() * timeouts, or Keepalive failure. */ -XdmcpDeadSession (reason) - char *reason; +void +XdmcpDeadSession (char *reason) { ErrorF ("XDM: %s, declaring session dead\n", reason); state = XDM_INIT_STATE; @@ -833,7 +863,7 @@ XdmcpDeadSession (reason) */ static void -timeout() +timeout(void) { timeOutRtx++; if (state == XDM_AWAIT_ALIVE_RESPONSE && timeOutRtx >= XDM_KA_RTX_LIMIT ) @@ -869,31 +899,37 @@ timeout() case XDM_AWAIT_ALIVE_RESPONSE: state = XDM_KEEPALIVE; break; + default: + break; } send_packet(); } -static -restart() +static void +restart(void) { state = XDM_INIT_STATE; timeOutRtx = 0; send_packet(); } -XdmcpCheckAuthentication (Name, Data, packet_type) - ARRAY8Ptr Name, Data; - int packet_type; +int +XdmcpCheckAuthentication ( + ARRAY8Ptr Name, + ARRAY8Ptr Data, + int packet_type) { return (XdmcpARRAY8Equal (Name, AuthenticationName) && (AuthenticationName->length == 0 || (*AuthenticationFuncs->Validator) (AuthenticationData, Data, packet_type))); } -XdmcpAddAuthorization (name, data) - ARRAY8Ptr name, data; +int +XdmcpAddAuthorization ( + ARRAY8Ptr name, + ARRAY8Ptr data) { - Bool (*AddAuth)(), AddAuthorization(); + AddAuthorFunc AddAuth; if (AuthenticationFuncs && AuthenticationFuncs->AddAuth) AddAuth = AuthenticationFuncs->AddAuth; @@ -911,10 +947,8 @@ XdmcpAddAuthorization (name, data) */ static void -get_xdmcp_sock() +get_xdmcp_sock(void) { - int soopts = 1; - #ifdef STREAMSCONN struct netconfig *nconf; @@ -952,6 +986,8 @@ get_xdmcp_sock() freenetconfigent(nconf); #else + int soopts = 1; + if ((xdmcpSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) XdmcpWarning("UDP socket creation failed"); #ifdef SO_BROADCAST @@ -959,11 +995,18 @@ get_xdmcp_sock() 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, + sizeof(FromAddress)) < 0) { + ErrorF("Xserver: failed to bind to -from address: %s\n", xdm_from); + exit(1); + } + } #endif /* STREAMSCONN */ } static void -send_query_msg() +send_query_msg(void) { XdmcpHeader header; Bool broadcast = FALSE; @@ -984,6 +1027,8 @@ send_query_msg() header.opcode = (CARD16) INDIRECT_QUERY; state = XDM_COLLECT_INDIRECT_QUERY; break; + default: + break; } header.length = 1; for (i = 0; i < AuthenticationNames.length; i++) @@ -996,21 +1041,21 @@ send_query_msg() int i; for (i = 0; i < NumBroadcastAddresses; i++) - XdmcpFlush (xdmcpSocket, &buffer, &BroadcastAddresses[i], + XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &BroadcastAddresses[i], sizeof (struct sockaddr_in)); } else { - XdmcpFlush (xdmcpSocket, &buffer, &ManagerAddress, + XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &ManagerAddress, sizeof (ManagerAddress)); } } static void -recv_willing_msg(from, fromlen, length) - struct sockaddr_in *from; - int fromlen; - unsigned length; +recv_willing_msg( + struct sockaddr_in *from, + int fromlen, + unsigned length) { ARRAY8 authenticationName; ARRAY8 hostname; @@ -1035,6 +1080,8 @@ recv_willing_msg(from, fromlen, length) case XDM_COLLECT_INDIRECT_QUERY: XdmcpAddHost(from, fromlen, &authenticationName, &hostname, &status); break; + default: + break; } } } @@ -1044,7 +1091,7 @@ recv_willing_msg(from, fromlen, length) } static void -send_request_msg() +send_request_msg(void) { XdmcpHeader header; int length; @@ -1089,13 +1136,12 @@ send_request_msg() XdmcpDisposeARRAY8 (&authenticationData); XdmcpWriteARRAYofARRAY8 (&buffer, &AuthorizationNames); XdmcpWriteARRAY8 (&buffer, &ManufacturerDisplayID); - if (XdmcpFlush (xdmcpSocket, &buffer, &req_sockaddr, req_socklen)) + if (XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen)) state = XDM_AWAIT_REQUEST_RESPONSE; } static void -recv_accept_msg(length) - unsigned length; +recv_accept_msg(unsigned length) { CARD32 AcceptSessionID; ARRAY8 AcceptAuthenticationName, AcceptAuthenticationData; @@ -1145,8 +1191,7 @@ recv_accept_msg(length) } static void -recv_decline_msg(length) - unsigned length; +recv_decline_msg(unsigned length) { ARRAY8 status, DeclineAuthenticationName, DeclineAuthenticationData; @@ -1172,7 +1217,7 @@ recv_decline_msg(length) } static void -send_manage_msg() +send_manage_msg(void) { XdmcpHeader header; @@ -1186,12 +1231,11 @@ send_manage_msg() XdmcpWriteCARD16 (&buffer, DisplayNumber); XdmcpWriteARRAY8 (&buffer, &DisplayClass); state = XDM_AWAIT_MANAGE_RESPONSE; - XdmcpFlush (xdmcpSocket, &buffer, &req_sockaddr, req_socklen); + XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen); } static void -recv_refuse_msg(length) - unsigned length; +recv_refuse_msg(unsigned length) { CARD32 RefusedSessionID; @@ -1210,8 +1254,7 @@ recv_refuse_msg(length) } static void -recv_failed_msg(length) - unsigned length; +recv_failed_msg(unsigned length) { CARD32 FailedSessionID; ARRAY8 status; @@ -1232,7 +1275,7 @@ recv_failed_msg(length) } static void -send_keepalive_msg() +send_keepalive_msg(void) { XdmcpHeader header; @@ -1245,16 +1288,14 @@ send_keepalive_msg() XdmcpWriteCARD32 (&buffer, SessionID); state = XDM_AWAIT_ALIVE_RESPONSE; - XdmcpFlush (xdmcpSocket, &buffer, &req_sockaddr, req_socklen); + XdmcpFlush (xdmcpSocket, &buffer, (XdmcpNetaddr) &req_sockaddr, req_socklen); } static void -recv_alive_msg (length) - unsigned length; +recv_alive_msg (unsigned length) { CARD8 SessionRunning; CARD32 AliveSessionID; - int dormancy; if (state != XDM_AWAIT_ALIVE_RESPONSE) return; @@ -1283,33 +1324,31 @@ recv_alive_msg (length) } } -static -XdmcpFatal (type, status) - char *type; - ARRAY8Ptr status; +static void +XdmcpFatal ( + char *type, + ARRAY8Ptr status) { - extern void AbortDDX(); - - ErrorF ("XDMCP fatal error: %s %*.*s\n", type, + FatalError ("XDMCP fatal error: %s %*.*s\n", type, status->length, status->length, status->data); - AbortDDX (); - exit (1); } -static -XdmcpWarning(str) - char *str; +static void +XdmcpWarning(char *str) { ErrorF("XDMCP warning: %s\n", str); } -static -get_manager_by_name(argc, argv, i) - int argc, i; - char **argv; +static void +get_manager_by_name( + int argc, + char **argv, + int i) { struct hostent *hep; +#ifdef XTHREADS_NEEDS_BYNAMEPARAMS _Xgethostbynameparams hparams; +#endif if (i == argc) { @@ -1336,6 +1375,46 @@ get_manager_by_name(argc, argv, i) exit (1); } } + +static void +get_fromaddr_by_name( + int argc, + char **argv, + int i) +{ + struct hostent *hep; +#ifdef XTHREADS_NEEDS_BYNAMEPARAMS + _Xgethostbynameparams hparams; +#endif + + if (i == argc) + { + ErrorF("Xserver: missing -from host name in command line\n"); + exit(1); + } + if (!(hep = _XGethostbyname(argv[i], hparams))) + { + ErrorF("Xserver: unknown host: %s\n", argv[i]); + exit(1); + } + if (hep->h_length == sizeof (struct in_addr)) + { + memset(&FromAddress, 0, sizeof(FromAddress)); + memmove(&FromAddress.sin_addr, hep->h_addr, hep->h_length); +#ifdef BSD44SOCKETS + FromAddress.sin_len = sizeof(FromAddress); +#endif + FromAddress.sin_family = AF_INET; + FromAddress.sin_port = 0; + } + else + { + ErrorF ("Xserver: -from host on strange network %s\n", argv[i]); + exit (1); + } + xdm_from = argv[i]; +} + #else static int xdmcp_non_empty; /* avoid complaint by ranlib */ #endif /* XDMCP */ |