OpenDis.c 28.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* nx-X11, NX protocol compression and NX extensions to this software     */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE which comes in the source       */
/* distribution.                                                          */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/*

Copyright 1985, 1986, 1998  The Open Group

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

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

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

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

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "Xlibint.h"
56 57 58
#if USE_XCB
#include "Xxcbint.h"
#else /* !USE_XCB */
59
#include <nx-X11/Xtrans/Xtrans.h>
60 61
#include <nx-X11/extensions/bigreqstr.h>
#endif /* USE_XCB */
62 63
#include <nx-X11/Xatom.h>
#include <nx-X11/Xresource.h>
64 65 66 67 68 69 70 71 72 73 74
#include <stdio.h>
#include "Xintconn.h"

#ifdef XKB
#include "XKBlib.h"
#endif /* XKB */

#ifdef NX_TRANS_SOCKET
extern void *_X11TransSocketProxyConnInfo(XtransConnInfo);
#endif

75
#if !USE_XCB
76 77 78 79 80 81
#define bignamelen (sizeof(XBigReqExtensionName) - 1)

typedef struct {
    unsigned long seq;
    int opcode;
} _XBigReqState;
82
#endif /* !USE_XCB */
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

#ifdef XTHREADS
#include "locking.h"
int  (*_XInitDisplayLock_fn)(Display *dpy) = NULL;
void (*_XFreeDisplayLock_fn)(Display *dpy) = NULL;

#define InitDisplayLock(d)	(_XInitDisplayLock_fn ? (*_XInitDisplayLock_fn)(d) : Success)
#define FreeDisplayLock(d)	if (_XFreeDisplayLock_fn) (*_XFreeDisplayLock_fn)(d)
#else
#define InitDisplayLock(dis) Success
#define FreeDisplayLock(dis)
#endif /* XTHREADS */

static xReq _dummy_request = {
	0, 0, 0
};

static void OutOfMemory(Display *dpy, char *setup);
101
#if !USE_XCB
102 103
static Bool _XBigReqHandler(Display *dpy, xReply *rep, char *buf, int len,
				XPointer data);
104
#endif /* !USE_XCB */
105

106
/*
107 108 109 110 111 112 113 114 115 116 117
 * Connects to a server, creates a Display object and returns a pointer to
 * the newly created Display back to the caller.
 */
Display *
XOpenDisplay (
	register _Xconst char *display)
{
	register Display *dpy;		/* New Display object being created. */
	register int i;
	int j, k;			/* random iterator indexes */
	char *display_name;		/* pointer to display name */
118
#if !USE_XCB
119 120
	int endian;			/* to determine which endian. */
	xConnClientPrefix client;	/* client information */
121 122 123 124 125
	int idisplay;			/* display number */
	int prefixread = 0;             /* setup prefix already read? */
	char *conn_auth_name, *conn_auth_data;
	int conn_auth_namelen, conn_auth_datalen;
#endif /* !USE_XCB */
126 127 128
	char *setup = NULL;		/* memory allocated at startup */
	char *fullname = NULL;		/* expanded name of display */
	int iscreen;			/* screen number */
129 130
	xConnSetupPrefix prefix;	/* prefix information */
	int vendorlen;			/* length of vendor string */
131 132 133 134 135 136 137 138 139 140 141 142
	union {
		xConnSetup *setup;
		char *failure;
		char *vendor;
		xPixmapFormat *sf;
		xWindowRoot *rp;
		xDepth *dp;
		xVisualType *vp;
	} u;				/* proto data returned from server */
	long setuplength;	/* number of bytes in setup message */
	long usedbytes = 0;     /* number of bytes we have processed */
	unsigned long mask;
143 144
	long int conn_buf_size;
	char *xlib_buffer_size;
145

146
#if !USE_XCB
147 148
	bzero((char *) &client, sizeof(client));
	bzero((char *) &prefix, sizeof(prefix));
149
#endif /* !USE_XCB */
150 151 152 153 154

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "\nXOpenDisplay: Called with display [%s].\n", display);
#endif
	/*
155
	 * If the display specifier string supplied as an argument to this
156 157 158 159 160 161 162 163 164 165 166 167
	 * routine is NULL or a pointer to NULL, read the DISPLAY variable.
	 */
	if (display == NULL || *display == '\0') {
		if ((display_name = getenv("DISPLAY")) == NULL) {
			/* Oops! No DISPLAY environment variable - error. */
			return(NULL);
		}
	}
	else {
		/* Display is non-NULL, copy the pointer */
		display_name = (char *)display;
	}
