aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/lib/X11/ConnDis.c
blob: 5d6f85aa7bff0f97bee8efd4cffa38eaa56839f5 (plain)
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
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
215
216
217
218
219
220
221
222
223
224
225
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
/**************************************************************************/
/*                                                                        */
/* 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.                                          */
/*                                                                        */
/**************************************************************************/

/*

Copyright 1989, 1998  The Open Group

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

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

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

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

*/

/*
 * This file contains operating system dependencies.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <nx-X11/Xlibint.h>
#include <nx-X11/Xtrans/Xtrans.h>
#include <nx-X11/Xauth.h>
#ifdef HASXDMAUTH
#include <X11/Xdmcp.h>
#endif
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>

#if !defined(WIN32)
#ifndef Lynx
#include <sys/socket.h>
#else
#include <socket.h>
#endif
#else
#include <nx-X11/Xwindows.h>
#endif

#ifndef X_CONNECTION_RETRIES		/* number retries on ECONNREFUSED */
#define X_CONNECTION_RETRIES 5
#endif

#include "Xintconn.h"

/* prototypes */
static void GetAuthorization(
    XtransConnInfo trans_conn,
    int family,
    char *saddr,
    int saddrlen,
    int idisplay,
    char **auth_namep,
    int *auth_namelenp,
    char **auth_datap,
    int *auth_datalenp);

/* functions */
static char *copystring (const char *src, int len)
{
    char *dst = Xmalloc (len + 1);

    if (dst) {
	strncpy (dst, src, len);
	dst[len] = '\0';
    }

    return dst;
}

#define Xstrdup(s)	copystring(s, strlen(s))

#ifdef TCPCONN
# define TCP_TRANS	"tcp"
#endif
#ifdef UNIXCONN
# define UNIX_TRANS	"unix"
#endif
#if defined(LOCALCONN) || defined(OS2PIPECONN) || defined(UNIXCONN)
# define LOCAL_TRANS	"local"
#endif

/* FIXME:  This should be handled through Makefile/configure logic. See configure.ac in upstream libX11 */

#ifdef UNIXCONN
#  ifdef TCPCONN
#    define LOCAL_TRANSPORT_LIST LOCAL_TRANS,UNIX_TRANS,TCP_TRANS
#  else
#    define LOCAL_TRANSPORT_LIST LOCAL_TRANS,UNIX_TRANS
#  endif
#else
#  ifdef TCPCONN
#    define LOCAL_TRANSPORT_LIST TCP_TRANS
#  else
#    define LOCAL_TRANSPORT_LIST
#  endif
#endif




/*
 * Attempts to connect to server, given display name. Returns file descriptor
 * (network socket) or -1 if connection fails.  Display names may be of the
 * following format:
 *
 *     [protocol/] [hostname] : [:] displaynumber [.screennumber]
 *
 * A string with exactly two colons seperating hostname from the
 * display indicates a (now unsupported) DECnet style name.  Colons in
 * the hostname may occur if an IPv6 numeric address is used as the
 * hostname.  An IPv6 numeric address may also end in a double colon,
 * so three colons in a row indicates an IPv6 address ending in ::
 * followed by :display.  To make it easier for people to read, an
 * IPv6 numeric address hostname may be surrounded by [ ] in a similar
 * fashion to the IPv6 numeric address URL syntax defined by IETF RFC
 * 2732.
 *
 * If no hostname and no protocol is specified, the string is interpreted
 * as the most efficient local connection to a server on the same machine.
 * This is usually:
 *
 *     o  shared memory
 *     o  local stream
 *     o  UNIX domain socket
 *     o  TCP to local host
 *
 * This function will eventually call the X Transport Interface functions
 * which expects the hostname in the format:
 *
 *	[protocol/] [hostname] : [:] displaynumber
 *
 */
