home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / X / mit / lib / X / XOpenDis.c.orig < prev    next >
Encoding:
Text File  |  1993-07-21  |  24.4 KB  |  911 lines

  1. /*
  2.  * $XConsortium: XOpenDis.c,v 11.120 91/09/09 14:47:58 rws Exp $
  3.  */
  4.  
  5. /* Copyright    Massachusetts Institute of Technology    1985, 1986    */
  6.  
  7. /*
  8. Permission to use, copy, modify, distribute, and sell this software and its
  9. documentation for any purpose is hereby granted without fee, provided that
  10. the above copyright notice appear in all copies and that both that
  11. copyright notice and this permission notice appear in supporting
  12. documentation, and that the name of M.I.T. not be used in advertising or
  13. publicity pertaining to distribution of the software without specific,
  14. written prior permission.  M.I.T. makes no representations about the
  15. suitability of this software for any purpose.  It is provided "as is"
  16. without express or implied warranty.
  17. */
  18.  
  19. /* Converted to V11 by jg */
  20.  
  21. #include <X11/Xlibint.h>
  22. #include <X11/Xos.h>
  23. #ifdef HASXDMAUTH
  24. #include "Xlibnet.h"
  25. #if TCPCONN
  26. #include <sys/socket.h>
  27. #endif
  28. #endif
  29. #include <X11/Xauth.h>
  30. #include <X11/Xatom.h>
  31.  
  32. #ifdef STREAMSCONN
  33. #ifdef SVR4
  34. #include <tiuser.h>
  35. #else
  36. #undef HASXDMAUTH
  37. #endif
  38. #endif
  39.  
  40. #ifdef SECURE_RPC
  41. #include <rpc/rpc.h>
  42. #ifdef ultrix
  43. #include <time.h>
  44. #include <rpc/auth_des.h>
  45. #endif
  46. #endif
  47.  
  48. #include <stdio.h>
  49.  
  50. #ifdef X_NOT_STDC_ENV
  51. extern char *getenv();
  52. #endif
  53.  
  54. extern int _Xdebug;
  55.  
  56. #ifndef lint
  57. static int lock;    /* get rid of ifdefs when locking implemented */
  58. #endif
  59.  
  60. static xReq _dummy_request = {
  61.     0, 0, 0
  62. };
  63.  
  64. /*
  65.  * First, a routine for setting authorization data
  66.  */
  67. static int xauth_namelen = 0;
  68. static char *xauth_name = NULL;     /* NULL means use default mechanism */
  69. static int xauth_datalen = 0;
  70. static char *xauth_data = NULL;     /* NULL means get default data */
  71.  
  72. /*
  73.  * This is a list of the authorization names which Xlib currently supports.
  74.  * Xau will choose the file entry which matches the earliest entry in this
  75.  * array, allowing us to prioritize these in terms of the most secure first
  76.  */
  77.  
  78. static char *default_xauth_names[] = {
  79. #ifdef SECURE_RPC
  80.     "SUN-DES-1",
  81. #endif
  82. #ifdef HASXDMAUTH
  83.     "XDM-AUTHORIZATION-1",
  84. #endif
  85.     "MIT-MAGIC-COOKIE-1"
  86. };
  87.  
  88. static int default_xauth_lengths[] = {
  89. #ifdef SECURE_RPC
  90.     9,        /* strlen ("SUN-DES-1") */
  91. #endif
  92. #ifdef HASXDMAUTH
  93.     19,        /* strlen ("XDM-AUTHORIZATION-1") */
  94. #endif
  95.     18        /* strlen ("MIT-MAGIC-COOKIE-1") */
  96. };
  97.  
  98. #define NUM_DEFAULT_AUTH    (sizeof (default_xauth_names) / sizeof (default_xauth_names[0]))
  99.     
  100. static char **xauth_names = default_xauth_names;
  101. static int  *xauth_lengths = default_xauth_lengths;
  102.  
  103. static int  xauth_names_length = NUM_DEFAULT_AUTH;
  104.  
  105. static OutOfMemory();
  106.  
  107. void XSetAuthorization (name, namelen, data, datalen)
  108.     int namelen, datalen;        /* lengths of name and data */
  109.     char *name, *data;            /* NULL or arbitrary array of bytes */
  110. {
  111.     char *tmpname, *tmpdata;
  112.  
  113.     if (xauth_name) Xfree (xauth_name);     /* free any existing data */
  114.     if (xauth_data) Xfree (xauth_data);
  115.  
  116.     xauth_name = xauth_data = NULL;    /* mark it no longer valid */
  117.     xauth_namelen = xauth_datalen = 0;
  118.  
  119.     if (namelen < 0) namelen = 0;    /* check for bogus inputs */
  120.     if (datalen < 0) datalen = 0;    /* maybe should return? */
  121.  
  122.     if (namelen > 0)  {            /* try to allocate space */
  123.     tmpname = Xmalloc ((unsigned) namelen);
  124.     if (!tmpname) return;
  125.     bcopy (name, tmpname, namelen);
  126.     } else {
  127.     tmpname = NULL;
  128.     }
  129.  
  130.     if (datalen > 0)  {
  131.     tmpdata = Xmalloc ((unsigned) datalen);
  132.     if (!tmpdata) {
  133.         if (tmpname) (void) Xfree (tmpname);
  134.         return;
  135.     }
  136.     bcopy (data, tmpdata, datalen);
  137.     } else {
  138.     tmpdata = NULL;
  139.     }
  140.  
  141.     xauth_name = tmpname;        /* and store the suckers */
  142.     xauth_namelen = namelen;
  143.     if (tmpname)
  144.     {
  145.     xauth_names = &xauth_name;
  146.     xauth_lengths = &xauth_namelen;
  147.     xauth_names_length = 1;
  148.     }
  149.     else
  150.     {
  151.     xauth_names = default_xauth_names;
  152.     xauth_lengths = default_xauth_lengths;
  153.     xauth_names_length = NUM_DEFAULT_AUTH;
  154.     }
  155.     xauth_data = tmpdata;
  156.     xauth_datalen = datalen;
  157.     return;
  158. }
  159.  
  160. #ifdef SECURE_RPC
  161. /*
  162.  * Create a credential that we can send to the X server.
  163.  */
  164. static int
  165. auth_ezencode(servername, window, cred_out, len)
  166.         char           *servername;
  167.         int             window;
  168.     char           *cred_out;
  169.         int            *len;
  170. {
  171.         AUTH           *a;
  172.         XDR             xdr;
  173.  
  174.         a = authdes_create(servername, window, NULL, NULL);
  175.         if (a == (AUTH *)NULL) {
  176.                 perror("auth_create");
  177.                 return 0;
  178.         }
  179.         xdrmem_create(&xdr, cred_out, *len, XDR_ENCODE);
  180.         if (AUTH_MARSHALL(a, &xdr) == FALSE) {
  181.                 perror("auth_marshall");
  182.                 AUTH_DESTROY(a);
  183.                 return 0;
  184.         }
  185.         *len = xdr_getpos(&xdr);
  186.         AUTH_DESTROY(a);
  187.     return 1;
  188. }
  189. #endif
  190.  
  191. extern Bool _XWireToEvent();
  192. extern Status _XUnknownNativeEvent();
  193. extern Bool _XUnknownWireEvent();
  194. /* 
  195.  * Connects to a server, creates a Display object and returns a pointer to
  196.  * the newly created Display back to the caller.
  197.  */
  198. #if NeedFunctionPrototypes
  199. Display *XOpenDisplay (
  200.     register _Xconst char *display)
  201. #else
  202. Display *XOpenDisplay (display)
  203.     register char *display;
  204. #endif
  205. {
  206.     register Display *dpy;        /* New Display object being created. */
  207.     register int i;
  208.     int j, k;            /* random iterator indexes */
  209.     char *display_name;        /* pointer to display name */
  210.     int endian;            /* to determine which endian. */
  211.     xConnClientPrefix client;    /* client information */
  212.     xConnSetupPrefix prefix;    /* prefix information */
  213.     int vendorlen;            /* length of vendor string */
  214.     char *setup;            /* memory allocated at startup */
  215.     char *fullname = NULL;        /* expanded name of display */
  216.     int idisplay;            /* display number */
  217.     int iscreen;            /* screen number */
  218.     union {
  219.         xConnSetup *setup;
  220.         char *failure;
  221.         char *vendor;
  222.         xPixmapFormat *sf;
  223.         xWindowRoot *rp;
  224.         xDepth *dp;
  225.         xVisualType *vp;
  226.     } u;                /* proto data returned from server */
  227.     long setuplength;    /* number of bytes in setup message */
  228.     Xauth *authptr = NULL;
  229.     char *server_addr = NULL;
  230.     int server_addrlen = 0;
  231.     char *conn_auth_name, *conn_auth_data;
  232.     int conn_auth_namelen, conn_auth_datalen;
  233.     int conn_family;
  234.     unsigned long mask;
  235.     extern Bool _XSendClientPrefix();
  236.     extern int _XConnectDisplay();
  237.     extern XID _XAllocID();
  238. #ifdef SECURE_RPC
  239.     char    rpc_cred[MAX_AUTH_BYTES];
  240. #endif
  241.  
  242. #ifdef HASXDMAUTH
  243.     char    xdmcp_data[192/8];
  244. #endif
  245.  
  246.     /*
  247.      * If the display specifier string supplied as an argument to this 
  248.      * routine is NULL or a pointer to NULL, read the DISPLAY variable.
  249.      */
  250.     if (display == NULL || *display == '\0') {
  251.         if ((display_name = getenv("DISPLAY")) == NULL) {
  252.             /* Oops! No DISPLAY environment variable - error. */
  253.             return(NULL);
  254.         }
  255.     }
  256.     else {
  257.         /* Display is non-NULL, copy the pointer */
  258.         display_name = (char *)display;
  259.     }
  260.  
  261. /*
  262.  * Lock against other threads trying to access global data (like the error
  263.  * handlers and display list).
  264.  */
  265.     LockMutex(&lock);
  266.  
  267. /*
  268.  * Set the default error handlers.  This allows the global variables to
  269.  * default to NULL for use with shared libraries.
  270.  */
  271.     if (_XErrorFunction == NULL) (void) XSetErrorHandler (NULL);
  272.     if (_XIOErrorFunction == NULL) (void) XSetIOErrorHandler (NULL);
  273.  
  274. /*
  275.  * Attempt to allocate a display structure. Return NULL if allocation fails.
  276.  */
  277.     if ((dpy = (Display *)Xcalloc(1, sizeof(Display))) == NULL) {
  278.         UnlockMutex(&lock);
  279.         return(NULL);
  280.     }
  281.  
  282. /*
  283.  * Call the Connect routine to get the network socket. If -1 is returned, the
  284.  * connection failed. The connect routine will set fullname to point to the
  285.  * expanded name.
  286.  */
  287.  
  288.     if ((dpy->fd = _XConnectDisplay (display_name, &fullname, &idisplay,
  289.                      &iscreen, &conn_family,
  290.                      &server_addrlen, &server_addr)) < 0) {
  291.         Xfree ((char *) dpy);
  292.         UnlockMutex(&lock);
  293.         return(NULL);
  294.     }
  295.  
  296. /*
  297.  * Look up the authorization protocol name and data if necessary.
  298.  */
  299.     if (xauth_name && xauth_data) {
  300.         conn_auth_namelen = xauth_namelen;
  301.         conn_auth_name = xauth_name;
  302.         conn_auth_datalen = xauth_datalen;
  303.         conn_auth_data = xauth_data;
  304.     } else {
  305.         char dpynumbuf[40];        /* big enough to hold 2^64 and more */
  306.         (void) sprintf (dpynumbuf, "%d", idisplay);
  307.  
  308.         authptr = XauGetBestAuthByAddr ((unsigned short) conn_family,
  309.                     (unsigned short) server_addrlen,
  310.                     server_addr,
  311.                     (unsigned short) strlen (dpynumbuf),
  312.                     dpynumbuf,
  313.                     xauth_names_length,
  314.                     xauth_names,
  315.                     xauth_lengths);
  316.         if (authptr) {
  317.         conn_auth_namelen = authptr->name_length;
  318.         conn_auth_name = (char *)authptr->name;
  319.         conn_auth_datalen = authptr->data_length;
  320.         conn_auth_data = (char *)authptr->data;
  321.         } else {
  322.         conn_auth_namelen = 0;
  323.         conn_auth_name = NULL;
  324.         conn_auth_datalen = 0;
  325.         conn_auth_data = NULL;
  326.         }
  327.     }
  328. #ifdef HASXDMAUTH
  329.     /*
  330.      * build XDM-AUTHORIZATION-1 data
  331.      */
  332.     if (conn_auth_namelen == 19 &&
  333.         !strncmp (conn_auth_name, "XDM-AUTHORIZATION-1", 19))
  334.     {
  335.         int        i, j;
  336.         long    now;
  337.         for (j = 0; j < 8; j++)
  338.         xdmcp_data[j] = conn_auth_data[j];
  339. #ifdef STREAMSCONN /* && SVR4 */
  340.         {
  341.             struct netbuf    netb;
  342.             char        addrret[1024];
  343.     
  344.             netb.maxlen = sizeof addrret;
  345.             netb.buf = addrret;
  346.             if (t_getname (dpy->fd, &netb, LOCALNAME) == -1)
  347.             t_error ("t_getname");
  348.         /*
  349.          * XXX - assumes that the return data
  350.          * are in a struct sockaddr_in, and that
  351.          * the data structure is layed out in
  352.          * the normal fashion.  This WILL NOT WORK
  353.          * on a non 32-bit machine (same in Xstreams.c)
  354.          */
  355.         for (i = 4; i < 8; i++)
  356.             xdmcp_data[j++] = netb.buf[i];
  357.         for (i = 2; i < 4; i++)
  358.             xdmcp_data[j++] = netb.buf[i];
  359.         }
  360. #else
  361.         {
  362.             unsigned long    addr;
  363.             unsigned short    port;
  364. #ifdef TCPCONN
  365.             int        addrlen;
  366.             struct sockaddr_in    in_addr;
  367.     
  368.             addrlen = sizeof (in_addr);
  369.             if (getsockname (dpy->fd,
  370.                  (struct sockaddr *) &in_addr,
  371.                   &addrlen) != -1 &&
  372.             addrlen >= sizeof in_addr &&
  373.             in_addr.sin_family == AF_INET)
  374.             {
  375.             addr = ntohl (in_addr.sin_addr.s_addr);
  376.             port = ntohs (in_addr.sin_port);
  377.             }
  378.             else
  379. #endif
  380.             {
  381.             static unsigned long    unix_addr = 0xFFFFFFFF;
  382.             addr = unix_addr--;
  383.             port = getpid ();
  384.             }
  385.             xdmcp_data[j++] = (addr >> 24) & 0xFF;
  386.             xdmcp_data[j++] = (addr >> 16) & 0xFF;
  387.             xdmcp_data[j++] = (addr >>  8) & 0xFF;
  388.             xdmcp_data[j++] = (addr >>  0) & 0xFF;
  389.             xdmcp_data[j++] = (port >>  8) & 0xFF;
  390.             xdmcp_data[j++] = (port >>  0) & 0xFF;
  391.         }
  392. #endif
  393.         time (&now);
  394.         xdmcp_data[j++] = (now >> 24) & 0xFF;
  395.         xdmcp_data[j++] = (now >> 16) & 0xFF;
  396.         xdmcp_data[j++] = (now >>  8) & 0xFF;
  397.         xdmcp_data[j++] = (now >>  0) & 0xFF;
  398.         while (j < 192 / 8)
  399.         xdmcp_data[j++] = 0;
  400.         XdmcpWrap (xdmcp_data, conn_auth_data + 8,
  401.               xdmcp_data, j);
  402.         conn_auth_data = xdmcp_data;
  403.         conn_auth_datalen = j;
  404.     }
  405. #endif /* HASXDMAUTH */
  406. #ifdef SECURE_RPC
  407.         /*
  408.          * The SUN-DES-1 authorization protocol uses the
  409.          * "secure RPC" mechanism in SunOS 4.0+.
  410.          */
  411.         if (conn_auth_namelen == 9 && !strncmp(conn_auth_name,
  412.             "SUN-DES-1", 9)) {
  413.             static char servernetname[MAXNETNAMELEN + 1];
  414.  
  415.             /*
  416.              * Copy over the server's netname from the authorization
  417.              * data field filled in by XauGetAuthByAddr().
  418.              */
  419.             if (conn_auth_datalen > MAXNETNAMELEN) {
  420.                 return 0;
  421.             }
  422.             bcopy(conn_auth_data, servernetname, conn_auth_datalen);
  423.             servernetname[conn_auth_datalen] = '\0';
  424.  
  425.         conn_auth_datalen = sizeof (rpc_cred);
  426.             if (auth_ezencode(servernetname, 100, rpc_cred, &conn_auth_datalen))
  427.         conn_auth_data = rpc_cred;
  428.         else
  429.         conn_auth_data = NULL;
  430.         }
  431. #endif
  432.     if (server_addr) (void) Xfree (server_addr);
  433. /*
  434.  * The xConnClientPrefix describes the initial connection setup information
  435.  * and is followed by the authorization information.  Sites that are interested
  436.  * in security are strongly encouraged to use an authentication and 
  437.  * authorization system such as Kerberos.
  438.  */
  439.     endian = 1;
  440.     if (*(char *) &endian)
  441.         client.byteOrder = '\154'; /* 'l' */
  442.     else
  443.         client.byteOrder = '\102'; /* 'B' */
  444.     client.majorVersion = X_PROTOCOL;
  445.     client.minorVersion = X_PROTOCOL_REVISION;
  446.     client.nbytesAuthProto = conn_auth_namelen;
  447.     client.nbytesAuthString = conn_auth_datalen;
  448.     if (!_XSendClientPrefix(dpy, &client, conn_auth_name, conn_auth_data))
  449.     {
  450.         _XDisconnectDisplay (dpy->fd);
  451.         Xfree ((char *)dpy);
  452.         UnlockMutex(&lock);
  453.         return(NULL);
  454.     }        
  455.     if (authptr) XauDisposeAuth (authptr);
  456. /*
  457.  * Now see if connection was accepted...
  458.  */
  459.     _XRead (dpy, (char *)&prefix,(long)SIZEOF(xConnSetupPrefix));
  460.  
  461.     if (prefix.majorVersion < X_PROTOCOL) {
  462.         fprintf (stderr,
  463.        "Xlib:  warning, client built for newer rev (%d) than server (%d)!\r\n",
  464.              X_PROTOCOL, prefix.majorVersion);
  465.     }
  466.     if (prefix.minorVersion != X_PROTOCOL_REVISION) {
  467.         fprintf (stderr,
  468.      "Xlib:  warning, client is protocol rev %d, server is rev %d!\r\n",
  469.              X_PROTOCOL_REVISION, prefix.minorVersion);
  470.     }
  471.  
  472.     setuplength = prefix.length << 2;
  473.     if ( (u.setup = (xConnSetup *)
  474.           (setup =  Xmalloc ((unsigned) setuplength))) == NULL) {
  475.         _XDisconnectDisplay (dpy->fd);
  476.         Xfree ((char *)dpy);
  477.         UnlockMutex(&lock);
  478.         return(NULL);
  479.     }
  480.     _XRead (dpy, (char *)u.setup, setuplength);
  481. /*
  482.  * If the connection was not accepted by the server due to problems,
  483.  * give error message to the user....
  484.  */
  485.     if (prefix.success != xTrue) {
  486.         /* XXX - printing messages marks a bad programming interface */
  487.         fprintf (stderr, 
  488.              "%s:  connection to \"%s\" refused by server\r\n%s:  ",
  489.              "Xlib", fullname, "Xlib");
  490.         (void) fwrite (u.failure, sizeof(char),
  491.             (int)prefix.lengthReason, stderr);
  492.         (void) fwrite ("\r\n", sizeof(char), 2, stderr);
  493.         _XDisconnectDisplay (dpy->fd);
  494.         Xfree ((char *)dpy);
  495.         Xfree (setup);
  496.         UnlockMutex(&lock);
  497.         return (NULL);
  498.     }
  499.  
  500. /*
  501.  * We succeeded at authorization, so let us move the data into
  502.  * the display structure.
  503.  */
  504.     dpy->proto_major_version= prefix.majorVersion;
  505.     dpy->proto_minor_version= prefix.minorVersion;
  506.     dpy->release         = u.setup->release;
  507.     dpy->resource_base    = u.setup->ridBase;
  508.     dpy->resource_mask    = u.setup->ridMask;
  509.     dpy->min_keycode    = u.setup->minKeyCode;
  510.     dpy->max_keycode    = u.setup->maxKeyCode;
  511.     dpy->keysyms        = (KeySym *) NULL;
  512.     dpy->modifiermap    = NULL;
  513.     dpy->lock_meaning    = NoSymbol;
  514.     dpy->keysyms_per_keycode = 0;
  515.     dpy->current        = None;
  516.     dpy->xdefaults        = (char *)NULL;
  517.     dpy->scratch_length    = 0L;
  518.     dpy->scratch_buffer    = NULL;
  519.     dpy->key_bindings    = NULL;
  520.     dpy->motion_buffer    = u.setup->motionBufferSize;
  521.     dpy->nformats        = u.setup->numFormats;
  522.     dpy->nscreens        = u.setup->numRoots;
  523.     dpy->byte_order        = u.setup->imageByteOrder;
  524.     dpy->bitmap_unit    = u.setup->bitmapScanlineUnit;
  525.     dpy->bitmap_pad        = u.setup->bitmapScanlinePad;
  526.     dpy->bitmap_bit_order   = u.setup->bitmapBitOrder;
  527.     dpy->max_request_size    = u.setup->maxRequestSize;
  528.     dpy->ext_procs        = (_XExtension *)NULL;
  529.     dpy->ext_data        = (XExtData *)NULL;
  530.     dpy->ext_number     = 0;
  531.     dpy->event_vec[X_Error] = _XUnknownWireEvent;
  532.     dpy->event_vec[X_Reply] = _XUnknownWireEvent;
  533.     dpy->wire_vec[X_Error]  = _XUnknownNativeEvent;
  534.     dpy->wire_vec[X_Reply]  = _XUnknownNativeEvent;
  535.     for (i = KeyPress; i < LASTEvent; i++) {
  536.         dpy->event_vec[i]     = _XWireToEvent;
  537.         dpy->wire_vec[i]     = NULL;
  538.     }
  539.     for (i = LASTEvent; i < 128; i++) {
  540.         dpy->event_vec[i]     = _XUnknownWireEvent;
  541.         dpy->wire_vec[i]     = _XUnknownNativeEvent;
  542.     }
  543.     dpy->resource_id    = 0;
  544.     mask = dpy->resource_mask;
  545.     dpy->resource_shift    = 0;
  546.     while (!(mask & 1)) {
  547.         dpy->resource_shift++;
  548.         mask = mask >> 1;
  549.     }
  550.     dpy->db         = (struct _XrmHashBucketRec *)NULL;
  551.     dpy->cursor_font    = None;
  552.     dpy->flags        = 0;
  553. /* 
  554.  * Initialize pointers to NULL so that XFreeDisplayStructure will
  555.  * work if we run out of memory
  556.  */
  557.  
  558.     dpy->screens = NULL;
  559.     dpy->display_name = NULL;
  560.     dpy->vendor = NULL;
  561.     dpy->buffer = NULL;
  562.     dpy->atoms = NULL;
  563.     dpy->error_vec = NULL;
  564.     dpy->context_db = NULL;
  565.  
  566. /*
  567.  * now extract the vendor string...  String must be null terminated,
  568.  * padded to multiple of 4 bytes.
  569.  */
  570.     dpy->vendor = (char *) Xmalloc((unsigned) (u.setup->nbytesVendor + 1));
  571.     if (dpy->vendor == NULL) {
  572.         OutOfMemory(dpy, setup);
  573.         UnlockMutex(&lock);
  574.         return (NULL);
  575.     }
  576.     vendorlen = u.setup->nbytesVendor;
  577.      u.setup = (xConnSetup *) (((char *) u.setup) + sz_xConnSetup);
  578.       (void) strncpy(dpy->vendor, u.vendor, vendorlen);
  579.     dpy->vendor[vendorlen] = '\0';
  580.      vendorlen = (vendorlen + 3) & ~3;    /* round up */
  581.     bcopy (u.vendor + vendorlen, setup,
  582.            (int) setuplength - sz_xConnSetup - vendorlen);
  583.      u.vendor = setup;
  584. /*
  585.  * Now iterate down setup information.....
  586.  */
  587.     dpy->pixmap_format = 
  588.         (ScreenFormat *)Xmalloc(
  589.         (unsigned) (dpy->nformats *sizeof(ScreenFormat)));
  590.     if (dpy->pixmap_format == NULL) {
  591.             OutOfMemory (dpy, setup);
  592.         UnlockMutex(&lock);
  593.         return(NULL);
  594.     }
  595. /*
  596.  * First decode the Z axis Screen format information.
  597.  */
  598.     for (i = 0; i < dpy->nformats; i++) {
  599.         register ScreenFormat *fmt = &dpy->pixmap_format[i];
  600.         fmt->depth = u.sf->depth;
  601.         fmt->bits_per_pixel = u.sf->bitsPerPixel;
  602.         fmt->scanline_pad = u.sf->scanLinePad;
  603.         fmt->ext_data = NULL;
  604.         u.sf = (xPixmapFormat *) (((char *) u.sf) + sz_xPixmapFormat);
  605.     }
  606.  
  607. /*
  608.  * next the Screen structures.
  609.  */
  610.     dpy->screens = 
  611.         (Screen *)Xmalloc((unsigned) dpy->nscreens*sizeof(Screen));
  612.     if (dpy->screens == NULL) {
  613.             OutOfMemory (dpy, setup);
  614.         UnlockMutex(&lock);
  615.         return(NULL);
  616.     }
  617. /*
  618.  * Now go deal with each screen structure.
  619.  */
  620.     for (i = 0; i < dpy->nscreens; i++) {
  621.         register Screen *sp = &dpy->screens[i];
  622.         VisualID root_visualID = u.rp->rootVisualID;
  623.         sp->display        = dpy;
  624.         sp->root         = u.rp->windowId;
  625.         sp->cmap         = u.rp->defaultColormap;
  626.         sp->white_pixel = u.rp->whitePixel;
  627.         sp->black_pixel = u.rp->blackPixel;
  628.         sp->root_input_mask = u.rp->currentInputMask;
  629.         sp->width        = u.rp->pixWidth;
  630.         sp->height        = u.rp->pixHeight;
  631.         sp->mwidth        = u.rp->mmWidth;
  632.         sp->mheight        = u.rp->mmHeight;
  633.         sp->min_maps    = u.rp->minInstalledMaps;
  634.         sp->max_maps    = u.rp->maxInstalledMaps;
  635.         sp->root_visual = NULL;  /* filled in later, when we alloc Visuals */
  636.         sp->backing_store= u.rp->backingStore;
  637.         sp->save_unders = u.rp->saveUnders;
  638.         sp->root_depth  = u.rp->rootDepth;
  639.         sp->ndepths        = u.rp->nDepths;
  640.         sp->ext_data   = NULL;
  641.         u.rp = (xWindowRoot *) (((char *) u.rp) + sz_xWindowRoot);
  642. /*
  643.  * lets set up the depth structures.
  644.  */
  645.         sp->depths = (Depth *)Xmalloc(
  646.             (unsigned)sp->ndepths*sizeof(Depth));
  647.         if (sp->depths == NULL) {
  648.         OutOfMemory (dpy, setup);
  649.         UnlockMutex(&lock);
  650.         return(NULL);
  651.         }
  652.         /*
  653.          * for all depths on this screen.
  654.          */
  655.         for (j = 0; j < sp->ndepths; j++) {
  656.         Depth *dp = &sp->depths[j];
  657.         dp->depth = u.dp->depth;
  658.         dp->nvisuals = u.dp->nVisuals;
  659.         u.dp = (xDepth *) (((char *) u.dp) + sz_xDepth);
  660.         if (dp->nvisuals > 0) {
  661.             dp->visuals = 
  662.               (Visual *)Xmalloc((unsigned)dp->nvisuals*sizeof(Visual));
  663.             if (dp->visuals == NULL) {
  664.             OutOfMemory (dpy, setup);
  665.             UnlockMutex(&lock);
  666.             return(NULL);
  667.             }
  668.             for (k = 0; k < dp->nvisuals; k++) {
  669.             register Visual *vp = &dp->visuals[k];
  670.             if ((vp->visualid = u.vp->visualID) == root_visualID)
  671.                sp->root_visual = vp;
  672.             vp->class    = u.vp->class;
  673.             vp->bits_per_rgb= u.vp->bitsPerRGB;
  674.             vp->map_entries    = u.vp->colormapEntries;
  675.             vp->red_mask    = u.vp->redMask;
  676.             vp->green_mask    = u.vp->greenMask;
  677.             vp->blue_mask    = u.vp->blueMask;
  678.             vp->ext_data    = NULL;
  679.             u.vp = (xVisualType *) (((char *) u.vp) +
  680.                         sz_xVisualType);
  681.             }
  682.         } else {
  683.             dp->visuals = (Visual *) NULL;
  684.         }
  685.         }
  686.     }
  687.         
  688.  
  689. /*
  690.  * Setup other information in this display structure.
  691.  */
  692.     dpy->vnumber = X_PROTOCOL;
  693.     dpy->resource_alloc = _XAllocID;
  694.     dpy->synchandler = NULL;
  695.     dpy->request = 0;
  696.     dpy->last_request_read = 0;
  697.     dpy->default_screen = iscreen;  /* Value returned by ConnectDisplay */
  698.     dpy->last_req = (char *)&_dummy_request;
  699.  
  700.     /* Salt away the host:display string for later use */
  701.     dpy->display_name = fullname;
  702.  
  703.     /* Set up the output buffers. */
  704.     if ((dpy->bufptr = dpy->buffer = Xmalloc(BUFSIZE)) == NULL) {
  705.             OutOfMemory (dpy, setup);
  706.         UnlockMutex(&lock);
  707.         return(NULL);
  708.     }
  709.     dpy->bufmax = dpy->buffer + BUFSIZE;
  710.  
  711.     /* Set up the input event queue and input event queue parameters. */
  712.     dpy->head = dpy->tail = NULL;
  713.     dpy->qlen = 0;
  714.  
  715.     /* Set up free-function record */
  716.     if ((dpy->free_funcs = (_XFreeFuncRec *)Xcalloc(1,
  717.                             sizeof(_XFreeFuncRec)))
  718.         == NULL) {
  719.         OutOfMemory (dpy, setup);
  720.         UnlockMutex(&lock);
  721.         return(NULL);
  722.     }
  723.  
  724. /*
  725.  * Now start talking to the server to setup all other information...
  726.  */
  727.  
  728.     Xfree (setup);    /* all finished with setup information */
  729.  
  730. /*
  731.  * Make sure default screen is legal.
  732.  */
  733.     if (iscreen >= dpy->nscreens) {
  734.         OutOfMemory(dpy, (char *) NULL);
  735.         UnlockMutex(&lock);
  736.         return(NULL);
  737.     }
  738.  
  739. /*
  740.  * Set up other stuff clients are always going to use.
  741.  */
  742.     for (i = 0; i < dpy->nscreens; i++) {
  743.         register Screen *sp = &dpy->screens[i];
  744.         XGCValues values;
  745.         values.foreground = sp->black_pixel;
  746.         values.background = sp->white_pixel;
  747.         if ((sp->default_gc = XCreateGC (dpy, sp->root,
  748.                          GCForeground|GCBackground,
  749.                          &values)) == NULL) {
  750.         OutOfMemory(dpy, (char *) NULL);
  751.         UnlockMutex (&lock);
  752.         return (NULL);
  753.         }
  754.     }
  755. /*
  756.  * call into synchronization routine so that all programs can be
  757.  * forced synchronize
  758.  */
  759.     (void) XSynchronize(dpy, _Xdebug);
  760.  
  761. /*
  762.  * and done mucking with the display
  763.  */
  764.     UnlockDisplay(dpy);        /* didn't exist, so didn't lock */
  765.     UnlockMutex(&lock);
  766.  
  767. /*
  768.  * get the resource manager database off the root window.
  769.  */
  770.     {
  771.         Atom actual_type;
  772.         int actual_format;
  773.         unsigned long nitems;
  774.         unsigned long leftover;
  775.         char *xdef = NULL;
  776.  
  777.         if (XGetWindowProperty (dpy, RootWindow(dpy, 0),
  778.                     XA_RESOURCE_MANAGER, 0L, 100000000L, False,
  779.                     XA_STRING, &actual_type, &actual_format,
  780.                     &nitems, &leftover,
  781.                     (unsigned char **) &xdef) == Success) {
  782.         if ((actual_type == XA_STRING) && (actual_format == 8)) {
  783.             LockDisplay (dpy);
  784.             dpy->xdefaults = xdef;
  785.             UnlockDisplay (dpy);
  786.         } else if (xdef) {
  787.             Xfree (xdef);
  788.         }
  789.         }
  790.     }
  791.  
  792. #ifdef MOTIFBC
  793.     {
  794.         extern Display *_XHeadOfDisplayList;
  795.         _XHeadOfDisplayList = dpy;
  796.     }
  797. #endif
  798. /*
  799.  * and return successfully
  800.  */
  801.      return(dpy);
  802. }
  803.  
  804.  
  805. /* OutOfMemory is called if malloc fails.  XOpenDisplay returns NULL
  806.    after this returns. */
  807.  
  808. static OutOfMemory (dpy, setup)
  809.     Display *dpy;
  810.     char *setup;
  811.     {
  812.     _XDisconnectDisplay (dpy->fd);
  813.     _XFreeDisplayStructure (dpy);
  814.     if (setup) Xfree (setup);
  815.     }
  816.  
  817.  
  818. /* XFreeDisplayStructure frees all the storage associated with a 
  819.  * Display.  It is used by XOpenDisplay if it runs out of memory,
  820.  * and also by XCloseDisplay.   It needs to check whether all pointers
  821.  * are non-NULL before dereferencing them, since it may be called
  822.  * by XOpenDisplay before the Display structure is fully formed.
  823.  * XOpenDisplay must be sure to initialize all the pointers to NULL
  824.  * before the first possible call on this.
  825.  */
  826.  
  827. _XFreeDisplayStructure(dpy)
  828.     register Display *dpy;
  829. {
  830.     if (dpy->screens) {
  831.         register int i;
  832.  
  833.             for (i = 0; i < dpy->nscreens; i++) {
  834.         Screen *sp = &dpy->screens[i];
  835.  
  836.         if (sp->depths) {
  837.            register int j;
  838.  
  839.            for (j = 0; j < sp->ndepths; j++) {
  840.             Depth *dp = &sp->depths[j];
  841.  
  842.             if (dp->visuals) {
  843.                register int k;
  844.  
  845.                for (k = 0; k < dp->nvisuals; k++)
  846.                  _XFreeExtData (dp->visuals[k].ext_data);
  847.                Xfree ((char *) dp->visuals);
  848.                }
  849.             }
  850.  
  851.            Xfree ((char *) sp->depths);
  852.            }
  853.  
  854.         _XFreeExtData (sp->ext_data);
  855.         }
  856.  
  857.         Xfree ((char *)dpy->screens);
  858.         }
  859.     
  860.     if (dpy->pixmap_format) {
  861.         register int i;
  862.  
  863.         for (i = 0; i < dpy->nformats; i++)
  864.           _XFreeExtData (dpy->pixmap_format[i].ext_data);
  865.             Xfree ((char *)dpy->pixmap_format);
  866.         }
  867.  
  868.     if (dpy->display_name)
  869.        Xfree (dpy->display_name);
  870.     if (dpy->vendor)
  871.        Xfree (dpy->vendor);
  872.  
  873.         if (dpy->buffer)
  874.        Xfree (dpy->buffer);
  875.     if (dpy->atoms)
  876.         (*dpy->free_funcs->atoms)(dpy);
  877.     if (dpy->keysyms)
  878.        Xfree ((char *) dpy->keysyms);
  879.     if (dpy->modifiermap)
  880.        (*dpy->free_funcs->modifiermap)(dpy->modifiermap);
  881.     if (dpy->xdefaults)
  882.        Xfree (dpy->xdefaults);
  883.     if (dpy->key_bindings)
  884.        (*dpy->free_funcs->key_bindings)(dpy);
  885.     if (dpy->error_vec)
  886.         Xfree ((char *)dpy->error_vec);
  887.     if (dpy->context_db)
  888.        (*dpy->free_funcs->context_db)(dpy);
  889.     if (dpy->cms.defaultCCCs)
  890.        (*dpy->free_funcs->defaultCCCs)(dpy);
  891.     if (dpy->cms.clientCmaps)
  892.        (*dpy->free_funcs->clientCmaps)(dpy);
  893.     if (dpy->cms.perVisualIntensityMaps)
  894.        (*dpy->free_funcs->intensityMaps)(dpy);
  895.     if (dpy->im_filters)
  896.        (*dpy->free_funcs->im_filters)(dpy);
  897.  
  898.     while (dpy->ext_procs) {
  899.         _XExtension *ext = dpy->ext_procs;
  900.         dpy->ext_procs = ext->next;
  901.         if (ext->name)
  902.         Xfree (ext->name);
  903.         Xfree ((char *)ext);
  904.     }
  905.  
  906.     _XFreeExtData (dpy->ext_data);
  907.     Xfree ((char *)dpy->free_funcs);
  908.  
  909.     Xfree ((char *)dpy);
  910. }
  911.