168

169 170 171 172 173 174 175 176 177 178
/*
 * Set the default error handlers.  This allows the global variables to
 * default to NULL for use with shared libraries.
 */
	if (_XErrorFunction == NULL) (void) XSetErrorHandler (NULL);
	if (_XIOErrorFunction == NULL) (void) XSetIOErrorHandler (NULL);

/*
 * Attempt to allocate a display structure. Return NULL if allocation fails.
 */
179
	if ((dpy = Xcalloc(1, sizeof(Display))) == NULL) {
180 181 182 183 184 185 186 187 188
		return(NULL);
	}

/*
 * Call the Connect routine to get the transport connection object.
 * If NULL is returned, the connection failed. The connect routine
 * will set fullname to point to the expanded name.
 */

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#if USE_XCB
	if(!_XConnectXCB(dpy, display, &fullname, &iscreen)) {
		/* Try falling back on other transports if no transport specified */
		const char *slash = strrchr(display_name, '/');
		if(slash == NULL) {
			const char *protocols[] = {"local", "unix", "tcp", "inet6", "inet", NULL};
			const char **s;
			size_t buf_size = strlen(display_name) + 7; // max strlen + 2 (null + /)
			char *buf = Xmalloc(buf_size * sizeof(char));

			if(buf) {
				for(s = protocols; buf && *s; s++) {
					snprintf(buf, buf_size, "%s/%s", *s, display_name);
					if(_XConnectXCB(dpy, buf, &fullname, &iscreen))
						goto fallback_success;
				}
				Xfree(buf);
			}
		}

		dpy->display_name = fullname;
		OutOfMemory(dpy, NULL);
		return NULL;
	}
fallback_success:
#else /* !USE_XCB */
215 216 217 218 219 220 221 222 223 224
	if ((dpy->trans_conn = _X11TransConnectDisplay (
					 display_name, &fullname, &idisplay,
					 &iscreen, &conn_auth_name,
					 &conn_auth_namelen, &conn_auth_data,
					 &conn_auth_datalen)) == NULL) {
		Xfree ((char *) dpy);
		return(NULL);
	}

	dpy->fd = _X11TransGetConnectionNumber (dpy->trans_conn);
225
#endif /* USE_XCB */
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST) 
        fprintf(stderr, "\nXOpenDisplay: Connected display with dpy->fd = [%d].\n", dpy->fd);
#endif
	/* Initialize as much of the display structure as we can.
	 * Initialize pointers to NULL so that XFreeDisplayStructure will
	 * work if we run out of memory before we finish initializing.
	 */
	dpy->display_name	= fullname;
	dpy->keysyms		= (KeySym *) NULL;
	dpy->modifiermap	= NULL;
	dpy->lock_meaning	= NoSymbol;
	dpy->keysyms_per_keycode = 0;
	dpy->xdefaults		= (char *)NULL;
	dpy->scratch_length	= 0L;
	dpy->scratch_buffer	= NULL;
	dpy->key_bindings	= NULL;
	dpy->ext_procs		= (_XExtension *)NULL;
	dpy->ext_data		= (XExtData *)NULL;
	dpy->ext_number 	= 0;
	dpy->event_vec[X_Error] = _XUnknownWireEvent;
	dpy->event_vec[X_Reply] = _XUnknownWireEvent;
	dpy->wire_vec[X_Error]  = _XUnknownNativeEvent;
	dpy->wire_vec[X_Reply]  = _XUnknownNativeEvent;
	for (i = KeyPress; i < LASTEvent; i++) {
	    dpy->event_vec[i] 	= _XWireToEvent;
	    dpy->wire_vec[i] 	= NULL;
	}
	for (i = LASTEvent; i < 128; i++) {
	    dpy->event_vec[i] 	= _XUnknownWireEvent;
	    dpy->wire_vec[i] 	= _XUnknownNativeEvent;
	}
	dpy->resource_id	= 0;
	dpy->db 		= (struct _XrmHashBucketRec *)NULL;
	dpy->cursor_font	= None;
	dpy->flags		= 0;
	dpy->async_handlers	= NULL;
	dpy->screens		= NULL;
	dpy->vendor		= NULL;
	dpy->buffer		= NULL;
	dpy->atoms		= NULL;
	dpy->error_vec		= NULL;
	dpy->context_db		= NULL;
	dpy->free_funcs		= NULL;
	dpy->pixmap_format	= NULL;
	dpy->cms.clientCmaps	= NULL;
	dpy->cms.defaultCCCs	= NULL;
	dpy->cms.perVisualIntensityMaps = NULL;
	dpy->im_filters		= NULL;
 	dpy->bigreq_size	= 0;
	dpy->lock		= NULL;
	dpy->lock_fns		= NULL;
	dpy->qfree		= NULL;
	dpy->next_event_serial_num = 1;
	dpy->im_fd_info		= NULL;
	dpy->im_fd_length	= 0;
	dpy->conn_watchers	= NULL;
	dpy->watcher_count	= 0;
	dpy->filedes		= NULL;
	dpy->flushes		= NULL;
	dpy->xcmisc_opcode	= 0;
	dpy->xkb_info		= NULL;