XtransConnInfo
_X11TransConnectDisplay (
    char *display_name,
    char **fullnamep,			/* RETURN */
    int *dpynump,			/* RETURN */
    int *screenp,			/* RETURN */
    char **auth_namep,			/* RETURN */
    int *auth_namelenp,			/* RETURN */
    char **auth_datap,			/* RETURN */
    int *auth_datalenp)			/* RETURN */
{
    int family;
    int saddrlen;
    Xtransaddr *saddr;
    char *lastp, *lastc, *p;		/* char pointers */
    char *pprotocol = NULL;		/* start of protocol name */
    char *phostname = NULL;		/* start of host of display */
    char *pdpynum = NULL;		/* start of dpynum of display */
    char *pscrnum = NULL;		/* start of screen of display */
    int idisplay = 0;			/* required display number */
    int iscreen = 0;			/* optional screen number */
    /*  int (*connfunc)(); */		/* method to create connection */
    int len, hostlen;			/* length tmp variable */
    int retry;				/* retry counter */
    char addrbuf[128];			/* final address passed to
					   X Transport Interface */
    char* address = addrbuf;
    XtransConnInfo trans_conn = NULL;	/* transport connection object */
    int connect_stat;
#if defined(LOCALCONN) || defined(UNIXCONN) || defined(TCPCONN)
    Bool reset_hostname = False;	/* Reset hostname? */
    char *original_hostname = NULL;
    int local_transport_index = -1;
    const char *local_transport[] = { LOCAL_TRANSPORT_LIST, NULL };
#endif

    p = display_name;

    saddrlen = 0;			/* set so that we can clear later */
    saddr = NULL;

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Called with display_name [%s].\n", display_name);
#endif

#ifdef NX_TRANS_SOCKET

    /*
     * Check if user selected the "nx"
     * protocol or an "nx" hostname.
     */

    if (!strncasecmp(p, "nx/", 3) || !strcasecmp(p, "nx") ||
            !strncasecmp(p, "nx:", 3) || !strncasecmp(p, "nx,", 3))
    {
        if (*(display_name + 2) == '/')
        {
          p += 3;
        }

        pprotocol = copystring ("nx", 2);

        if (!pprotocol) goto bad;

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_X11TransConnectDisplay: Forced protocol to [%s].\n", pprotocol);
#endif

    }
    else
    {

#endif

    /*
     * Step 0, find the protocol.  This is delimited by the optional
     * slash ('/').
     */
    for (lastp = p; *p && *p != ':' && *p != '/'; p++) ;
    if (!*p) return NULL;		/* must have a colon */

    if (p != lastp && *p != ':') {	/* protocol given? */
	pprotocol = copystring (lastp, p - lastp);
	if (!pprotocol) goto bad;	/* no memory */
	p++;				/* skip the '/' */
    } else
	p = display_name;		/* reset the pointer in
					   case no protocol was given */
#ifdef NX_TRANS_SOCKET

    } /* End of step 0. */

    /*
     * Check if user specified the "nx" protocol or
     * hostname is "nx" or in the form "nx,...".
     */

    if (pprotocol && !strcasecmp(pprotocol, "nx"))
    {

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_X11TransConnectDisplay: Checking hostname [%s].\n", p);
#endif

        /*
         * Options can include a "display=" tuple so
         * need to scan right to left.
         */

        lastp = p;
        lastc = NULL;

        for (; *p; p++)
            if (*p == ':')
                lastc = p;

        /*
         * Don't complain if no screen was provided.
         */

        if (lastc)
        {
            phostname = copystring (lastp, lastc - lastp);

            p = lastc;
        }
        else
        {
            phostname = copystring (lastp, strlen(lastp));
        }

        if (!phostname) goto bad;

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_X11TransConnectDisplay: Forced hostname [%s].\n", phostname);
#endif

    }
    else
    {

#endif

    /*
     * Step 1, find the hostname.  This is delimited by either one colon,
     * or two colons in the case of DECnet (DECnet Phase V allows a single
     * colon in the hostname).  (See note above regarding IPv6 numeric
     * addresses with triple colons or [] brackets.)
     * FIXME: we do not support DECnet anymore, so maybe remove these checks?
     */

    lastp = p;
    lastc = NULL;
    for (; *p; p++)
	if (*p == ':')
	    lastc = p;

    if (!lastc) return NULL;		/* must have a colon */

    if ((lastp != lastc) && (*(lastc - 1) == ':')
#if defined(IPv6) && defined(AF_INET6)
      && ( ((lastc - 1) == lastp) || (*(lastc - 2) != ':'))
#endif
	) {
	/* DECnet display specified */

	goto bad;
    }
    else
	hostlen = lastc - lastp;

    if (hostlen > 0) {		/* hostname given? */
	phostname = copystring (lastp, hostlen);
	if (!phostname) goto bad;	/* no memory */
    }

    p = lastc;

#if defined(LOCALCONN) || defined(UNIXCONN) || defined(TCPCONN)
    /* check if phostname == localnodename AND protocol not specified */
    if (!pprotocol && phostname) {
	char localhostname[256];

	if ((_XGetHostname (localhostname, sizeof localhostname) > 0)
	    && (strcmp(phostname, localhostname) == 0)) {
	    original_hostname = phostname;
	    phostname = NULL;
	    reset_hostname = True;
	}
    }
#endif

#ifdef NX_TRANS_SOCKET

    } /* End of step 1. */

    /*
     * Check if no display was specified. In this case
     * search the "port=n" option in NX host string.
     */

    if (*p)
    {

#endif


    /*
     * Step 2, find the display number.  This field is required and is
     * delimited either by a nul or a period, depending on whether or not
     * a screen number is present.
     */

    for (lastp = ++p; *p && isascii(*p) && isdigit(*p); p++) ;
    if ((p == lastp) ||			/* required field */
	(*p != '\0' && *p != '.') ||	/* invalid non-digit terminator */
	!(pdpynum = copystring (lastp, p - lastp)))  /* no memory */
      goto bad;
    idisplay = atoi (pdpynum);

#ifdef NX_TRANS_SOCKET

    }
    else
    {
        char *host  = NULL;
        char *name  = NULL;
        char *value = NULL;

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_X11TransConnectDisplay: Searching port in port [%s].\n", phostname);
#endif

        if (!strncasecmp(phostname, "nx,", 3))
        {
            host = copystring(phostname + 3, strlen(phostname) - 3);
        }

        if (!host) goto bad;

        idisplay = -1;

        name = strtok(host, "=");

        while (name)
        {
            value = strtok(NULL, ",");

            if (value == NULL || strstr(value, "=") != NULL ||
                    strstr(name, ",") != NULL || strlen(value) >= 128)
            {
                Xfree(host);

                goto bad;
            }
            else if (strcasecmp(name, "port") == 0)
            {
                idisplay = atoi(value);

                pdpynum = copystring(value, strlen(value));

                if (!pdpynum) goto bad;

                break;
            }

            name = strtok(NULL, "=");
        }

        Xfree(host);

        if (idisplay == -1)
        {
            goto bad;
        }

    } /* End of step 2. */

#endif


    /*
     * Step 3, find the screen number.  This field is optional.  It is
     * present only if the display number was followed by a period (which
     * we've already verified is the only non-nul character).
     */

    if (*p) {
	for (lastp = ++p; *p && isascii(*p) && isdigit (*p); p++) ;
	if (p != lastp) {
	    if (*p ||			/* non-digits */
		!(pscrnum = copystring (lastp, p - lastp))) /* no memory */
		goto bad;
	    iscreen = atoi (lastp);
	}
    }

    /*
     * At this point, we know the following information:
     *
     *     pprotocol                protocol string or NULL
     *     phostname                hostname string or NULL
     *     idisplay                 display number
     *     iscreen                  screen number
     *
     * We can now decide which transport to use based on the ConnectionFlags
     * build parameter the hostname string.  If phostname is NULL or equals
     * the string "local", then choose the best transport.  If phostname
     * is "unix", then choose BSD UNIX domain sockets (if configured).
     */

#ifdef NX_TRANS_SOCKET

    /*
     * If user selected the "nx" protocol
     * force "local" transport.
     */

    if (pprotocol && !strcasecmp(pprotocol, "nx"))
    {
        pprotocol = copystring ("local", 5);

        if (!pprotocol) goto bad;

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_X11TransConnectDisplay: Converted protocol to [%s].\n", pprotocol);
#endif

    }

#endif

#if defined(TCPCONN) || defined(UNIXCONN) || defined(LOCALCONN) || defined(MNX_TCPCONN) || defined(OS2PIPECONN)
    if (!pprotocol) {
#if defined(UNIXCONN)
	if (phostname && (strcmp (phostname, "unix") == 0)) {
	    Xfree(pprotocol);
	    pprotocol = copystring ("unix", 4);
	} else
#endif
#ifdef HAVE_LAUNCHD
	if (phostname && phostname[0]=='/') {
		pprotocol = copystring ("local", 5);
	}
#endif
	if (!phostname)
	{
	    if (local_transport[0] != NULL) {
		pprotocol = Xstrdup(local_transport[0]);
		local_transport_index = 0;
	    }
	}

	if (!pprotocol) { /* if still not found one, tcp is our last resort */
	    pprotocol = copystring ("tcp", 3);
	}
    }
#endif


  connect:
    /*
     * This seems kind of backwards, but we need to put the protocol,
     * host, and port back together to pass to _X11TransOpenCOTSClient().
     */

    {
	int olen = 3 + (pprotocol ? strlen(pprotocol) : 0) +
		       (phostname ? strlen(phostname) : 0) +
		       (pdpynum   ? strlen(pdpynum)   : 0);
	if (olen > sizeof addrbuf) address = Xmalloc (olen);
    }
    if (!address) goto bad;

    sprintf(address,"%s/%s:%d",
	pprotocol ? pprotocol : "",
	phostname ? phostname : "",
	idisplay );

    /*
     * Make the connection, also need to get the auth address info for
     * the connection.  Do retries in case server host has hit its
     * backlog (which, unfortunately, isn't distinguishable from there not
     * being a server listening at all, which is why we have to not retry
     * too many times).
     */
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Entering connection loop.\n");
#endif
    for(retry=X_CONNECTION_RETRIES; retry>=0; retry-- )
    {
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Going to call _X11TransOpenCOTSClient(address) with address [%s].\n", address);
#endif
	if ( (trans_conn = _X11TransOpenCOTSClient(address)) == NULL )
	{
	    break;
	}
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Going to call _X11TransConnect(trans_conn,address).\n");
#endif
	if ((connect_stat = _X11TransConnect(trans_conn,address)) < 0 )
	{
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
            fprintf(stderr, "_X11TransConnectDisplay: Going to call _X11TransClose(trans_conn).\n");
#endif
	    _X11TransClose(trans_conn);
	    trans_conn = NULL;

	    if (connect_stat == TRANS_TRY_CONNECT_AGAIN)
		continue;
	    else
		break;
	}

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Going to call _X11TransGetPeerAddr(trans_conn, &family, &saddrlen, &saddr).\n");
#endif
	_X11TransGetPeerAddr(trans_conn, &family, &saddrlen, &saddr);

	/*
	 * The family is given in a socket format (ie AF_INET). This
	 * will convert it to the format used by the authorization and
	 * X protocol (ie FamilyInternet).
	 */

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Going to call _X11TransConvertAddress(&family, &saddrlen, &saddr).\n");
#endif
	if( _X11TransConvertAddress(&family, &saddrlen, &saddr) < 0 )
	{
	    _X11TransClose(trans_conn);
	    trans_conn = NULL;
	    if (saddr)
	    {
		free ((char *) saddr);
		saddr = NULL;
	    }
	    continue;
	}

	break;
    }

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        fprintf(stderr, "_X11TransConnectDisplay: Out of connection loop.\n");
#endif
    if (address != addrbuf) Xfree (address);
    address = addrbuf;

    if( trans_conn == NULL )
      goto bad;

    /*
     * Set close-on-exec so that programs that fork() doesn't get confused.
     */

    _X11TransSetOption(trans_conn,TRANS_CLOSEONEXEC,1);

    /*
     * Build the expanded display name:
     *
     *     [host] : [:] dpy . scr \0
     */
#if defined(LOCALCONN) || defined(TCPCONN) || defined(UNIXCONN)
    /*
     *  If we computed the host name, get rid of it so that
     *  XDisplayString() and XDisplayName() agree.
     */
    if (reset_hostname && (phostname != original_hostname)) {
	Xfree (phostname);
	phostname = original_hostname;
	original_hostname = NULL;
    }
#endif
    len = ((phostname ? strlen(phostname) : 0) + 1 +
	   strlen(pdpynum) + 1 + (pscrnum ? strlen(pscrnum) : 1) + 1);
    *fullnamep = (char *) Xmalloc (len);
    if (!*fullnamep) goto bad;

#ifdef HAVE_LAUNCHD
    if (phostname && strlen(phostname) > 11 && !strncmp(phostname, "/tmp/launch", 11))
	sprintf (*fullnamep, "%s%s%d",
	     (phostname ? phostname : ""),
	     ":",
	     idisplay);
    else
#endif
    sprintf (*fullnamep, "%s%s%d.%d",
	     (phostname ? phostname : ""),
	     ":",
	     idisplay, iscreen);

    *dpynump = idisplay;
    *screenp = iscreen;
    if (pprotocol) Xfree (pprotocol);
    if (phostname) Xfree (phostname);
    if (pdpynum) Xfree (pdpynum);
    if (pscrnum) Xfree (pscrnum);
#if defined(LOCALCONN) || defined(UNIXCONN) || defined(TCPCONN)
    if (original_hostname) Xfree (original_hostname);
#endif

    GetAuthorization(trans_conn, family, (char *) saddr, saddrlen, idisplay,
		     auth_namep, auth_namelenp, auth_datap, auth_datalenp);
    return trans_conn;


    /*
     * error return; make sure everything is cleaned up.
     */
  bad:
    if (trans_conn) (void)_X11TransClose(trans_conn);
    if (saddr) free ((char *) saddr);
    if (pprotocol) Xfree (pprotocol);
    if (phostname) Xfree (phostname);
    if (address && address != addrbuf) { Xfree(address); address = addrbuf; }

#if defined(LOCALCONN) || defined(UNIXCONN) || defined(TCPCONN)
    /* If connecting to the local machine, and we failed, try again with
     * the next transport type available, if there is one.
     */
    if (local_transport_index >= 0) {
	if (local_transport[++local_transport_index] != NULL) {
	    pprotocol = Xstrdup(local_transport[local_transport_index]);
#ifdef TCPCONN
	    if (strcmp(pprotocol, "tcp") == 0) {
		if (original_hostname != NULL) {
		    phostname = original_hostname;
		    original_hostname = NULL;
		} else {
		    phostname = copystring("localhost", 9);
		}
	    } else
#endif /* TCPCONN */
	    {
		if ((phostname != NULL) && (original_hostname == NULL)) {
		    original_hostname = phostname;
		}
		phostname = NULL;
	    }
	    goto connect;
	}
    }

    /* No more to try, we've failed all available local transports */
    if (original_hostname) Xfree(original_hostname);
#endif /* LOCALCONN || UNIXCONN || TCPCONN */

    if (pdpynum) Xfree (pdpynum);
    if (pscrnum) Xfree (pscrnum);
    return NULL;

}