/*
 * Setup other information in this display structure.
 */
	dpy->vnumber = X_PROTOCOL;
	dpy->resource_alloc = _XAllocID;
	dpy->idlist_alloc = _XAllocIDs;
	dpy->synchandler = NULL;
	dpy->savedsynchandler = NULL;
	dpy->request = 0;
	dpy->last_request_read = 0;
	dpy->default_screen = iscreen;  /* Value returned by ConnectDisplay */
	dpy->last_req = (char *)&_dummy_request;

	/* Initialize the display lock */
	if (InitDisplayLock(dpy) != 0) {
	        OutOfMemory (dpy, setup);
		return(NULL);
	}

	if (!_XPollfdCacheInit(dpy)) {
	        OutOfMemory (dpy, setup);
		return(NULL);
311
	}
312 313 314 315 316 317 318 319

	/* Set up the output buffers. */
#ifndef XLIBDEFAULTBUFSIZE
#define XLIBDEFAULTBUFSIZE 16384 /* 16k */
#endif
#ifndef XLIBMINBUFSIZE
#define XLIBMINBUFSIZE BUFSIZE /* old default buffer size */
#endif
320 321 322 323 324 325 326 327 328 329 330 331 332
	xlib_buffer_size = getenv("XLIBBUFFERSIZE");

#ifdef __sun /* Backwards compatibility for old Solaris libX11 name */
	if (xlib_buffer_size == NULL)
	    xlib_buffer_size = getenv("XSUNBUFFERSIZE");
#endif

	if (xlib_buffer_size == NULL)
	    conn_buf_size = XLIBDEFAULTBUFSIZE;
	else
	    conn_buf_size = 1024 * strtol(xlib_buffer_size, NULL, 10);
	if (conn_buf_size < XLIBMINBUFSIZE)
	    conn_buf_size = XLIBMINBUFSIZE;
333 334 335 336 337
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST) 
    fprintf (stderr, "Xlib: Running with XLIBBUFFERSIZE [%d] XLIBMINBUFSIZE [%d] "
                 "buffer size [%ld].\n", XLIBDEFAULTBUFSIZE, XLIBMINBUFSIZE, conn_buf_size);
#endif

338 339 340 341 342 343 344 345 346 347
	if ((dpy->bufptr = dpy->buffer = Xcalloc(1, conn_buf_size)) == NULL) {
	    OutOfMemory (dpy, setup);
	    return(NULL);
	}
	dpy->bufmax = dpy->buffer + conn_buf_size;
#if USE_XCB
	dpy->xcb->real_bufmax = dpy->bufmax;
	dpy->bufmax = dpy->buffer;
#endif

348 349 350 351 352
	/* Set up the input event queue and input event queue parameters. */
	dpy->head = dpy->tail = NULL;
	dpy->qlen = 0;

	/* Set up free-function record */
353
	if ((dpy->free_funcs = Xcalloc(1, sizeof(_XFreeFuncRec))) == NULL) {
354 355 356 357
	    OutOfMemory (dpy, setup);
	    return(NULL);
	}

358
#if !USE_XCB
359 360 361
/*
 * The xConnClientPrefix describes the initial connection setup information
 * and is followed by the authorization information.  Sites that are interested
362
 * in security are strongly encouraged to use an authentication and
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
 * authorization system such as Kerberos.
 */
	endian = 1;
	if (*(char *) &endian)
	    client.byteOrder = '\154'; /* 'l' */
	else
	    client.byteOrder = '\102'; /* 'B' */
	client.majorVersion = X_PROTOCOL;
	client.minorVersion = X_PROTOCOL_REVISION;
	client.nbytesAuthProto = conn_auth_namelen;
	client.nbytesAuthString = conn_auth_datalen;
	prefixread = _XSendClientPrefix(dpy, &client,
					conn_auth_name, conn_auth_data,
					&prefix);
	if (prefixread < 0)
	{
	    _XDisconnectDisplay (dpy->trans_conn);
	    Xfree ((char *)dpy);
	    return(NULL);
	}
	if (conn_auth_name) Xfree(conn_auth_name);
	if (conn_auth_data) Xfree(conn_auth_data);