/*
 * This is gross, but we need it for compatiblity.
 * The test suite relies on the following interface.
 *
 */

int _XConnectDisplay (
    char *display_name,
    char **fullnamep,			/* RETURN */
    int *dpynump,			/* RETURN */
    int *screenp,			/* RETURN */
    char **auth_namep,			/* RETURN */
    int *auth_namelenp,			/* RETURN */
    char **auth_datap,			/* RETURN */
    int *auth_datalenp)			/* RETURN */
{
   XtransConnInfo trans_conn;

   trans_conn = _X11TransConnectDisplay (
		      display_name, fullnamep, dpynump, screenp,
		      auth_namep, auth_namelenp, auth_datap, auth_datalenp);

   if (trans_conn)
   {
       int fd = _X11TransGetConnectionNumber (trans_conn);
       _X11TransFreeConnInfo (trans_conn);
       return (fd);
   }
   else
       return (-1);
}


/*****************************************************************************
 *                                                                           *
 *			  Connection Utility Routines                        *
 *                                                                           *
 *****************************************************************************/

/*
 * Disconnect from server.
 */

int _XDisconnectDisplay (XtransConnInfo trans_conn)
{
    _X11TransDisconnect(trans_conn);
    _X11TransClose(trans_conn);
    return 0;
}