/*
 * Now see if connection was accepted...
 */
	/* these internal functions expect the display to be locked */
	LockDisplay(dpy);

	if (prefixread == 0)
	    _XRead (dpy, (char *)&prefix,(long)SIZEOF(xConnSetupPrefix));

	/* an Authenticate reply we weren't expecting? */
	if (prefix.success != xTrue && prefix.success != xFalse) {
	    fprintf (stderr,
      "Xlib: unexpected connection setup reply from server, type %d.\r\n",
		     prefix.success);
	    _XDisconnectDisplay (dpy->trans_conn);
	    Xfree ((char *)dpy);
	    return(NULL);
	}

	if (prefix.majorVersion != X_PROTOCOL) {
	    /* XXX - printing messages marks a bad programming interface */
#ifdef NX_TRANS_SOCKET
            if (_X11TransSocketProxyConnInfo(dpy->trans_conn) == NULL) {
                fprintf (stderr, "Xlib: client uses different protocol version (%d) "
                             "than server (%d)!\r\n", X_PROTOCOL, prefix.majorVersion);
            }
#else
	    fprintf (stderr,
     "Xlib: client uses different protocol version (%d) than server (%d)!\r\n",
		     X_PROTOCOL, prefix.majorVersion);
#endif
	    _XDisconnectDisplay (dpy->trans_conn);
	    Xfree ((char *)dpy);
	    return(NULL);
	}
420
#endif /* !USE_XCB */
421

422 423 424 425 426 427 428 429 430 431
#if USE_XCB
	{
		const struct xcb_setup_t *xcbsetup = xcb_get_setup(dpy->xcb->connection);
		memcpy(&prefix, xcbsetup, sizeof(prefix));
		setuplength = prefix.length << 2;
		setup = (char *) xcbsetup;
		setup += SIZEOF(xConnSetupPrefix);
		u.setup = (xConnSetup *) setup;
	}
#else /* !USE_XCB */
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
	setuplength = prefix.length << 2;
	if ( (u.setup = (xConnSetup *)
	      (setup =  Xmalloc ((unsigned) setuplength))) == NULL) {
		_XDisconnectDisplay (dpy->trans_conn);
		Xfree ((char *)dpy);
		return(NULL);
	}
	_XRead (dpy, (char *)u.setup, setuplength);

/*
 * If the connection was not accepted by the server due to problems,
 * give error message to the user....
 */
	if (prefix.success != xTrue) {
		/* XXX - printing messages marks a bad programming interface */
447
		fprintf (stderr,
448 449 450 451 452 453
		      "Xlib: connection to \"%s\" refused by server\r\nXlib: ",
			 fullname);

		if (prefix.lengthReason > setuplength) {
		    fprintf (stderr, "Xlib: Broken initial reply: length of reason > length of packet\r\n");
		}else{
454 455
		    (void) fwrite (u.failure, (size_t)sizeof(char),
			       (size_t)prefix.lengthReason, stderr);
456 457 458 459 460 461
		    (void) fwrite ("\r\n", sizeof(char), 2, stderr);
		}

		OutOfMemory(dpy, setup);
		return (NULL);
	}
462
#endif /* USE_XCB */
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

/*
 * Check if the reply was long enough to get any information out of it.
 */
	usedbytes = sz_xConnSetup;
	if (setuplength < usedbytes ) {
	    fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
	    OutOfMemory(dpy, setup);
	    return (NULL);
	}

/*
 * We succeeded at authorization, so let us move the data into
 * the display structure.
 */
	dpy->proto_major_version= prefix.majorVersion;
	dpy->proto_minor_version= prefix.minorVersion;
	dpy->release 		= u.setup->release;
	dpy->resource_base	= u.setup->ridBase;
	dpy->resource_mask	= u.setup->ridMask;
	dpy->min_keycode	= u.setup->minKeyCode;
	dpy->max_keycode	= u.setup->maxKeyCode;
	dpy->motion_buffer	= u.setup->motionBufferSize;
	dpy->nformats		= u.setup->numFormats;
	dpy->nscreens		= u.setup->numRoots;
	dpy->byte_order		= u.setup->imageByteOrder;
	dpy->bitmap_unit	= u.setup->bitmapScanlineUnit;
	dpy->bitmap_pad		= u.setup->bitmapScanlinePad;
	dpy->bitmap_bit_order   = u.setup->bitmapBitOrder;
	dpy->max_request_size	= u.setup->maxRequestSize;
	mask = dpy->resource_mask;
	dpy->resource_shift	= 0;
	if (!mask)
	{
	    fprintf (stderr, "Xlib: connection to \"%s\" invalid setup\n",
		     fullname);
	    OutOfMemory(dpy, setup);
	    return (NULL);
	}