Bool
_XSendClientPrefix(
     Display *dpy,
     xConnClientPrefix *client,			/* contains count for auth_* */
     char *auth_proto, char *auth_string,	/* NOT null-terminated */
     xConnSetupPrefix *prefix)			/* prefix information */
{
    int auth_length = client->nbytesAuthProto;
    int auth_strlen = client->nbytesAuthString;
    static char padbuf[3];		/* for padding to 4x bytes */
    int pad;
    struct iovec iovarray[5], *iov = iovarray;
    int niov = 0;
    int len = 0;

#define add_to_iov(b,l) \
  { iov->iov_base = (b); iov->iov_len = (l); iov++, niov++; len += (l); }

    add_to_iov ((caddr_t) client, SIZEOF(xConnClientPrefix));

    /*
     * write authorization protocol name and data
     */
    if (auth_length > 0) {
	add_to_iov (auth_proto, auth_length);
	pad = -auth_length & 3; /* pad auth_length to a multiple of 4 */
	if (pad) add_to_iov (padbuf, pad);
    }
    if (auth_strlen > 0) {
	add_to_iov (auth_string, auth_strlen);
	pad = -auth_strlen & 3; /* pad auth_strlen to a multiple of 4 */
	if (pad) add_to_iov (padbuf, pad);
    }

#undef add_to_iov

    len -= _X11TransWritev (dpy->trans_conn, iovarray, niov);

    /*
     * Set the connection non-blocking since we use select() to block.
     */

    _X11TransSetOption(dpy->trans_conn, TRANS_NONBLOCKING, 1);

    if (len != 0)
	return -1;
#ifdef NX_TRANS_SOCKET
    if (_NXDisplayWriteFunction != NULL) {
        (*_NXDisplayWriteFunction)(dpy, len);
    }
#ifdef NX_TRANS_CHANGE
    if (_NXDisplayCongestionFunction != NULL &&
            _X11TransSocketCongestionChange(dpy->trans_conn, &congestion) == 1) {
        (*_NXDisplayCongestionFunction)(dpy, congestion);
    }
#endif
#endif

#ifdef K5AUTH
    if (auth_length == 14 &&
	!strncmp(auth_proto, "MIT-KERBEROS-5", 14))
    {
	return k5_clientauth(dpy, prefix);
    } else
#endif
    return 0;
}


#ifdef STREAMSCONN
#ifdef SVR4
#include <tiuser.h>
#else
#undef HASXDMAUTH
#endif
#endif

#ifdef SECURE_RPC
#include <rpc/rpc.h>
#ifdef ultrix
#include <time.h>
#include <rpc/auth_des.h>
#endif
#endif

#ifdef HASXDMAUTH
#include <time.h>
#define Time_t time_t
#endif

/*
 * First, a routine for setting authorization data
 */
static int xauth_namelen = 0;
static char *xauth_name = NULL;	 /* NULL means use default mechanism */
static int xauth_datalen = 0;
static char *xauth_data = NULL;	 /* NULL means get default data */

/*
 * This is a list of the authorization names which Xlib currently supports.
 * Xau will choose the file entry which matches the earliest entry in this
 * array, allowing us to prioritize these in terms of the most secure first
 */

static char *default_xauth_names[] = {
#ifdef K5AUTH
    "MIT-KERBEROS-5",
#endif
#ifdef SECURE_RPC
    "SUN-DES-1",
#endif
#ifdef HASXDMAUTH
    "XDM-AUTHORIZATION-1",
#endif
    "MIT-MAGIC-COOKIE-1"
};

static _Xconst int default_xauth_lengths[] = {
#ifdef K5AUTH
    14,     /* strlen ("MIT-KERBEROS-5") */
#endif
#ifdef SECURE_RPC
    9,	    /* strlen ("SUN-DES-1") */
#endif
#ifdef HASXDMAUTH
    19,	    /* strlen ("XDM-AUTHORIZATION-1") */
#endif
    18	    /* strlen ("MIT-MAGIC-COOKIE-1") */
};

#define NUM_DEFAULT_AUTH    (sizeof (default_xauth_names) / sizeof (default_xauth_names[0]))

static char **xauth_names = default_xauth_names;
static _Xconst int  *xauth_lengths = default_xauth_lengths;

static int  xauth_names_length = NUM_DEFAULT_AUTH;

void XSetAuthorization (
    char *name, int namelen,		/* *len are lengths of name and data */
    char *data, int datalen)		/* name/data are NULL or arbitrary array of bytes */
{
    char *tmpname, *tmpdata;

    _XLockMutex(_Xglobal_lock);
    if (xauth_name) Xfree (xauth_name);	 /* free any existing data */
    if (xauth_data) Xfree (xauth_data);

    xauth_name = xauth_data = NULL;	/* mark it no longer valid */
    xauth_namelen = xauth_datalen = 0;
    _XUnlockMutex(_Xglobal_lock);

    if (namelen < 0) namelen = 0;	/* check for bogus inputs */
    if (datalen < 0) datalen = 0;	/* maybe should return? */

    if (namelen > 0)  {			/* try to allocate space */
	tmpname = Xmalloc ((unsigned) namelen);
	if (!tmpname) return;
	memcpy (tmpname, name, namelen);
    } else {
	tmpname = NULL;
    }

    if (datalen > 0)  {
	tmpdata = Xmalloc ((unsigned) datalen);
	if (!tmpdata) {
	    if (tmpname) (void) Xfree (tmpname);
	    return;
	}
	memcpy (tmpdata, data, datalen);
    } else {
	tmpdata = NULL;
    }

    _XLockMutex(_Xglobal_lock);
    xauth_name = tmpname;		/* and store the suckers */
    xauth_namelen = namelen;
    if (tmpname)
    {
	xauth_names = &xauth_name;
	xauth_lengths = &xauth_namelen;
	xauth_names_length = 1;
    }
    else
    {
	xauth_names = default_xauth_names;
	xauth_lengths = default_xauth_lengths;
	xauth_names_length = NUM_DEFAULT_AUTH;
    }
    xauth_data = tmpdata;
    xauth_datalen = datalen;
    _XUnlockMutex(_Xglobal_lock);
    return;
}

#ifdef SECURE_RPC
/*
 * Create a credential that we can send to the X server.
 */
static int
auth_ezencode(
    char           *servername,
    int             window,
    char	   *cred_out,
    int            *len)
{
        AUTH           *a;
        XDR             xdr;

#if defined(SVR4) && defined(sun)
        a = authdes_seccreate(servername, window, NULL, NULL);
#else
        a = (AUTH *)authdes_create(servername, window, NULL, NULL);
#endif
        if (a == (AUTH *)NULL) {
                perror("auth_create");
                return 0;
        }
        xdrmem_create(&xdr, cred_out, *len, XDR_ENCODE);
        if (AUTH_MARSHALL(a, &xdr) == FALSE) {
                perror("auth_marshall");
                AUTH_DESTROY(a);
                return 0;
        }
        *len = xdr_getpos(&xdr);
        AUTH_DESTROY(a);
	return 1;
}
#endif