502

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
	while (!(mask & 1)) {
	    dpy->resource_shift++;
	    mask = mask >> 1;
	}
	dpy->resource_max = (dpy->resource_mask >> dpy->resource_shift) - 5;
/*
 * now extract the vendor string...  String must be null terminated,
 * padded to multiple of 4 bytes.
 */
	/* Check for a sane vendor string length */
	if (u.setup->nbytesVendor > 256) {
	    OutOfMemory(dpy, setup);
	    return (NULL);
	}

518
	dpy->vendor = Xmalloc(u.setup->nbytesVendor + 1);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
	if (dpy->vendor == NULL) {
	    OutOfMemory(dpy, setup);
	    return (NULL);
	}
	vendorlen = u.setup->nbytesVendor;

/*
 * validate setup length
 */
	usedbytes += (vendorlen + 3) & ~3;
	if (setuplength < usedbytes) {
	    fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
	    OutOfMemory(dpy, setup);
	    return (NULL);
	}

 	u.setup = (xConnSetup *) (((char *) u.setup) + sz_xConnSetup);
  	(void) strncpy(dpy->vendor, u.vendor, vendorlen);
	dpy->vendor[vendorlen] = '\0';
 	vendorlen = (vendorlen + 3) & ~3;	/* round up */
539
	u.vendor += vendorlen;
540 541 542 543

/*
 * Now iterate down setup information.....
 */
544
	dpy->pixmap_format = Xcalloc(dpy->nformats, sizeof(ScreenFormat));
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
	if (dpy->pixmap_format == NULL) {
	        OutOfMemory (dpy, setup);
		return(NULL);
	}
/*
 * First decode the Z axis Screen format information.
 */
	usedbytes += dpy->nformats * sz_xPixmapFormat;

	if (setuplength < usedbytes) {
	    fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
	    OutOfMemory (dpy, setup);
	    return(NULL);
	}

	for (i = 0; i < dpy->nformats; i++) {
	    register ScreenFormat *fmt = &dpy->pixmap_format[i];
	    fmt->depth = u.sf->depth;
	    fmt->bits_per_pixel = u.sf->bitsPerPixel;
	    fmt->scanline_pad = u.sf->scanLinePad;
	    fmt->ext_data = NULL;
	    u.sf = (xPixmapFormat *) (((char *) u.sf) + sz_xPixmapFormat);
	}

/*
 * next the Screen structures.
 */
572
	dpy->screens = Xcalloc(dpy->nscreens, sizeof(Screen));
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	if (dpy->screens == NULL) {
	        OutOfMemory (dpy, setup);
		return(NULL);
	}