#ifdef K5AUTH
#include <com_err.h>

extern krb5_flags krb5_kdc_default_options;

/*
 * k5_clientauth
 *
 * Returns non-zero if the setup prefix has been read,
 * so we can tell XOpenDisplay to not bother looking for it by
 * itself.
 */
static int k5_clientauth(dpy, sprefix)
    Display *dpy;
    xConnSetupPrefix *sprefix;
{
    krb5_error_code retval;
    xReq prefix;
    char *buf;
    CARD16 plen, tlen;
    krb5_data kbuf;
    krb5_ccache cc;
    krb5_creds creds;
    krb5_principal cprinc, sprinc;
    krb5_ap_rep_enc_part *repl;

    krb5_init_ets();
    /*
     * stage 0: get encoded principal and tgt from server
     */
    _XRead(dpy, (char *)&prefix, sz_xReq);
    if (prefix.reqType != 2 && prefix.reqType != 3)
	/* not an auth packet... so deal */
	if (prefix.reqType == 0 || prefix.reqType == 1)
	{
	    memcpy((char *)sprefix, (char *)&prefix, sz_xReq);
	    _XRead(dpy, (char *)sprefix + sz_xReq,
		   sz_xConnSetupPrefix - sz_xReq); /* ewww... gross */
	    return 1;
	}
	else
	{
	    fprintf(stderr,
		    "Xlib: Krb5 stage 0: got illegal connection setup success code %d\n",
		    prefix.reqType);
	    return -1;
	}
    if (prefix.data != 0)
    {
	fprintf(stderr, "Xlib: got out of sequence (%d) packet in Krb5 auth\n",
		prefix.data);
	return -1;
    }
    buf = (char *)malloc((prefix.length << 2) - sz_xReq);
    if (buf == NULL)		/* malloc failed.  Run away! */
    {
	fprintf(stderr, "Xlib: malloc bombed in Krb5 auth\n");
	return -1;
    }
    tlen = (prefix.length << 2) - sz_xReq;
    _XRead(dpy, buf, tlen);
    if (prefix.reqType == 2 && tlen < 6)
    {
	fprintf(stderr, "Xlib: Krb5 stage 0 reply from server too short\n");
	free(buf);
	return -1;
    }
    if (prefix.reqType == 2)
    {
	plen = *(CARD16 *)buf;
	kbuf.data = buf + 2;
	kbuf.length = (plen > tlen) ? tlen : plen;
    }
    else
    {
	kbuf.data = buf;
	kbuf.length = tlen;
    }
    if (XauKrb5Decode(kbuf, &sprinc))
    {
	free(buf);
	fprintf(stderr, "Xlib: XauKrb5Decode bombed\n");
	return -1;
    }
    if (prefix.reqType == 3)	/* do some special stuff here */
    {
	char *sname, *hostname = NULL;

	sname = (char *)malloc(krb5_princ_component(sprinc, 0)->length + 1);
	if (sname == NULL)
	{
	    free(buf);
	    krb5_free_principal(sprinc);
	    fprintf(stderr, "Xlib: malloc bombed in Krb5 auth\n");
	    return -1;
	}
	memcpy(sname, krb5_princ_component(sprinc, 0)->data,
	       krb5_princ_component(sprinc, 0)->length);
	sname[krb5_princ_component(sprinc, 0)->length] = '\0';
	krb5_free_principal(sprinc);
	if (dpy->display_name[0] != ':') /* hunt for a hostname */
	{
	    char *t;

	    if ((hostname = (char *)malloc(strlen(dpy->display_name)))
		== NULL)
	    {
		free(buf);
		free(sname);
		fprintf(stderr, "Xlib: malloc bombed in Krb5 auth\n");
		return -1;
	    }
	    strcpy(hostname, dpy->display_name);
	    t = strchr(hostname, ':');
	    if (t == NULL)
	    {
		free(buf);
		free(sname);
		free(hostname);
		fprintf(stderr,
			"Xlib: shouldn't get here! malformed display name.");
		return -1;
	    }
	    if ((t - hostname + 1 < strlen(hostname)) && t[1] == ':')
		t++;
	    *t = '\0';		/* truncate the dpy number out */
	}
	retval = krb5_sname_to_principal(hostname, sname,
					 KRB5_NT_SRV_HST, &sprinc);
	free(sname);
	if (hostname)
	    free(hostname);
	if (retval)
	{
	    free(buf);
	    fprintf(stderr, "Xlib: krb5_sname_to_principal failed: %s\n",
		    error_message(retval));
	    return -1;
	}
    }
    if (retval = krb5_cc_default(&cc))
    {
	free(buf);
	krb5_free_principal(sprinc);
	fprintf(stderr, "Xlib: krb5_cc_default failed: %s\n",
		error_message(retval));
	return -1;
    }
    if (retval = krb5_cc_get_principal(cc, &cprinc))
    {
	free(buf);
	krb5_free_principal(sprinc);
	fprintf(stderr, "Xlib: cannot get Kerberos principal from \"%s\": %s\n",
		krb5_cc_default_name(), error_message(retval));
	return -1;
    }
    bzero((char *)&creds, sizeof(creds));
    creds.server = sprinc;
    creds.client = cprinc;
    if (prefix.reqType == 2)
    {
	creds.second_ticket.length = tlen - plen - 2;
	creds.second_ticket.data = buf + 2 + plen;
	retval = krb5_get_credentials(KRB5_GC_USER_USER |
				      krb5_kdc_default_options,
				      cc, &creds);
    }
    else
	retval = krb5_get_credentials(krb5_kdc_default_options,
				      cc, &creds);
    if (retval)
    {
	free(buf);
	krb5_free_cred_contents(&creds);
	fprintf(stderr, "Xlib: cannot get Kerberos credentials: %s\n",
		error_message(retval));
	return -1;
    }
    /*
     * now format the ap_req to send to the server
     */
    if (prefix.reqType == 2)
	retval = krb5_mk_req_extended(AP_OPTS_USE_SESSION_KEY |
				      AP_OPTS_MUTUAL_REQUIRED, NULL,
				      0, 0, NULL, cc,
				      &creds, NULL, &kbuf);
    else
	retval = krb5_mk_req_extended(AP_OPTS_MUTUAL_REQUIRED, NULL,
				      0, 0, NULL, cc, &creds, NULL,
				      &kbuf);
    free(buf);
    if (retval)			/* Some manner of Kerberos lossage */
    {
	krb5_free_cred_contents(&creds);
	fprintf(stderr, "Xlib: krb5_mk_req_extended failed: %s\n",
		error_message(retval));
	return -1;
    }
    prefix.reqType = 1;
    prefix.data = 0;
    prefix.length = (kbuf.length + sz_xReq + 3) >> 2;
    /*
     * stage 1: send ap_req to server
     */
    _XSend(dpy, (char *)&prefix, sz_xReq);
    _XSend(dpy, (char *)kbuf.data, kbuf.length);
    free(kbuf.data);
    /*
     * stage 2: get ap_rep from server to mutually authenticate
     */
    _XRead(dpy, (char *)&prefix, sz_xReq);
    if (prefix.reqType != 2)
	if (prefix.reqType == 0 || prefix.reqType == 1)
	{
	    memcpy((char *)sprefix, (char *)&prefix, sz_xReq);
	    _XRead(dpy, (char *)sprefix + sz_xReq,
		   sz_xConnSetupPrefix - sz_xReq);
	    return 1;
	}
	else
	{
	    fprintf(stderr,
		    "Xlib: Krb5 stage 2: got illegal connection setup success code %d\n",
		    prefix.reqType);
	    return -1;
	}
    if (prefix.data != 2)
	return -1;
    kbuf.length = (prefix.length << 2) - sz_xReq;
    kbuf.data = (char *)malloc(kbuf.length);
    if (kbuf.data == NULL)
    {
	fprintf(stderr, "Xlib: malloc bombed in Krb5 auth\n");
	return -1;
    }
    _XRead(dpy, (char *)kbuf.data, kbuf.length);
    retval = krb5_rd_rep(&kbuf, &creds.keyblock, &repl);
    if (retval)
    {
	free(kbuf.data);
	fprintf(stderr, "Xlib: krb5_rd_rep failed: %s\n",
		error_message(retval));
	return -1;
    }
    free(kbuf.data);
    /*
     * stage 3: send a short ack to the server and return
     */
    prefix.reqType = 3;
    prefix.data = 0;
    prefix.length = sz_xReq >> 2;
    _XSend(dpy, (char *)&prefix, sz_xReq);
    return 0;
}
#endif /* K5AUTH */