/*
 * Now go deal with each screen structure.
 */
	for (i = 0; i < dpy->nscreens; i++) {
	    register Screen *sp = &dpy->screens[i];
	    VisualID root_visualID;

	    usedbytes += sz_xWindowRoot;
	    if (setuplength < usedbytes) {
		fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
		OutOfMemory (dpy, setup);
		return(NULL);
	    }

592
	    root_visualID = u.rp->rootVisualID;
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
	    sp->display	    = dpy;
	    sp->root 	    = u.rp->windowId;
	    sp->cmap 	    = u.rp->defaultColormap;
	    sp->white_pixel = u.rp->whitePixel;
	    sp->black_pixel = u.rp->blackPixel;
	    sp->root_input_mask = u.rp->currentInputMask;
	    sp->width	    = u.rp->pixWidth;
	    sp->height	    = u.rp->pixHeight;
	    sp->mwidth	    = u.rp->mmWidth;
	    sp->mheight	    = u.rp->mmHeight;
	    sp->min_maps    = u.rp->minInstalledMaps;
	    sp->max_maps    = u.rp->maxInstalledMaps;
	    sp->backing_store= u.rp->backingStore;
	    sp->save_unders = u.rp->saveUnders;
	    sp->root_depth  = u.rp->rootDepth;
	    sp->ndepths	    = u.rp->nDepths;
	    sp->ext_data   = NULL;
	    u.rp = (xWindowRoot *) (((char *) u.rp) + sz_xWindowRoot);
/*
 * lets set up the depth structures.
 */
614
	    sp->depths = Xcalloc(sp->ndepths, sizeof(Depth));
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
	    if (sp->depths == NULL) {
		OutOfMemory (dpy, setup);
		return(NULL);
	    }
	    /*
	     * for all depths on this screen.
	     */
	    for (j = 0; j < sp->ndepths; j++) {
		Depth *dp = &sp->depths[j];

		usedbytes += sz_xDepth;
		if (setuplength < usedbytes) {
		    fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
		    OutOfMemory (dpy, setup);
		    return(NULL);
		}
631

632 633 634 635
		dp->depth = u.dp->depth;
		dp->nvisuals = u.dp->nVisuals;
		u.dp = (xDepth *) (((char *) u.dp) + sz_xDepth);
		if (dp->nvisuals > 0) {
636
		    dp->visuals = Xcalloc(dp->nvisuals, sizeof(Visual));
637 638 639 640 641 642 643 644 645 646 647 648 649
		    if (dp->visuals == NULL) {
			OutOfMemory (dpy, setup);
			return(NULL);
		    }
		    for (k = 0; k < dp->nvisuals; k++) {
			register Visual *vp = &dp->visuals[k];

			usedbytes += sz_xVisualType;
			if (setuplength < usedbytes) {
			    fprintf (stderr, "Xlib: Broken initial reply: Too short (%ld)\n", setuplength);
			    OutOfMemory (dpy, setup);
			    return(NULL);
			}
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
			vp->visualid	= u.vp->visualID;
			vp->class	= u.vp->class;
			vp->bits_per_rgb= u.vp->bitsPerRGB;
			vp->map_entries	= u.vp->colormapEntries;
			vp->red_mask	= u.vp->redMask;
			vp->green_mask	= u.vp->greenMask;
			vp->blue_mask	= u.vp->blueMask;
			vp->ext_data	= NULL;
			u.vp = (xVisualType *) (((char *) u.vp) +
						sz_xVisualType);
		    }
		    if (dp->depth == 32 && getenv ("XLIB_SKIP_ARGB_VISUALS"))
		    {
			Xfree (dp->visuals);
			dp->visuals = NULL;
			dp->nvisuals = 0;
		    }
		} else {
		    dp->visuals = (Visual *) NULL;
		}
	    }
	    sp->root_visual = _XVIDtoVisual(dpy, root_visualID);
	}

	if(usedbytes != setuplength){
	    /* Sanity check, shouldn't happen. */
	    fprintf(stderr, "Xlib: Did not parse entire setup message: "
	                    "parsed: %ld, message: %ld\n",
		    usedbytes, setuplength);
	    OutOfMemory(dpy, setup);
	    return(NULL);
	}

/*
 * Now start talking to the server to setup all other information...
 */

688
#if !USE_XCB
689
	Xfree (setup);	/* all finished with setup information */
690
#endif /* !USE_XCB */
691 692 693 694 695 696 697 698 699

/*
 * Make sure default screen is legal.
 */
	if (iscreen >= dpy->nscreens) {
	    OutOfMemory(dpy, (char *) NULL);
	    return(NULL);
	}

700
#if !USE_XCB
701 702 703 704
/*
 * finished calling internal routines, now unlock for external routines
 */
	UnlockDisplay(dpy);
705 706 707
#endif /* !USE_XCB */

#if USE_XCB
708 709 710
/*
 * get availability of large requests
 */
711 712 713 714
	dpy->bigreq_size = xcb_get_maximum_request_length(dpy->xcb->connection);
	if(dpy->bigreq_size <= dpy->max_request_size)
		dpy->bigreq_size = 0;
#endif /* USE_XCB */
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

/*
 * Set up other stuff clients are always going to use.
 */
	for (i = 0; i < dpy->nscreens; i++) {
	    register Screen *sp = &dpy->screens[i];
	    XGCValues values;
	    values.foreground = sp->black_pixel;
	    values.background = sp->white_pixel;
	    if ((sp->default_gc = XCreateGC (dpy, sp->root,
					     GCForeground|GCBackground,
					     &values)) == NULL) {
		OutOfMemory(dpy, (char *) NULL);
		return (NULL);
	    }
	}
/*
 * call into synchronization routine so that all programs can be
 * forced synchronous
 */
	(void) XSynchronize(dpy, _Xdebug);

/*
 * get the resource manager database off the root window.
 */
	LockDisplay(dpy);
	{
742 743 744
	    xGetPropertyReply reply;
	    xGetPropertyReq *req;
#if !USE_XCB
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
	    _XAsyncHandler async;
	    _XBigReqState async_state;
	    xQueryExtensionReq *qreq;
	    xBigReqEnableReq *breq;
	    xBigReqEnableReply brep;

	    GetReq(QueryExtension, qreq);
	    async_state.seq = dpy->request;
	    async_state.opcode = 0;
	    async.next = dpy->async_handlers;
	    async.handler = _XBigReqHandler;
	    async.data = (XPointer)&async_state;
	    dpy->async_handlers = &async;
	    qreq->nbytes = bignamelen;
	    qreq->length += (bignamelen+3)>>2;
	    Data(dpy, XBigReqExtensionName, bignamelen);
761
#endif /* !USE_XCB */
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

	    GetReq (GetProperty, req);
	    req->window = RootWindow(dpy, 0);
	    req->property = XA_RESOURCE_MANAGER;
	    req->type = XA_STRING;
	    req->delete = False;
	    req->longOffset = 0;
	    req->longLength = 100000000L;

	    if (_XReply (dpy, (xReply *) &reply, 0, xFalse)) {
		if (reply.format == 8 && reply.propertyType == XA_STRING &&
		    (reply.nItems + 1 > 0) &&
		    (reply.nItems <= req->longLength * 4) &&
		    (dpy->xdefaults = Xmalloc (reply.nItems + 1))) {
		    _XReadPad (dpy, dpy->xdefaults, reply.nItems);
		    dpy->xdefaults[reply.nItems] = '\0';
		}
		else if (reply.propertyType != None)
780
		    _XEatDataWords(dpy, reply.length);
781
	    }
782
#if !USE_XCB
783 784 785 786 787 788 789 790
	    DeqAsyncHandler(dpy, &async);
	    if (async_state.opcode) {
		GetReq(BigReqEnable, breq);
		breq->reqType = async_state.opcode;
		breq->brReqType = X_BigReqEnable;
		if (_XReply(dpy, (xReply *)&brep, 0, xFalse))
		    dpy->bigreq_size = brep.max_request_size;
	    }
791
#endif /* !USE_XCB */
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
	}
	UnlockDisplay(dpy);

#ifdef MOTIFBC
	{
	    extern Display *_XHeadOfDisplayList;
	    _XHeadOfDisplayList = dpy;
	}
#endif
#ifdef XKB
	XkbUseExtension(dpy,NULL,NULL);
#endif
/*
 * and return successfully
 */
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST) 
        fprintf(stderr, "XOpenDisplay: Returning display at [%p].\n", dpy);
#endif
 	return(dpy);
}

813
#if !USE_XCB
814
static Bool
815 816 817 818 819 820
_XBigReqHandler(
    register Display *dpy,
    register xReply *rep,
    char *buf,
    int len,
    XPointer data)
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
{
    _XBigReqState *state;
    xQueryExtensionReply replbuf;
    xQueryExtensionReply *repl;

    state = (_XBigReqState *)data;
    if (dpy->last_request_read != state->seq)
	return False;
    if (rep->generic.type == X_Error)
	return True;
    repl = (xQueryExtensionReply *)
	_XGetAsyncReply(dpy, (char *)&replbuf, rep, buf, len,
			(SIZEOF(xQueryExtensionReply) - SIZEOF(xReply)) >> 2,
			True);
    if (repl->present)
	state->opcode = repl->major_opcode;
    return True;
}
839
#endif /* !USE_XCB */
840 841


842
/* XFreeDisplayStructure frees all the storage associated with a
843 844 845 846 847 848 849 850
 * Display.  It is used by XOpenDisplay if it runs out of memory,
 * and also by XCloseDisplay.   It needs to check whether all pointers
 * are non-NULL before dereferencing them, since it may be called
 * by XOpenDisplay before the Display structure is fully formed.
 * XOpenDisplay must be sure to initialize all the pointers to NULL
 * before the first possible call on this.
 */