static void
GetAuthorization(
    XtransConnInfo trans_conn,
    int family,
    char *saddr,
    int saddrlen,
    int idisplay,
    char **auth_namep,			/* RETURN */
    int *auth_namelenp,			/* RETURN */
    char **auth_datap,			/* RETURN */
    int *auth_datalenp)			/* RETURN */
{
#ifdef SECURE_RPC
    char rpc_cred[MAX_AUTH_BYTES];
#endif
#ifdef HASXDMAUTH
    unsigned char xdmcp_data[192/8];
#endif
    char *auth_name;
    int auth_namelen;
    unsigned char *auth_data;
    int auth_datalen;
    Xauth *authptr = NULL;

/*
 * Look up the authorization protocol name and data if necessary.
 */
    if (xauth_name && xauth_data) {
	auth_namelen = xauth_namelen;
	auth_name = xauth_name;
	auth_datalen = xauth_datalen;
	auth_data = (unsigned char *) xauth_data;
    } else {
	char dpynumbuf[40];		/* big enough to hold 2^64 and more */
	(void) sprintf (dpynumbuf, "%d", idisplay);

	authptr = XauGetBestAuthByAddr ((unsigned short) family,
				    (unsigned short) saddrlen,
				    saddr,
				    (unsigned short) strlen (dpynumbuf),
				    dpynumbuf,
				    xauth_names_length,
				    xauth_names,
				    xauth_lengths);
	if (authptr) {
	    auth_namelen = authptr->name_length;
	    auth_name = (char *)authptr->name;
	    auth_datalen = authptr->data_length;
	    auth_data = (unsigned char *) authptr->data;
	} else {
	    auth_namelen = 0;
	    auth_name = NULL;
	    auth_datalen = 0;
	    auth_data = NULL;
	}
    }
#ifdef HASXDMAUTH
    /*
     * build XDM-AUTHORIZATION-1 data
     */
    if (auth_namelen == 19 && !strncmp (auth_name, "XDM-AUTHORIZATION-1", 19))
    {
	int i, j;
	Time_t  now;
	int family, addrlen;
	Xtransaddr *addr = NULL;

	for (j = 0; j < 8; j++)
	    xdmcp_data[j] = auth_data[j];

	_X11TransGetMyAddr(trans_conn, &family, &addrlen, &addr);

	switch( family )
	{
#ifdef AF_INET
	case AF_INET:
	  {
	    /*
	     * addr will contain a sockaddr_in with all
	     * of the members already in network byte order.
	     */

	    for(i=4; i<8; i++)	/* do sin_addr */
		xdmcp_data[j++] = ((char *)addr)[i];
	    for(i=2; i<4; i++)	/* do sin_port */
		xdmcp_data[j++] = ((char *)addr)[i];
	    break;
	  }
#endif /* AF_INET */
#if defined(IPv6) && defined(AF_INET6)
	case AF_INET6:
	  /* XXX This should probably never happen */
	  {
	    unsigned char ipv4mappedprefix[] = {
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };

	    /* In the case of v4 mapped addresses send the v4
	       part of the address - addr is already in network byte order */
	    if (memcmp((char*)addr+8, ipv4mappedprefix, 12) == 0) {
		for (i = 20 ; i < 24; i++)
		    xdmcp_data[j++] = ((char *)addr)[i];

		/* Port number */
		for (i=2; i<4; i++)
		    xdmcp_data[j++] = ((char *)addr)[i];
	    } else {
		/* Fake data to keep the data aligned. Otherwise the
		   the server will bail about incorrect timing data */
		for (i = 0; i < 6; i++) {
		    xdmcp_data[j++] = 0;
		}
	    }
	    break;
	  }
#endif /* AF_INET6 */
#ifdef AF_UNIX
	case AF_UNIX:
	  {
	    /*
	     * We don't use the sockaddr_un for this encoding.
	     * Instead, we create a sockaddr_in filled with
	     * a decreasing counter for the address, and the
	     * pid for the port.
	     */

	    static unsigned long    unix_addr = 0xFFFFFFFF;
	    unsigned long	the_addr;
	    unsigned short	the_port;
	    unsigned long	the_utime;
	    struct timeval      tp;

	    X_GETTIMEOFDAY(&tp);
	    _XLockMutex(_Xglobal_lock);
	    the_addr = unix_addr--;
	    _XUnlockMutex(_Xglobal_lock);
	    the_utime = (unsigned long) tp.tv_usec;
	    the_port = getpid ();

	    xdmcp_data[j++] = (the_utime >> 24) & 0xFF;
	    xdmcp_data[j++] = (the_utime >> 16) & 0xFF;
	    xdmcp_data[j++] = ((the_utime >>  8) & 0xF0)
		| ((the_addr >>  8) & 0x0F);
	    xdmcp_data[j++] = (the_addr >>  0) & 0xFF;
	    xdmcp_data[j++] = (the_port >>  8) & 0xFF;
	    xdmcp_data[j++] = (the_port >>  0) & 0xFF;
	    break;
	  }
#endif /* AF_UNIX */
	default:
	    /*
	     * Need to return some kind of errro status here.
	     * maybe a NULL auth??
	     */
	    break;
	} /* switch */

	if (addr)
	    free ((char *) addr);

	time (&now);
	xdmcp_data[j++] = (now >> 24) & 0xFF;
	xdmcp_data[j++] = (now >> 16) & 0xFF;
	xdmcp_data[j++] = (now >>  8) & 0xFF;
	xdmcp_data[j++] = (now >>  0) & 0xFF;
	while (j < 192 / 8)
	    xdmcp_data[j++] = 0;
	_XLockMutex(_Xglobal_lock);
	/* this function might use static data, hence the lock around it */
	XdmcpWrap (xdmcp_data, auth_data + 8,
		      xdmcp_data, j);
	_XUnlockMutex(_Xglobal_lock);
	auth_data = xdmcp_data;
	auth_datalen = j;
    }
#endif /* HASXDMAUTH */
#ifdef SECURE_RPC
    /*
     * The SUN-DES-1 authorization protocol uses the
     * "secure RPC" mechanism in SunOS 4.0+.
     */
    if (auth_namelen == 9 && !strncmp(auth_name, "SUN-DES-1", 9)) {
	char servernetname[MAXNETNAMELEN + 1];

	/*
	 * Copy over the server's netname from the authorization
	 * data field filled in by XauGetAuthByAddr().
	 */
	if (auth_datalen > MAXNETNAMELEN) {
	    auth_datalen = 0;
	    auth_data = NULL;
	} else {
	    memcpy(servernetname, auth_data, auth_datalen);
	    servernetname[auth_datalen] = '\0';

	    auth_datalen = sizeof (rpc_cred);
	    if (auth_ezencode(servernetname, 100, rpc_cred,
			      &auth_datalen))
		auth_data = (unsigned char *) rpc_cred;
	    else {
		auth_datalen = 0;
		auth_data = NULL;
	    }
	}
    }
#endif
    if (saddr) free ((char *) saddr);
    if ((*auth_namelenp = auth_namelen))
    {
	if ((*auth_namep = Xmalloc(auth_namelen)))
	    memcpy(*auth_namep, auth_name, auth_namelen);
	else
	    *auth_namelenp = 0;
    }
    else
	*auth_namep = NULL;
    if ((*auth_datalenp = auth_datalen))
    {
	if ((*auth_datap = Xmalloc(auth_datalen)))
	    memcpy(*auth_datap, auth_data, auth_datalen);
	else
	    *auth_datalenp = 0;
    }
    else
	*auth_datap = NULL;
    if (authptr) XauDisposeAuth (authptr);
}