851
void _XFreeDisplayStructure(Display *dpy)
852
{
853 854 855 856 857 858 859 860 861 862 863
	/* move all cookies in the EQ to the jar, then free them. */
	if (dpy->qfree) {
	    _XQEvent *qelt = dpy->qfree;
	    while (qelt) {
		if (_XIsEventCookie(dpy, &qelt->event))
		    _XStoreEventCookie(dpy, &qelt->event);
		qelt = qelt->next;
	    }
        }
	if (dpy->cookiejar)
	    _XFreeEventCookies(dpy);
864 865 866
	while (dpy->ext_procs) {
	    _XExtension *ext = dpy->ext_procs;
	    dpy->ext_procs = ext->next;
867
	    Xfree (ext->name);
868
	    Xfree (ext);
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
	}
	if (dpy->im_filters)
	   (*dpy->free_funcs->im_filters)(dpy);
	if (dpy->cms.clientCmaps)
	   (*dpy->free_funcs->clientCmaps)(dpy);
	if (dpy->cms.defaultCCCs)
	   (*dpy->free_funcs->defaultCCCs)(dpy);
	if (dpy->cms.perVisualIntensityMaps)
	   (*dpy->free_funcs->intensityMaps)(dpy);
	if (dpy->atoms)
	    (*dpy->free_funcs->atoms)(dpy);
	if (dpy->modifiermap)
	   (*dpy->free_funcs->modifiermap)(dpy->modifiermap);
	if (dpy->key_bindings)
	   (*dpy->free_funcs->key_bindings)(dpy);
	if (dpy->context_db)
	   (*dpy->free_funcs->context_db)(dpy);
	if (dpy->xkb_info)
	   (*dpy->free_funcs->xkb)(dpy);

	/* if RM database was allocated by XGetDefault() free it */
	if (dpy->db && (dpy->flags & XlibDisplayDfltRMDB))
	    XrmDestroyDatabase(dpy->db);

	if (dpy->screens) {
	    register int i;

            for (i = 0; i < dpy->nscreens; i++) {
		Screen *sp = &dpy->screens[i];

		if (sp->depths) {
		   register int j;

		   for (j = 0; j < sp->ndepths; j++) {
			Depth *dp = &sp->depths[j];

			if (dp->visuals) {
			   register int k;

			   for (k = 0; k < dp->nvisuals; k++)
			     _XFreeExtData (dp->visuals[k].ext_data);
910
			   Xfree (dp->visuals);
911 912 913
			   }
			}

914
		   Xfree (sp->depths);
915 916 917 918 919
		   }

		_XFreeExtData (sp->ext_data);
		}

920
	    Xfree (dpy->screens);
921
	    }
922

923 924 925 926 927
	if (dpy->pixmap_format) {
	    register int i;

	    for (i = 0; i < dpy->nformats; i++)
	      _XFreeExtData (dpy->pixmap_format[i].ext_data);
928
            Xfree (dpy->pixmap_format);
929 930
	    }

931
	free(dpy->display_name);
932

933 934 935 936 937
	Xfree (dpy->vendor);
	Xfree (dpy->buffer);
	Xfree (dpy->keysyms);
	Xfree (dpy->xdefaults);
	Xfree (dpy->error_vec);
938 939

	_XFreeExtData (dpy->ext_data);
940 941 942

	Xfree (dpy->free_funcs);
	Xfree (dpy->scratch_buffer);
943 944 945 946 947 948 949
	FreeDisplayLock(dpy);

	if (dpy->qfree) {
	    register _XQEvent *qelt = dpy->qfree;

	    while (qelt) {
		register _XQEvent *qnxt = qelt->next;
950
		Xfree (qelt);
951 952 953 954 955 956
		qelt = qnxt;
	    }
	}
	while (dpy->im_fd_info) {
	    struct _XConnectionInfo *conni = dpy->im_fd_info;
	    dpy->im_fd_info = conni->next;
957
	    Xfree (conni->watch_data);
958 959 960 961 962 963 964
	    Xfree (conni);
	}
	if (dpy->conn_watchers) {
	    struct _XConnWatchInfo *watcher = dpy->conn_watchers;
	    dpy->conn_watchers = watcher->next;
	    Xfree (watcher);
	}
965 966

	Xfree (dpy->filedes);
967

968 969 970 971
#if USE_XCB
	_XFreeX11XCBStructure(dpy);
#endif /* USE_XCB */

972
	Xfree (dpy);
973 974 975 976 977
}

/* OutOfMemory is called if malloc fails.  XOpenDisplay returns NULL
   after this returns. */

978
static void OutOfMemory(Display *dpy, char *setup)
979
{
980 981 982 983
#if USE_XCB
    if(dpy->xcb->connection)
	xcb_disconnect(dpy->xcb->connection);
#else /* !USE_XCB */
984
    _XDisconnectDisplay (dpy->trans_conn);
985
#endif /* USE_XCB */
986
    _XFreeDisplayStructure (dpy);
987
#if !USE_XCB
988
    if (setup) Xfree (setup);
989
#endif /* !USE_XCB */
990
}