summaryrefslogtreecommitdiff
path: root/gui/gdmchooser.c
blob: cd5ced77db494a79983a75db11678a7e1cc62273 (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
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
/* GDM - The GNOME Display Manager
 * Copyright (C) 1998, 1999, 2000 Martin K, Petersen <mkp@mkp.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/* gdmchooser discovers hosts running XDMCP on the local network (s),
 * presents a list of them and allows the user to choose one. The
 * selected hostname will be printed on stdout. */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <ctype.h>
#include <fcntl.h>
#include <signal.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif

#include <X11/Xmd.h>
#include <X11/Xdmcp.h>

#include <gdk/gdkx.h>
#include <glib/gi18n.h>
#include <glade/glade.h>

#include "gdm.h"
#include "misc.h"
#include "gdmwm.h"
#include "gdmcomm.h"
#include "gdmcommon.h"
#include "gdmconfig.h"

#include "viciousui.h"

static gboolean RUNNING_UNDER_GDM = FALSE;

enum {
	CHOOSER_LIST_ICON_COLUMN = 0,
	CHOOSER_LIST_LABEL_COLUMN,
	CHOOSER_LIST_HOST_COLUMN
};

typedef struct _GdmChooserHost GdmChooserHost;
struct _GdmChooserHost {
    gchar *name;
    gchar *desc;
#ifdef ENABLE_IPV6
    struct in6_addr ia6;
#endif
    struct in_addr ia;
    gint addrtype;    /* Address stored is IPv4 or IPv6 */
    GdkPixbuf *picture;
    gboolean willing;
};


static const gchar *scanning_message = N_("Please wait: scanning local network...");
static const gchar *empty_network = N_("No serving hosts were found.");
static const gchar *active_network = N_("Choose a ho_st to connect to:");

/* XDM chooser style stuff */
static gchar *xdm_address = NULL;
static gchar *client_address = NULL;
static gint connection_type = 0;

/* Exported for glade */
void gdm_chooser_cancel (/*void*/);
void gdm_chooser_add_host (void);
void gdm_chooser_add_entry_changed (void);
void gdm_chooser_manage (GtkButton *button, gpointer data);
void gdm_chooser_browser_select (GtkWidget *widget,
				 gint selected,
				 GdkEvent *event);
void gdm_chooser_browser_unselect (GtkWidget *widget,
				   gint selected,
				   GdkEvent *event);
void gdm_chooser_xdmcp_discover (void);
void display_chooser_information (void);

#define ADD_TIMEOUT 3000
static guint add_check_handler = 0;

/* if this is received, select that host automatically */
#ifdef ENABLE_IPV6 
static struct in6_addr *added6_addr = NULL;
#endif
static struct in_addr *added_addr = NULL;
static char *added_host = NULL;

static guint scan_time_handler = 0;

#define PING_TIMEOUT 2000
#define PING_TRIES 3
static int ping_tries = PING_TRIES;
static guint ping_try_handler = 0;

/* set in the main function */
static char **stored_argv = NULL;
static int stored_argc = 0;

/* Fixetyfix */
int XdmcpReallocARRAY8 (ARRAY8Ptr array, int length);


typedef struct _XdmAuth {
    ARRAY8  authentication;
    ARRAY8  authorization;
} XdmAuthRec, *XdmAuthPtr;

static XdmAuthRec authlist = { 
    { (CARD16)  0, (CARD8 *) 0 },
    { (CARD16)  0, (CARD8 *) 0 }
};


static gint sockfd;
static XdmcpBuffer bcbuf;
static XdmcpBuffer querybuf;
static GSList *bcaddr;
static GSList *queryaddr;

enum {
	GDM_BACKGROUND_NONE = 0,
	GDM_BACKGROUND_IMAGE = 1,
	GDM_BACKGROUND_COLOR = 2
};

static GladeXML *chooser_app;
static GtkWidget *chooser, *manage, *rescan, *cancel, *add_entry, *add_button;
static GtkWidget *status_label;

static GIOChannel *channel;
static GList *chooser_hosts = NULL;
static GdkPixbuf *defhostimg;
static GtkWidget *browser;
static GtkTreeModel *browser_model;
static GdmChooserHost *curhost;

static gboolean have_ipv6;      /* Socket is IPv4 or IPv6 */

static gboolean
find_host_in_list (GdmChooserHost *host, GtkTreeIter *iter)
{
	if (gtk_tree_model_get_iter_first (browser_model, iter)) {
		do {
			GdmChooserHost *lhost;
			gtk_tree_model_get (browser_model, iter,
					    CHOOSER_LIST_HOST_COLUMN, &lhost,
					    -1);
			if (lhost == host)
				return TRUE;
		} while (gtk_tree_model_iter_next (browser_model, iter));
	}
	return FALSE;
}

static void
gdm_chooser_host_dispose (GdmChooserHost *host)
{
    if (!host)
	return;

    if (host->picture != NULL)
	    g_object_unref (G_OBJECT (host->picture));
    host->picture = NULL;

    g_free (host->name);
    host->name = NULL;
    g_free (host->desc);
    host->desc = NULL;
    g_free (host);
}

static GdmChooserHost * 
gdm_chooser_host_alloc (const char *hostname,
			const char *description,
			char *ia,
			int family,
			gboolean willing)
{
    GdmChooserHost *host;
    GdkPixbuf *img;
    gchar *hostimg;
    gchar *hostimgdir;

    host = g_new0 (GdmChooserHost, 1);
    host->name = g_strdup (hostname);
    host->desc = g_strdup (description);
    host->willing = willing;
#ifdef ENABLE_IPV6
    if (family == AF_INET6)
	    memcpy (&host->ia6, (struct in6_addr *)ia, sizeof (struct in6_addr));
    else
#endif
	    memcpy (&host->ia, (struct in_addr *)ia, sizeof (struct in_addr));

    host->addrtype = family;
    chooser_hosts = g_list_prepend (chooser_hosts, host);
    
    if ( ! willing)
	    return host;

    hostimgdir = gdm_config_get_string (GDM_KEY_HOST_IMAGE_DIR); 
    hostimg    = g_strconcat (hostimgdir, "/", hostname, NULL);
    if (g_access (hostimg, R_OK) != 0) {
	    g_free (hostimg);
	    hostimg = g_strconcat (hostimgdir, "/", hostname, ".png", NULL);
    }

    if (g_access (hostimg, R_OK) == 0 &&
	(img = gdk_pixbuf_new_from_file (hostimg, NULL)) != NULL) {
	gint w, h, maxw, maxh;

	w = gdk_pixbuf_get_width (img);
	h = gdk_pixbuf_get_height (img);
	
	maxw = gdm_config_get_int (GDM_KEY_MAX_ICON_WIDTH);
	maxh = gdm_config_get_int (GDM_KEY_MAX_ICON_HEIGHT);

	if (w > h && w > maxw) {
	    h = h * ((gfloat) maxw / w);
	    w = maxw;
	} else if (h > maxh) {
	    w = w * ((gfloat) maxh / h);
	    h = maxh;
	}


	if (w != gdk_pixbuf_get_width (img) ||
	    h != gdk_pixbuf_get_height (img))
		host->picture = gdk_pixbuf_scale_simple (img, w, h,
							 GDK_INTERP_BILINEAR);
	else
		host->picture = g_object_ref (G_OBJECT (img));
	
	g_object_unref (G_OBJECT (img));
    } else if (defhostimg != NULL) {
	    host->picture = (GdkPixbuf *)g_object_ref (G_OBJECT (defhostimg));
    }

    g_free (hostimg);

    return host;
}

static void
gdm_chooser_browser_add_host (GdmChooserHost *host)
{
    gboolean add_this_host = FALSE;

    if (host->willing) {
	    GtkTreeIter iter = {0};
	    const char *addr;
	    char *label;
	    char *name, *desc;
#ifdef ENABLE_IPV6
	    if (host->addrtype == AF_INET6) {   /* IPv6 address */
		static char buffer6[INET6_ADDRSTRLEN];

		addr = inet_ntop (AF_INET6, host->ia6.s6_addr, buffer6, INET6_ADDRSTRLEN);
	    }
	    else /* IPv4 address */
#endif
	    {
		addr = inet_ntoa (host->ia);
	    }

	    name = g_markup_escape_text (host->name, -1);
	    desc = g_markup_escape_text (host->desc, -1);

	    if (strcmp (addr, host->name) == 0)
		    label = g_strdup_printf ("<b>%s</b>\n%s",
					     name,
					     desc);
	    else
		    label = g_strdup_printf ("<b>%s</b> (%s)\n%s",
					     name,
					     addr,
					     desc);

	    g_free (name);
	    g_free (desc);

	    gtk_list_store_append (GTK_LIST_STORE (browser_model), &iter);
	    gtk_list_store_set (GTK_LIST_STORE (browser_model), &iter,
				CHOOSER_LIST_ICON_COLUMN, host->picture,
				CHOOSER_LIST_LABEL_COLUMN, label,
				CHOOSER_LIST_HOST_COLUMN, host,
				-1);
	    g_free (label);

#ifdef ENABLE_IPV6
	    if (added6_addr != NULL && memcmp (&host->ia6, added6_addr,
                                   sizeof (struct in6_addr)) == 0) {
		added6_addr = NULL;
		add_this_host = TRUE;
	    }
#else
	    if (added_addr != NULL &&
		memcmp (&host->ia, added_addr,
			sizeof (struct in_addr)) == 0) {
		added_addr = NULL;
		add_this_host = TRUE;
	    }
#endif
	    if (add_this_host) {
		    GtkTreeSelection *selection;
		    GtkTreePath *path = gtk_tree_model_get_path (browser_model, &iter);
		    selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (browser));
		    gtk_tree_selection_select_iter (selection, &iter);
		    gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (browser),
						  path, NULL,
						  FALSE, 0.0, 0.0);
		    gtk_tree_path_free (path);
		    gtk_widget_grab_focus (manage);
	    }
	    g_free (added_host);
	    added_host = NULL;
	    if (add_check_handler > 0)
		    g_source_remove (add_check_handler);
	    add_check_handler = 0;
    }

    gtk_widget_set_sensitive (GTK_WIDGET (browser), TRUE);
}

static GdmChooserHost *
gdm_host_known (char *ia, gint family)
{
	GList *li;

	for (li = chooser_hosts; li != NULL; li = li->next) {
		GdmChooserHost *host = li->data;
#ifdef ENABLE_IPV6
		if (family == AF_INET6) {
			if (host->addrtype != AF_INET6)
				continue;
			if ( ! memcmp (&host->ia6, (struct in6_addr *)ia, sizeof (struct in6_addr)))
				return host;
		}
		else
#endif
		if (family == AF_INET) {
			if (host->addrtype != AF_INET)
				continue;
			if ( ! memcmp (&host->ia, (struct in_addr *)ia, sizeof (struct in_addr)))
				return host;
		}
	}
	return NULL;
}

static gboolean
is_loopback_addr (char *ia, gint family)
{
	const char lo[] = {127,0,0,1};

#ifdef ENABLE_IPV6
	if (family == AF_INET6 && IN6_IS_ADDR_LOOPBACK ((struct in6_addr *)ia)) {
	    return TRUE;
	} else
#endif
	if (((family == AF_INET) && (((struct in_addr *) ia)->s_addr == INADDR_LOOPBACK)) || memcmp (&((struct in_addr *)ia)->s_addr, lo, 4) == 0) {
	    return TRUE;
	}
	else {
	    return FALSE;
	}
}

static gboolean
gdm_addr_known (char *ia, gint family)
{
	GSList *li;

	for (li = queryaddr; li != NULL; li = li->next) {
		struct sockaddr *sa = li->data;

#ifdef ENABLE_IPV6
		if (sa->sa_family == AF_INET6) {
			if (family != AF_INET6)
				continue;

			if (!memcmp (&((struct sockaddr_in6 *)sa)->sin6_addr, (struct in6_addr *)ia , sizeof (struct in6_addr)))
				return TRUE;
		}
		else if (sa->sa_family == AF_INET) {
			if (family != AF_INET)
				continue;

			if (!memcmp (&((struct sockaddr_in *)sa)->sin_addr, (struct in_addr *)ia, sizeof (struct in_addr)))
				return TRUE;

		}
#else
		if (memcmp (&((struct sockaddr_in *)sa)->sin_addr, (struct in_addr *)ia, sizeof (struct in_addr)) == 0)
			return TRUE;
#endif
	}
	return FALSE;
}

static gboolean
gdm_chooser_decode_packet (GIOChannel   *source,
			   GIOCondition  condition,
			   gpointer      data)
{
#ifdef ENABLE_IPV6
    char hbuf[NI_MAXHOST];
    struct sockaddr_in6 clnt6_sa;
#endif
    struct sockaddr_in clnt_sa;
    gint sa_len;
    static XdmcpBuffer buf;
    XdmcpHeader header;
    struct hostent *he;
    gchar *hostname = NULL;
    gchar *status = NULL;
    ARRAY8 auth = {0}, host = {0}, stat = {0};
    GdmChooserHost *gh;
    int pipe_buf;
    gboolean host_not_willing = FALSE;

    if ( ! (condition & G_IO_IN)) 
        return TRUE;

#ifdef ENABLE_IPV6
    if (have_ipv6) {
	    sa_len = sizeof (struct sockaddr_in6);
	    if (! XdmcpFill (sockfd, &buf, (XdmcpNetaddr) &clnt6_sa, &sa_len))
		    return TRUE;
    } else
#endif
    {
	    sa_len = sizeof (struct sockaddr_in);
	    if (! XdmcpFill (sockfd, &buf, (XdmcpNetaddr) &clnt_sa, &sa_len))
		    return TRUE;
    }

    if (! XdmcpReadHeader (&buf, &header))
	return TRUE;
    
    if (header.version != XDM_PROTOCOL_VERSION)
	return TRUE;

    if (header.opcode == WILLING) {
	    if (! XdmcpReadARRAY8 (&buf, &auth))
		    goto done;

	    if (! XdmcpReadARRAY8 (&buf, &host))
		    goto done;

	    if (! XdmcpReadARRAY8 (&buf, &stat))
		    goto done;

	    status = g_strndup ((char *) stat.data, MIN (stat.length, 256));
    } else if (header.opcode == UNWILLING) {
	    /* immaterial, will not be shown */
	    status = NULL;
    } else {
	    return TRUE;
    }
#ifdef ENABLE_IPV6
    /*Since, IPv4 addresses will get extracted as V4 mapped IPv6 address*/

    if (have_ipv6 &&
	IN6_IS_ADDR_V4MAPPED (&(clnt6_sa.sin6_addr))) {
        memset (&clnt_sa, 0, sizeof (clnt_sa));
        memcpy (&(clnt_sa.sin_addr), &(clnt6_sa.sin6_addr.s6_addr[12]), 4);
        clnt_sa.sin_family = AF_INET;
        clnt_sa.sin_port = clnt6_sa.sin6_port;
        clnt6_sa.sin6_family = AF_INET;
    }

    if (have_ipv6 &&
	((struct sockaddr *) &clnt6_sa)->sa_family == AF_INET6) {
        if ( ! is_loopback_addr ((gchar *) &clnt6_sa.sin6_addr, AF_INET6)) {
	    clnt6_sa.sin6_scope_id = 0;
	
	    getnameinfo ((struct sockaddr *)&clnt6_sa, sizeof (struct sockaddr_in6), hbuf, sizeof (hbuf), NULL, 0, 0);

	    hostname = hbuf;

	    if (strlen (hostname)+1 > PIPE_BUF)
		goto done;
	    hostname = g_strdup (hostname);

        } else {
	    hostname = g_new0 (char, 1024);
	
	    if (gethostname (hostname, 1023) != 0) {
		g_free (hostname);
		goto done;
	    }
	    added6_addr = NULL;
	    gh = gdm_host_known ((char *)&clnt6_sa.sin6_addr, AF_INET6);
        }
    } else
#endif
    {
        if ( !is_loopback_addr ((char *)&clnt_sa.sin_addr, AF_INET)) {
	    he = gethostbyaddr ((gchar *) &clnt_sa.sin_addr,
				sizeof (struct in_addr),
				AF_INET);

	    hostname = (he && he->h_name) ? he->h_name : inet_ntoa (clnt_sa.sin_addr);
	    if (strlen (hostname)+1 > PIPE_BUF)
                   goto done;

	    hostname = g_strdup (hostname);
        } else {
	    hostname = g_new0 (char, 1024);
	    if (gethostname (hostname, 1023) != 0) {
		    g_free (hostname);
		    goto done;
	    }
        }
    }

#ifdef PIPE_BUF
    pipe_buf = PIPE_BUF;
#else
    /* apparently Hurd doesn't have PIPE_BUF */
    pipe_buf = fpathconf (1 /*stdout*/, _PC_PIPE_BUF);
    /* could return -1 if no limit */
#endif

    /* We can't pipe hostnames larger than this */
    if (pipe_buf > 0 && strlen (hostname)+1 > pipe_buf) {
	    g_free (hostname);
	    goto done;
    }

#ifdef ENABLE_IPV6
    if (have_ipv6 && ((struct sockaddr *) &clnt6_sa)->sa_family == AF_INET6) {
	    gh = gdm_host_known ((char *)&clnt6_sa.sin6_addr, AF_INET6);
	    if (gh == NULL) {
		gh = gdm_chooser_host_alloc (hostname, status, (char *)&clnt6_sa.sin6_addr, AF_INET6, header.opcode == WILLING);
		gdm_chooser_browser_add_host (gh);
	    }
    } else
#endif
    {
	    gh = gdm_host_known ((char *)&clnt_sa.sin_addr, AF_INET);
	    if (gh == NULL) {
		gh = gdm_chooser_host_alloc (hostname, status, (char *)&clnt_sa.sin_addr, AF_INET, header.opcode == WILLING);
		gdm_chooser_browser_add_host (gh);
	    }
    }
    if (gh != NULL) {
      /* server changed it's mind */
	    if (header.opcode == WILLING &&
		! gh->willing) {
		    gh->willing = TRUE;
		    gdm_chooser_browser_add_host (gh);
	    }
	    /* hmmm what about the other change, just ignore
	       for now, it's kind of confusing to just remove
	       servers really */
    }
#ifdef ENABLE_IPV6
    if (have_ipv6 &&
	((struct sockaddr *) &clnt6_sa)->sa_family == AF_INET6 &&
        ! gh->willing &&
	added6_addr != NULL &&
        memcmp (&gh->ia6, added6_addr, sizeof (struct in6_addr)) == 0) {

	    added6_addr = NULL;
	    host_not_willing = TRUE;
    }
    else
#endif
    if (clnt_sa.sin_family == AF_INET &&
	! gh->willing &&
	added_addr != NULL &&
	memcmp (&gh->ia, added_addr, sizeof (struct in_addr)) == 0) {

	    added_addr = NULL;
	    host_not_willing = TRUE;
    }

    if (host_not_willing) {
	    GtkWidget *dialog;
	    gchar *msg;

	    if (add_check_handler > 0)
		    g_source_remove (add_check_handler);
	    add_check_handler = 0;

	    msg = g_strdup_printf (_("The host \"%s\" is not willing "
	                             "to support a login session right now.  "
	                             "Please try again later."),
	                           added_host);

	    dialog = ve_hig_dialog_new
		    (GTK_WINDOW (chooser) /* parent */,
		     GTK_DIALOG_MODAL /* flags */,
		     GTK_MESSAGE_ERROR,
		     GTK_BUTTONS_OK,
		     _("Cannot connect to remote server"),
		     msg);

	    g_free (msg);

	    if (RUNNING_UNDER_GDM)
		    gdm_wm_center_window (GTK_WINDOW (dialog));

	    gdm_wm_no_login_focus_push ();
	    gtk_dialog_run (GTK_DIALOG (dialog));
	    gtk_widget_destroy (dialog);
	    gdm_wm_no_login_focus_pop ();

	    g_free (added_host);
	    added_host = NULL;
    }

    g_free (hostname);
    
 done:
    if (header.opcode == WILLING) {
	    XdmcpDisposeARRAY8 (&auth);
	    XdmcpDisposeARRAY8 (&host);
	    XdmcpDisposeARRAY8 (&stat);
    }
    
    g_free (status);
    
    return TRUE;
}


/* Find broadcast address for all active, non pointopoint interfaces */
static void
gdm_chooser_find_bcaddr (void)
{
	int i = 0, num;
	int sock;
	struct ifconf ifc;
	char *buf;
	struct ifreq *ifr;

	sock = socket (AF_INET, SOCK_DGRAM, 0);
#ifdef SIOCGIFNUM
	if (ioctl (sock, SIOCGIFNUM, &num) < 0) {
		num = 64;
	}
#else
	num = 64;
#endif

	ifc.ifc_len = sizeof (struct ifreq) * num;
	ifc.ifc_buf = buf = g_malloc0 (ifc.ifc_len);
	if (ioctl (sock, SIOCGIFCONF, &ifc) < 0) {
		g_free (buf);
		gdm_common_error ("Could not get local addresses!");
		close (sock);
		return;
	}

	ifr = ifc.ifc_req;
	num = ifc.ifc_len / sizeof (struct ifreq);
	for (i = 0 ; i < num ; i++) {
		if ( ! ve_string_empty (ifr[i].ifr_name)) {
			struct ifreq ifreq;
			struct sockaddr_in *ba = NULL;
			struct sockaddr_in *sin = NULL;

			memset (&ifreq, 0, sizeof (ifreq));

			strncpy (ifreq.ifr_name, ifr[i].ifr_name,
				 sizeof (ifreq.ifr_name));
			/* paranoia */
			ifreq.ifr_name[sizeof (ifreq.ifr_name) - 1] = '\0';

			if (ioctl (sock, SIOCGIFFLAGS, &ifreq) < 0) 
				gdm_common_error ("Could not get SIOCGIFFLAGS for %s", ifr[i].ifr_name);

			if ((ifreq.ifr_flags & IFF_UP) == 0 ||
			    (ifreq.ifr_flags & IFF_BROADCAST) == 0 ||
			    ioctl (sock, SIOCGIFBRDADDR, &ifreq) < 0)
				continue;

			ba = (struct sockaddr_in *) &ifreq.ifr_broadaddr;

			sin = g_new0 (struct sockaddr_in, 1);

			sin->sin_family = AF_INET;
			memcpy (&sin->sin_addr, &ba->sin_addr, sizeof (ba->sin_addr));
			bcaddr =  g_slist_append (bcaddr, sin);
		}
	}

	g_free (buf);
}

/* Append multicast address into the list */
#ifdef ENABLE_IPV6
static void
gdm_chooser_find_mcaddr (void)
{
	struct sockaddr_in6 *sin6;
	int sock;       /* Temporary socket for getting information about available interfaces */
	u_char loop = 0; /* Disable multicast for loopback interface */
	int i, num;
	char *buf;
	/* For interfaces' list */
	struct ifconf ifc;
	struct ifreq *ifr = NULL;

	sock = socket (AF_INET, SOCK_DGRAM, 0);
#ifdef SIOCGIFNUM
	if (ioctl (sock, SIOCGIFNUM, &num) < 0) {
		num = 64;
	}
#else
	num = 64;
#endif
	ifc.ifc_len = sizeof (struct ifreq) * num;
	ifc.ifc_buf = buf = malloc (ifc.ifc_len);

	if (setsockopt (sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof (loop)) < 0)
		gdm_common_error ("setsockopt: Could not disable loopback interface for multicasting\n");

	if (ioctl (sock, SIOCGIFCONF, &ifc) >= 0)
		ifr = ifc.ifc_req;
		num = ifc.ifc_len / sizeof (struct ifreq); /* No of interfaces */
		for (i = 0 ; i < num ; i++) {
			struct ifreq ifreq;
			int ifindex;
                                                            
			memset (&ifreq, 0, sizeof (ifreq));
			strncpy (ifreq.ifr_name, ifr[i].ifr_name, sizeof (ifreq.ifr_name));
			ifreq.ifr_name[sizeof (ifreq.ifr_name) - 1] = '\0';

			if (ioctl (sock, SIOCGIFFLAGS, &ifreq) < 0)
				gdm_common_error ("Could not get interface flags for %s\n", ifr[i].ifr_name); 
			ifindex = if_nametoindex (ifr[i].ifr_name);
                                                            
			if ((!(ifreq.ifr_flags & IFF_UP) || (!(ifreq.ifr_flags & IFF_MULTICAST))) || (ifindex == 0 )) {
			/* Not a valid interface or Not up */
				continue;
			}

			sin6 = g_new0 (struct sockaddr_in6, 1);
			sin6->sin6_family = AF_INET6;
			sin6->sin6_port = htons (XDM_UDP_PORT);
			sin6->sin6_scope_id = ifindex;
			inet_pton (AF_INET6, gdm_config_get_string (GDM_KEY_MULTICAST_ADDR),
				&sin6->sin6_addr);

			/* bcaddr is also serving for multicast address for IPv6 */
			bcaddr = g_slist_append (bcaddr, sin6);
		}
}
#endif

static gboolean
chooser_scan_time_update (gpointer data)
{
	GList *li;
	scan_time_handler = 0;
	for (li = chooser_hosts; li != NULL; li = li->next) {
		GdmChooserHost *host = (GdmChooserHost *) li->data;
		if (host->willing)
			break;
	}
	if (li != NULL /* something was found */) {
		gtk_label_set_label (GTK_LABEL (status_label), _(active_network));
	} else {
		gtk_label_set_label (GTK_LABEL (status_label), _(empty_network));
	}
	gtk_widget_set_sensitive (GTK_WIDGET (rescan), TRUE);
	return FALSE;
}

static void
do_ping (gboolean full)
{
    struct sockaddr_in sock;
    GSList *bl = bcaddr;
    GSList *ql = queryaddr;
    struct sockaddr *ia;
#ifdef ENABLE_IPV6
    struct sockaddr_in6 sock6;

    memset (&sock6, 0, sizeof (sock6));
    sock6.sin6_family = AF_INET6;
    sock6.sin6_port = htons (XDM_UDP_PORT);
#endif

    sock.sin_family = AF_INET;
    sock.sin_port = htons (XDM_UDP_PORT);

    while (bl) {
	    ia = (struct sockaddr *) bl->data;
#ifdef ENABLE_IPV6
            if (have_ipv6) {    /* Convert the IPv4 broadcast address to v4 mapped v6 address.*/
		if (ia->sa_family == AF_INET) {
		    char tmpaddr[30];
		    struct in6_addr in6;

		    sprintf (tmpaddr, "::ffff:%s", inet_ntoa (((struct sockaddr_in *)(ia))->sin_addr));
		    inet_pton (AF_INET6, tmpaddr, &in6);
		    memcpy (sock6.sin6_addr.s6_addr, in6.s6_addr, sizeof (struct in6_addr));
		    XdmcpFlush (sockfd, &bcbuf, (XdmcpNetaddr) &sock6, (int) sizeof (struct sockaddr_in6));
		}

		else if (ia->sa_family == AF_INET6) {
		    memcpy (sock6.sin6_addr.s6_addr, ((struct sockaddr_in6 *)ia)->sin6_addr.s6_addr, sizeof (struct in6_addr));
		    XdmcpFlush (sockfd, &bcbuf, (XdmcpNetaddr) &sock6, (int) sizeof (struct sockaddr_in6));
		}
	    }
	    else
#endif
	    {
		if (ia->sa_family == AF_INET) {
		    sock.sin_addr.s_addr = ((struct sockaddr_in *)ia)->sin_addr.s_addr;
		    XdmcpFlush (sockfd, &bcbuf, (XdmcpNetaddr) &sock, (int)sizeof (struct sockaddr_in));
		}
	    }
	    bl = bl->next;
    }

    while (ql != NULL) {
	    ia = (struct sockaddr *) ql->data;

#ifdef ENABLE_IPV6
	    if (have_ipv6) {
		if (ia->sa_family == AF_INET) {
		    char tmpaddr[30];
		    struct in6_addr in6;

		    sprintf (tmpaddr, "::ffff:%s", inet_ntoa (((struct sockaddr_in *)(ia))->sin_addr));
		    inet_pton (AF_INET6, tmpaddr, &in6);

		    if (full || ! gdm_host_known ((char *)&((struct sockaddr_in6 *)ia)->sin6_addr, AF_INET6)) {
			memcpy (sock6.sin6_addr.s6_addr, in6.s6_addr, sizeof (struct in6_addr));
			XdmcpFlush (sockfd, &bcbuf, (XdmcpNetaddr) &sock6, (int) sizeof (struct sockaddr_in6));
		    }
		}

		if (ia->sa_family == AF_INET6) {
		    if (full || ! gdm_host_known ((char *)&((struct sockaddr_in6 *)ia)->sin6_addr, AF_INET6)) {
			memcpy (&sock6.sin6_addr, &((struct sockaddr_in6 *)ia)->sin6_addr, sizeof (struct in6_addr));
			XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock6, (int) sizeof (struct sockaddr_in6));
		    }
		}
	    }
	    else
#endif
	    {
		if (full || ! gdm_host_known ((char *)&((struct sockaddr_in *)ia)->sin_addr, AF_INET)) {
		    sock.sin_addr.s_addr = ((struct sockaddr_in *)ia)->sin_addr.s_addr;
		    XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock, (int)sizeof (struct sockaddr_in));
		}
	    }
	    ql = ql->next;
    }
}

static gboolean
ping_try (gpointer data)
{
	do_ping (FALSE);

	ping_tries --;
	if (ping_tries <= 0)
		return FALSE;
	else
		return TRUE;
}

void
gdm_chooser_xdmcp_discover (void)
{
    GList *hl = chooser_hosts;

    g_free (added_host);
    added_host = NULL;
#ifdef ENABLE_IPV6
    added6_addr = NULL;
#endif
    added_addr = NULL;
    if (add_check_handler > 0)
	    g_source_remove (add_check_handler);
    add_check_handler = 0;

    gtk_widget_set_sensitive (GTK_WIDGET (manage), FALSE);
    gtk_widget_set_sensitive (GTK_WIDGET (rescan), FALSE);
    gtk_list_store_clear (GTK_LIST_STORE (browser_model));
    gtk_widget_set_sensitive (GTK_WIDGET (browser), FALSE);
    gtk_label_set_label (GTK_LABEL (status_label),
			 _(scanning_message));

    while (hl) {
	gdm_chooser_host_dispose ((GdmChooserHost *) hl->data);
	hl = hl->next;
    }

    g_list_free (chooser_hosts);
    chooser_hosts = NULL;

    do_ping (TRUE);

    if (scan_time_handler > 0)
	    g_source_remove (scan_time_handler);
    scan_time_handler = g_timeout_add (gdm_config_get_int (GDM_KEY_SCAN_TIME) * 1000, 
				       chooser_scan_time_update, NULL);

    /* Note we already used up one try */
    ping_tries = PING_TRIES - 1;
    if (ping_try_handler > 0)
	    g_source_remove (ping_try_handler);
    ping_try_handler = g_timeout_add (PING_TIMEOUT, ping_try, NULL);
}

#ifndef ishexdigit
#define ishexdigit(c) (isdigit(c) || ('a' <= (c) && (c) <= 'f'))
#endif
#define HexChar(c)  ('0' <= (c) && (c) <= '9' ? (c) - '0' : (c) - 'a' + 10)

static int
from_hex (const char *s, char *d, int len)
{
  int t;
  while (len >= 2)
    {
      if (!ishexdigit(*s))
 return 1;
      t = HexChar(*s) << 4;
      s++;
      if (!ishexdigit(*s))
 return 1;
      t += HexChar(*s);
      s++;
      *d++ = t;
      len -= 2;
    }
  return len;
}

static void
gdm_chooser_add_hosts (char **hosts)
{
	struct hostent *hostent;
#ifdef ENABLE_IPV6
	struct sockaddr_in6 *qa6 = NULL;
	struct addrinfo hints, *result, *res;
#endif
	struct sockaddr_in* qa = NULL;
	int used_addr = 0;
	int i;

	for (i = 0; hosts != NULL && hosts[i] != NULL; i++) {
		const char *name = hosts[i];

		if (strcmp (name, "BROADCAST") == 0) {
			gdm_chooser_find_bcaddr ();
			continue;
		}
#ifdef ENABLE_IPV6
		if (strcmp (name, "MULTICAST") == 0) {
			gdm_chooser_find_mcaddr ();
			continue;
		}
#endif
		if (used_addr == AF_INET || !qa) {
			qa = g_new0 (struct sockaddr_in, 1);
			memset (qa, 0, sizeof (*qa));
			qa->sin_family = AF_INET;
		}
#ifdef ENABLE_IPV6
		if (used_addr == AF_INET6 || !qa6) {
			 qa6 = g_new0 (struct sockaddr_in6, 1);
			 memset (qa6, 0, sizeof (qa6));
			 qa6->sin6_family = AF_INET6;
		}

		result = NULL;
		memset (&hints, 0, sizeof (hints));
		hints.ai_socktype = SOCK_STREAM;

		if ((strlen (name) == 32) && from_hex (name, (char *) &qa6->sin6_addr, strlen (name)) == 0) {
			queryaddr = g_slist_append (queryaddr, qa6);
			g_free (qa);
			qa = NULL;
			used_addr = AF_INET6;
		}
		else
#endif
		if ((strlen (name) == 8) && (from_hex (name, (char *) &qa->sin_addr, strlen (name)) == 0)) {
			queryaddr = g_slist_append (queryaddr, qa);
#ifdef ENABLE_IPV6
			g_free (qa6);
			qa6 = NULL;
#endif
			used_addr = AF_INET;
		}
		else
#ifdef ENABLE_IPV6
		if (inet_pton (AF_INET6, name, &qa6->sin6_addr) > 0) {
			queryaddr = g_slist_append (queryaddr, qa6);
			g_free (qa);
			qa = NULL;
			used_addr = AF_INET6;
		}
		else
#endif
		if ((qa->sin_addr.s_addr = inet_addr (name)) != -1) {
			queryaddr = g_slist_append (queryaddr, qa);
#ifdef ENABLE_IPV6
			g_free (qa6);
			qa6 = NULL;
#endif
			used_addr = AF_INET;
		}
		else
#ifdef ENABLE_IPV6
		if (getaddrinfo (name, NULL, &hints, &result) == 0) {
			for (res = result; res; res = res->ai_next) {
				if (res && res->ai_family == AF_INET6) {
					memmove (qa6, res->ai_addr, res->ai_addrlen);
					queryaddr = g_slist_append (queryaddr, qa6);
					g_free (qa);
					qa = NULL;
					used_addr = AF_INET6;
                           }
				if (res && res->ai_family == AF_INET) {
					memmove (qa, res->ai_addr, res->ai_addrlen);
					queryaddr = g_slist_append (queryaddr, qa);
					g_free (qa6);
					qa6 = NULL;
					used_addr = AF_INET;
				}
			}
		} else
#endif
		if ((hostent = gethostbyname (name)) != NULL
			 && hostent->h_addrtype == AF_INET
			 && hostent->h_length == 4) {
			qa->sin_family = AF_INET;
			memmove (&qa->sin_addr, hostent->h_addr, 4);
			queryaddr = g_slist_append (queryaddr, qa);
#ifdef ENABLE_IPV6
			g_free (qa6);
			qa6 = NULL;
#endif
			used_addr = AF_INET;
		} else {
			continue; /* not a valid address */
		}
	}

	if (bcaddr == NULL &&
	    queryaddr == NULL)
		gdm_chooser_find_bcaddr ();
}

static void
gdm_chooser_xdmcp_init (char **hosts)
{
    static XdmcpHeader header;
    gint sockopts = 1;

    /* Open socket for communication */
#ifdef ENABLE_IPV6
    if ((sockfd = socket (AF_INET6, SOCK_DGRAM, 0)) == -1)
	have_ipv6 = FALSE;
    else
	have_ipv6 = TRUE;
#endif
    if ( ! have_ipv6) {
	if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) == -1) {
	    gdm_common_fail_exit ("Could not create socket!");
	}
    }

    if (setsockopt (sockfd, SOL_SOCKET, SO_BROADCAST,
        (char *) &sockopts, sizeof (sockopts)) < 0) {
	gdm_common_fail_exit ("Could not set socket options!");
    }

    /* Assemble XDMCP BROADCAST_QUERY packet in static buffer */
    header.opcode  = (CARD16) BROADCAST_QUERY;
    header.length  = 1;
    header.version = XDM_PROTOCOL_VERSION;
    XdmcpWriteHeader (&bcbuf, &header);
    XdmcpWriteARRAY8 (&bcbuf, &authlist.authentication);

    /* Assemble XDMCP QUERY packet in static buffer */
    header.opcode  = (CARD16) QUERY;
    header.length  = 1;
    header.version = XDM_PROTOCOL_VERSION;
    XdmcpWriteHeader (&querybuf, &header);
    XdmcpWriteARRAY8 (&querybuf, &authlist.authentication);

    gdm_chooser_add_hosts (hosts);

    channel = g_io_channel_unix_new (sockfd);
    g_io_channel_set_encoding (channel, NULL, NULL);
    g_io_channel_set_buffered (channel, FALSE);
    g_io_add_watch_full (channel, G_PRIORITY_DEFAULT,
			G_IO_IN|G_IO_PRI|G_IO_ERR|G_IO_HUP|G_IO_NVAL,
			gdm_chooser_decode_packet,
			GINT_TO_POINTER (sockfd), NULL);
    g_io_channel_unref (channel);

    gdm_chooser_xdmcp_discover ();
}

static void
gdm_chooser_choose_host (const char *hostname)
{
  ARRAY8 tmparr;
#ifndef ENABLE_IPV6
  struct hostent *hentry;
#endif

  printf ("\n%s\n", curhost->name);
  fflush (stdout);
  if (xdm_address != NULL) {
#ifdef ENABLE_IPV6
      int status;
      struct sockaddr_in6 in6_addr;
      struct addrinfo hints, *result;
#endif
      struct sockaddr_in in_addr;
      char xdm_addr[32];
      char client_addr[32];
      int fd;
      char buf[1024];
      XdmcpBuffer buffer;
      long family, port, addr;

      if (strlen (xdm_address) > 64 ||
	  from_hex (xdm_address, xdm_addr, strlen (xdm_address)) != 0) {
	      gdm_common_fail_exit ("gdm_chooser_chooser_host: Invalid xdm address.");
      }

      family = (xdm_addr[0] << 8) | xdm_addr[1];
      port = (xdm_addr[2] << 8) | xdm_addr[3];

#ifdef ENABLE_IPV6
      if (family == AF_INET6) {
	  memset (&in6_addr, 0, sizeof (in6_addr));

	  in6_addr.sin6_port   = htons (port);
	  in6_addr.sin6_family = AF_INET6;

	  memcpy (&in6_addr.sin6_addr, &xdm_address[4], 16);

	  if ((fd = socket (PF_INET6, SOCK_STREAM, 0)) == -1) {
	      gdm_common_fail_exit ("gdm_chooser_choose_host: Could not create response socket.");
	  }

	  if (connect (fd, (struct sockaddr *) &in6_addr,
              sizeof (in6_addr)) == -1) {

	      gdm_common_fail_exit ("gdm_chooser_chooser_host: Could not connect to xdm.");
	  }
      } else
#endif
      {
	  addr = (xdm_addr[4] << 24) | (xdm_addr[5] << 16) |
                 (xdm_addr[6] << 8)  | xdm_addr[7];

	  in_addr.sin_family      = AF_INET;
	  in_addr.sin_port        = htons (port);
	  in_addr.sin_addr.s_addr = htonl (addr);

	  if ((fd = socket (PF_INET, SOCK_STREAM, 0)) == -1) {
	      gdm_common_fail_exit ("gdm_chooser_chooser_host: Could not create response socket.");
	  }

	  if (connect (fd, (struct sockaddr *) &in_addr,
              sizeof (in_addr)) == -1) {

	      gdm_common_fail_exit ("gdm_chooser_chooser_host: Could not connect to xdm.");
	  }
      }

      buffer.data = (BYTE *) buf;
      buffer.size = sizeof (buf);
      buffer.pointer = 0;
      buffer.count = 0;

      if (strlen (client_address) > 64 || from_hex (client_address,
          client_addr, strlen (client_address)) != 0) {

	   gdm_common_fail_exit ("gdm_chooser_chooser_host: Invalid client address.");
      }

      tmparr.data   = (BYTE *) client_addr;
      tmparr.length = strlen (client_address) / 2;

      XdmcpWriteARRAY8 (&buffer, &tmparr);
      XdmcpWriteCARD16 (&buffer, (CARD16) connection_type);

#ifdef ENABLE_IPV6
      result = NULL;
      memset (&hints, 0, sizeof (hints));
      hints.ai_socktype = SOCK_STREAM;

      status = getaddrinfo (hostname, NULL, &hints, &result);

      if (status != 0) {
	   gdm_common_fail_exit ("gdm_chooser_chooser_host: Could not get host entry for %s",
	       hostname);
      }

      if (result->ai_family == AF_INET6)
	  tmparr.length = 16;
      if (result->ai_family == AF_INET)
	  tmparr.length = 4;
      tmparr.data = (BYTE *) result->ai_addr;
#else
      hentry = gethostbyname (hostname);

      if (!hentry) {
	  gdm_common_fail_exit ("gdm_chooser_chooser_host: Could not get host entry for %s",
	     hostname);
      }

      tmparr.data   = (BYTE *) hentry->h_addr_list[0]; /* XXX */
      tmparr.length = 4;

#endif
      XdmcpWriteARRAY8 (&buffer, &tmparr);
      write (fd, (char *) buffer.data, buffer.pointer);
      close (fd);
  }
}

static gboolean
add_check (gpointer data)
{
	gboolean check = FALSE;

#ifdef ENABLE_IPV6
	if (have_ipv6 && added6_addr != NULL)
		check = TRUE;
	else
#endif
	if ((! have_ipv6) && added_addr != NULL)
		check = TRUE;

	if (check) {
		GtkWidget *dialog;
		gchar *msg;
		
		msg = g_strdup_printf (_("Did not receive any response from host \"%s\" "
		                         "in %d seconds.  Perhaps the host is not "
		                         "turned on, or is not willing to support a "
		                         "login session right now.  Please try again "
		                         "later."),
		                       added_host,
		                       ADD_TIMEOUT / 1000);

		dialog = ve_hig_dialog_new
			(GTK_WINDOW (chooser) /* parent */,
			 GTK_DIALOG_MODAL /* flags */,
			 GTK_MESSAGE_ERROR,
			 GTK_BUTTONS_OK,
			 _("Did not receive response from server"),
			 msg);

		g_free (msg);

		if (RUNNING_UNDER_GDM)
			gdm_wm_center_window (GTK_WINDOW (dialog));

		gdm_wm_no_login_focus_push ();
		gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
		gdm_wm_no_login_focus_pop ();
	}
	add_check_handler = 0;
	return FALSE;
}

void
gdm_chooser_add_host (void)
{
	struct hostent *hostent;
	struct sockaddr_in *qa;
	GdmChooserHost *host = NULL;
	struct sockaddr_in sock;
	gboolean status  = FALSE;
	const char *name;
#ifdef ENABLE_IPV6
	struct sockaddr_in6 *qa6;
	struct sockaddr_in6 sock6;
	struct addrinfo hints, *result;

	result = NULL;
	memset (&hints, 0, sizeof (hints));
	hints.ai_socktype = SOCK_DGRAM;
#endif

	name = gtk_entry_get_text (GTK_ENTRY (add_entry));
	if (ve_string_empty (name))
		return;

	qa = g_new0 (struct sockaddr_in, 1);
	qa->sin_family = AF_INET;
#ifdef ENABLE_IPV6
	qa6 = g_new0 (struct sockaddr_in6, 1);
	qa6->sin6_family = AF_INET6;

	if (have_ipv6 && strlen (name) == 32 && 
	    from_hex (name, (char *) &qa6->sin6_addr, strlen (name)) == 0) ;

	else
#endif
	if (strlen (name) == 8 &&
	    from_hex (name, (char *) &qa->sin_addr, strlen (name)) == 0) {
#ifdef ENABLE_IPV6
		if (have_ipv6) {
			char tmpaddr[30];

			sprintf (tmpaddr, "::ffff:%s", inet_ntoa (qa->sin_addr));
			inet_pton (AF_INET6, tmpaddr, &qa6->sin6_addr);
		}
#endif
	}
	else
#ifdef ENABLE_IPV6
	if (have_ipv6 && inet_pton (AF_INET6, name, &qa6->sin6_addr) > 0) ;
	else
#endif
	if (inet_aton (name, &(qa->sin_addr))) {
#ifdef ENABLE_IPV6
		if (have_ipv6) {
			char tmpaddr[30];

			sprintf (tmpaddr, "::ffff:%s", inet_ntoa (qa->sin_addr));
			inet_pton (AF_INET6, tmpaddr, &qa6->sin6_addr);
		}
#endif
	}
	else
#ifdef ENABLE_IPV6
	if (getaddrinfo (name, NULL, &hints, &result) == 0) {
		if (result->ai_family == AF_INET6) {
			memcpy (qa6, (struct sockaddr_in6 *)result->ai_addr, result->ai_addrlen);
		}
		else if (result->ai_family == AF_INET) {
			if (have_ipv6) {
				char tmpaddr [30];

				sprintf (tmpaddr, "::ffff:%s",
				  inet_ntoa (((struct sockaddr_in *)result->ai_addr)->sin_addr));
				inet_pton (AF_INET6, tmpaddr, &qa6->sin6_addr);
			}
		}
	}
	else
#endif
	if ((hostent = gethostbyname (name)) != NULL &&
	     hostent->h_addrtype == AF_INET && hostent->h_length == 4) {
		memmove (&qa->sin_addr, hostent->h_addr, 4);
	} else {
		GtkWidget *dialog;
		gchar *msg;

		msg = g_strdup_printf (_("Cannot find the host \"%s\". "
		                         "Perhaps you have mistyped it."),
		                       name);

		dialog = ve_hig_dialog_new
		(GTK_WINDOW (chooser) /* parent */,
		 GTK_DIALOG_MODAL /* flags */,
		 GTK_MESSAGE_ERROR,
		 GTK_BUTTONS_OK,
		 _("Cannot find host"),
		 msg);
		 
		g_free (msg);

		if (RUNNING_UNDER_GDM)
			gdm_wm_center_window (GTK_WINDOW (dialog));

		gdm_wm_no_login_focus_push ();
		gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
		gdm_wm_no_login_focus_pop ();
		g_free (qa);
#ifdef ENABLE_IPV6
		g_free (qa6);
#endif
		return; /* not a valid address */
	}

#ifdef ENABLE_IPV6
	if (have_ipv6) {
		memset (&sock6, 0, sizeof (struct sockaddr_in6));
		sock6.sin6_family = AF_INET6;
		sock6.sin6_port = htons (XDM_UDP_PORT);
		status = gdm_addr_known ((char *)&qa6->sin6_addr, AF_INET6);
		if ( ! status) {
			queryaddr = g_slist_append (queryaddr, qa6);
		}
		if (IN6_IS_ADDR_V4MAPPED (&qa6->sin6_addr)) {
			memcpy (&qa->sin_addr, &(qa6->sin6_addr.s6_addr[12]), 4);
			host = gdm_host_known ((char *) &qa->sin_addr, AF_INET);
		}
		else
			host = gdm_host_known ((char *) &qa6->sin6_addr, AF_INET6);
	} else
#endif
	{
		memset (&sock, 0, sizeof (struct sockaddr_in));
		sock.sin_family = AF_INET;
		sock.sin_port = htons (XDM_UDP_PORT);
		status = gdm_addr_known ((char *)&qa->sin_addr, AF_INET);
		if ( ! status) {
			queryaddr = g_slist_append (queryaddr, qa);
		}
		host = gdm_host_known ((char *) &qa->sin_addr, AF_INET);
	}

	if (host != NULL) {
		GtkTreeIter iter = {0};
		if (find_host_in_list (host, &iter)) {
			GtkTreeSelection *selection;
			GtkTreePath *path = gtk_tree_model_get_path (browser_model, &iter);
			selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (browser));
			gtk_tree_selection_select_iter (selection, &iter);
			gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (browser),
						      path, NULL,
						      FALSE, 0.0, 0.0);
			gtk_tree_path_free (path);
			gtk_widget_grab_focus (manage);
		} else {
			/* hmm, probably not willing, ping the host then for
			   good measure */
#ifdef ENABLE_IPV6
			if (have_ipv6) {
				memcpy (&sock6.sin6_addr, &qa6->sin6_addr, sizeof (qa6->sin6_addr));
				XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock6, (int) sizeof (struct sockaddr_in6));
				added6_addr = &qa6->sin6_addr;
				if (IN6_IS_ADDR_V4MAPPED (added6_addr))
					added_addr = (struct in_addr *)&(qa6->sin6_addr.s6_addr[12]);
			} else
#endif
			{
				sock.sin_addr.s_addr = qa->sin_addr.s_addr;
				XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock, (int)sizeof (struct sockaddr_in));
				added_addr = &qa->sin_addr;
			}
			g_free (added_host);
			added_host = g_strdup (name);

			if (add_check_handler > 0)
				g_source_remove (add_check_handler);
			add_check_handler = g_timeout_add (ADD_TIMEOUT,
							   add_check, NULL);
		}

		/* empty the text entry to indicate success */
		gtk_entry_set_text (GTK_ENTRY (add_entry), "");
		g_free (qa);
#ifdef ENABLE_IPV6
		g_free (qa6);
#endif
		return;
	}
#ifdef ENABLE_IPV6
	if (have_ipv6) {
		added6_addr = &qa6->sin6_addr;

		if (IN6_IS_ADDR_V4MAPPED (added6_addr))
			added_addr = (struct in_addr *)&(qa6->sin6_addr.s6_addr[12]);

		memcpy (&sock6.sin6_addr, &qa6->sin6_addr, sizeof (struct in6_addr));
		XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock6, (int)sizeof (struct sockaddr_in6));
	} else
#endif
	{
		added_addr = &qa->sin_addr;

		/* and send out the query */
		sock.sin_addr.s_addr = qa->sin_addr.s_addr;
		XdmcpFlush (sockfd, &querybuf, (XdmcpNetaddr) &sock, (int)sizeof (struct sockaddr_in));
	}
	g_free (added_host);
	added_host = g_strdup (name);
	if (add_check_handler > 0)
		g_source_remove (add_check_handler);
	add_check_handler = g_timeout_add (ADD_TIMEOUT,
					   add_check, NULL);

	/* empty the text entry to indicate success */
	gtk_entry_set_text (GTK_ENTRY (add_entry), "");

	g_free (qa);
#ifdef ENABLE_IPV6
	g_free (qa6);
#endif
}

void
gdm_chooser_add_entry_changed (void)
{
	const char *name;

	name = gtk_entry_get_text (GTK_ENTRY (add_entry));
	gtk_widget_set_sensitive (add_button, ! ve_string_empty (name));
}

void
gdm_chooser_cancel (/*void*/)
{
    if (scan_time_handler > 0) {
	    g_source_remove (scan_time_handler);
	    scan_time_handler = 0;
    }

    closelog ();
    /* exit rather gtk_main_quit, it's just safer this way we don't
       have to worry about random whackiness happening */
    exit (EXIT_SUCCESS);
}


void
gdm_chooser_manage (GtkButton *button, gpointer data)
{
    if (scan_time_handler > 0) {
	    g_source_remove (scan_time_handler);
	    scan_time_handler = 0;
    }

    if (curhost)
      gdm_chooser_choose_host (curhost->name);
   
    closelog ();

    /* exit rather gtk_main_quit, it's just safer this way we don't
       have to worry about random whackiness happening */
    exit (EXIT_SUCCESS);
}

static void
host_selected (GtkTreeSelection *selection, gpointer data)
{
	GtkTreeModel *tm = NULL;
	GtkTreeIter iter = {0};

	curhost = NULL;

	if (gtk_tree_selection_get_selected (selection, &tm, &iter)) {
		gtk_tree_model_get (tm, &iter, CHOOSER_LIST_HOST_COLUMN,
				    &curhost, -1);
	}

	gtk_widget_set_sensitive (manage, curhost != NULL);
}

static void
row_activated (GtkTreeView *tree_view,
	       GtkTreePath *path,
	       GtkTreeViewColumn *column)
{
	if (curhost != NULL)
		gdm_chooser_manage (NULL, NULL);
}

void
display_chooser_information (void)
{
	GtkWidget *dialog;

	/* How to get HIG compliance? */
	dialog = gtk_message_dialog_new
		(GTK_WINDOW (chooser) /* parent */,
		 GTK_DIALOG_MODAL /* flags */,
		 GTK_MESSAGE_INFO,
		 GTK_BUTTONS_OK,
		 _("The main area of this application shows the hosts on "
		   "the local network that have \"XDMCP\" enabled. This "
		   "allows users to login remotely to other computers as "
		   "if they were logged on using the console.\n\n"
		   "You can rescan the network for new hosts by clicking "
		   "\"Refresh\".  When you have selected a host click "
		   "\"Connect\" to open a session to that computer."));
	gtk_dialog_set_has_separator (GTK_DIALOG (dialog), FALSE);

	if (RUNNING_UNDER_GDM)
		gdm_wm_center_window (GTK_WINDOW (dialog));

	gdm_wm_no_login_focus_push ();
	gtk_dialog_run (GTK_DIALOG (dialog));
	gtk_widget_destroy (dialog);
	gdm_wm_no_login_focus_pop ();
}

static void 
gdm_chooser_gui_init (void)
{
	GtkTreeSelection *selection;
	GtkTreeViewColumn *column;
	gchar *defaulthosticon;
	int width;
	int height;

	glade_helper_add_glade_directory (GDM_GLADE_DIR);
	glade_helper_search_gnome_dirs (FALSE);

    /* Enable theme */
    if (RUNNING_UNDER_GDM) {
	const char *theme_name;

	if ( ! ve_string_empty (gdm_config_get_string (GDM_KEY_GTKRC)))
		gtk_rc_parse (gdm_config_get_string (GDM_KEY_GTKRC));

	theme_name = g_getenv ("GDM_GTK_THEME");
	if (ve_string_empty (theme_name))
		theme_name = gdm_config_get_string (GDM_KEY_GTK_THEME);

	if ( ! ve_string_empty (theme_name)) {
		gdm_set_theme (theme_name);
	}
    }

    defaulthosticon = gdm_config_get_string (GDM_KEY_DEFAULT_HOST_IMG);

    /* Load default host image */
    if (g_access (defaulthosticon, R_OK) != 0) {
	gdm_common_error ("Could not open default host icon: %s", defaulthosticon);
	/* bogus image */
	defhostimg = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
				     FALSE /* has_alpha */,
				     8 /* bits_per_sample */,
				     48 /* width */,
				     48 /* height */);
    } else {
	defhostimg = gdk_pixbuf_new_from_file (defaulthosticon, NULL);
    }

    /* Main window */
    chooser_app = glade_helper_load ("gdmchooser.glade",
				     "gdmchooser_main",
				     GTK_TYPE_DIALOG,
				     FALSE /* dump_on_destroy */);
    glade_xml_signal_autoconnect (chooser_app);
   
    chooser = glade_helper_get (chooser_app, "gdmchooser_main",
				GTK_TYPE_DIALOG);
    manage = glade_helper_get (chooser_app, "connect_button",
			       GTK_TYPE_BUTTON);
    rescan = glade_helper_get (chooser_app, "rescan_button",
			       GTK_TYPE_BUTTON);
    cancel = glade_helper_get (chooser_app, "quit_button",
			       GTK_TYPE_BUTTON);
    status_label = glade_helper_get (chooser_app, "status_label",
				     GTK_TYPE_LABEL);
    add_entry = glade_helper_get (chooser_app, "add_entry",
				  GTK_TYPE_ENTRY);
    add_button = glade_helper_get (chooser_app, "add_button",
				   GTK_TYPE_BUTTON);

    browser = glade_helper_get (chooser_app, "chooser_iconlist",
				GTK_TYPE_TREE_VIEW);

    gtk_dialog_set_has_separator (GTK_DIALOG (chooser), FALSE);

    gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (browser), TRUE);

    selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (browser));
    gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);

    g_signal_connect (selection, "changed",
		      G_CALLBACK (host_selected),
		      NULL);
    g_signal_connect (browser, "row_activated",
		      G_CALLBACK (row_activated),
		      NULL);

    browser_model = (GtkTreeModel *)gtk_list_store_new (3,
							GDK_TYPE_PIXBUF,
							G_TYPE_STRING,
							G_TYPE_POINTER);
    gtk_tree_view_set_model (GTK_TREE_VIEW (browser), browser_model);
    column = gtk_tree_view_column_new_with_attributes
	    ("Icon",
	     gtk_cell_renderer_pixbuf_new (),
	     "pixbuf", CHOOSER_LIST_ICON_COLUMN,
	     NULL);
    gtk_tree_view_append_column (GTK_TREE_VIEW (browser), column);

    column = gtk_tree_view_column_new_with_attributes
	    ("Hostname",
	     gtk_cell_renderer_text_new (),
	     "markup", CHOOSER_LIST_LABEL_COLUMN,
	     NULL);
    gtk_tree_view_append_column (GTK_TREE_VIEW (browser), column);

    gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (browser_model),
					  CHOOSER_LIST_LABEL_COLUMN,
					  GTK_SORT_ASCENDING);


    if ( ! gdm_config_get_bool (GDM_KEY_ALLOW_ADD)) {
	    GtkWidget *w = glade_helper_get (chooser_app, "add_hbox",
					     GTK_TYPE_HBOX);
	    gtk_widget_hide (w);
    }

    gtk_window_get_size (GTK_WINDOW (chooser),
			 &width, &height);
    if (RUNNING_UNDER_GDM) {
	    if (width > gdm_wm_screen.width)
		    width = gdm_wm_screen.width;
	    if (height > gdm_wm_screen.height)
		    height = gdm_wm_screen.height;
    } else {
	    if (width > gdk_screen_width ())
		    width = gdk_screen_width ();
	    if (height > gdk_screen_height ())
		    height = gdk_screen_height ();
    }
    gtk_widget_set_size_request (GTK_WIDGET (chooser), 
				 width, height);
    gtk_window_set_default_size (GTK_WINDOW (chooser), 
				 width, height);
    gtk_window_resize (GTK_WINDOW (chooser), 
		       width, height);


    /* cursor blinking is evil on remote displays, don't do it forever */
    gdm_common_setup_blinking ();
    gdm_common_setup_blinking_entry (add_entry);

    if (RUNNING_UNDER_GDM) {
	    gtk_widget_show_now (chooser);
	    gdm_wm_center_window (GTK_WINDOW (chooser));
    }
}

/* 
 * If new configuration keys are added to this program, make sure to add the
 * key to the gdm_read_config and gdm_reread_config functions.
 */
static gboolean
gdm_read_config (void)
{
	/* Read config data in bulk */
	gdmcomm_comm_bulk_start ();

	gdmcomm_set_debug (gdm_config_get_bool (GDM_KEY_DEBUG));

	/*
	 * Read all the keys at once and close sockets connection so we do
	 * not have to keep the socket open.  
	 */
	gdm_config_get_string (GDM_KEY_HOSTS);
	gdm_config_get_string (GDM_KEY_GTKRC);
	gdm_config_get_string (GDM_KEY_GTK_THEME);
	gdm_config_get_string (GDM_KEY_DEFAULT_HOST_IMG);
	gdm_config_get_string (GDM_KEY_HOST_IMAGE_DIR);
	gdm_config_get_string (GDM_KEY_MULTICAST_ADDR);
	gdm_config_get_string (GDM_KEY_BACKGROUND_COLOR);
	gdm_config_get_int    (GDM_KEY_XINERAMA_SCREEN);
	gdm_config_get_int    (GDM_KEY_MAX_ICON_WIDTH);
	gdm_config_get_int    (GDM_KEY_MAX_ICON_HEIGHT);
	gdm_config_get_int    (GDM_KEY_SCAN_TIME);
	gdm_config_get_int    (GDM_KEY_BACKGROUND_TYPE);
	gdm_config_get_bool   (GDM_KEY_ALLOW_ADD);
	gdm_config_get_bool   (GDM_KEY_BROADCAST);
	gdm_config_get_bool   (GDM_KEY_MULTICAST);

	gdmcomm_comm_bulk_stop ();
}

static gboolean
gdm_reread_config (int sig, gpointer data)
{
	/* reparse config stuff here.  At least ones we care about */

	/* Read config data in bulk */
	gdmcomm_comm_bulk_start ();

	if (gdm_config_reload_bool (GDM_KEY_DEBUG))
		gdmcomm_set_debug (gdm_config_get_bool (GDM_KEY_DEBUG));

	/* FIXME: The following is evil, we should update on the fly rather
	 * then just restarting */
	/* Also we may not need to check ALL those keys but just a few */
	if (gdm_config_reload_string (GDM_KEY_HOSTS) ||
	    gdm_config_reload_string (GDM_KEY_GTKRC) ||
	    gdm_config_reload_string (GDM_KEY_GTK_THEME) ||
	    gdm_config_reload_string (GDM_KEY_DEFAULT_HOST_IMG) ||
	    gdm_config_reload_string (GDM_KEY_HOST_IMAGE_DIR) ||
	    gdm_config_reload_string (GDM_KEY_MULTICAST_ADDR) ||
	    gdm_config_reload_int    (GDM_KEY_XINERAMA_SCREEN) ||
	    gdm_config_reload_int    (GDM_KEY_MAX_ICON_WIDTH) ||
	    gdm_config_reload_int    (GDM_KEY_MAX_ICON_HEIGHT) ||
	    gdm_config_reload_int    (GDM_KEY_SCAN_TIME) ||
	    gdm_config_reload_bool   (GDM_KEY_ALLOW_ADD) ||
	    gdm_config_reload_bool   (GDM_KEY_BROADCAST) ||
	    gdm_config_reload_bool   (GDM_KEY_MULTICAST)) {

		if (RUNNING_UNDER_GDM) {
			/* Set busy cursor */
			gdm_common_setup_cursor (GDK_WATCH);
			gdm_wm_save_wm_order ();
		}

		/* we don't need to tell the slave that we're restarting
		   it doesn't care about our state.  Unlike with the greeter */
		execvp (stored_argv[0], stored_argv);
		_exit (DISPLAY_REMANAGE);
	}

	/* we only use the color and do it for all types except NONE */
	if (gdm_config_reload_string (GDM_KEY_BACKGROUND_COLOR) ||
	    gdm_config_reload_int    (GDM_KEY_BACKGROUND_TYPE)) {

		if (gdm_config_get_int (GDM_KEY_BACKGROUND_TYPE) != GDM_BACKGROUND_NONE) {
			gdm_common_setup_background_color (gdm_config_get_string
				(GDM_KEY_BACKGROUND_COLOR));
		}
	}

	gdmcomm_comm_bulk_stop ();

	return TRUE;
}


static void
gdm_chooser_signals_init (void)
{
    struct sigaction hup;
    struct sigaction term;
    sigset_t mask;

    ve_signal_add (SIGHUP, gdm_reread_config, NULL);

    hup.sa_handler = ve_signal_notify;
    hup.sa_flags = 0;
    sigemptyset (&hup.sa_mask);
    sigaddset (&hup.sa_mask, SIGCHLD);

    term.sa_handler = gdm_chooser_cancel;
    term.sa_flags = 0;
    sigemptyset (&term.sa_mask);

    if (sigaction (SIGHUP, &hup, NULL) < 0) {
        gdm_common_fail_exit ("%s: Error setting up %s signal handler: %s",
	    "gdm_signals_init", "HUP", strerror (errno));
    }

    if (sigaction (SIGINT, &term, NULL) < 0) {
        gdm_common_fail_exit ("%s: Error setting up %s signal handler: %s",
           "gdm_signals_init", "INT", strerror (errno));
    }

    if (sigaction (SIGTERM, &term, NULL) < 0) {
        gdm_common_fail_exit ("%s: Error setting up %s signal handler: %s",
           "gdm_signals_init", "TERM", strerror (errno));
    }

    sigfillset (&mask);
    sigdelset (&mask, SIGTERM);
    sigdelset (&mask, SIGHUP);
    sigdelset (&mask, SIGINT);
    
    if (sigprocmask (SIG_SETMASK, &mask, NULL) == -1) 
	gdm_common_fail_exit ("Could not set signal mask!");
}

GOptionEntry chooser_options [] = {
       { "xdmaddress", '\0', 0, G_OPTION_ARG_STRING, &xdm_address,
          N_("Socket for xdm communication"), N_("SOCKET") },
       { "clientaddress", '\0', 0, G_OPTION_ARG_STRING, &client_address,
          N_("Client address to return in response to xdm"), N_("ADDRESS") },
       { "connectionType", '\0', 0, G_OPTION_ARG_INT, &connection_type,
          N_("Connection type to return in response to xdm"), N_("TYPE") },
       { G_OPTION_REMAINING, NULL, 0, G_OPTION_ARG_STRING_ARRAY, &chooser_hosts,
          NULL, NULL },
       { NULL }
 };

static gboolean
gdm_event (GSignalInvocationHint *ihint,
	   guint		n_param_values,
	   const GValue	       *param_values,
	   gpointer		data)
{
	GdkEvent *event;

	/* HAAAAAAAAAAAAAAAAACK */
	/* Since the user has not logged in yet and may have left/right
	 * mouse buttons switched, we just translate every right mouse click
	 * to a left mouse click */
	if (n_param_values != 2 ||
	    !G_VALUE_HOLDS (&param_values[1], GDK_TYPE_EVENT))
	  return FALSE;
	
	event = g_value_get_boxed (&param_values[1]);
	if ((event->type == GDK_BUTTON_PRESS ||
	     event->type == GDK_2BUTTON_PRESS ||
	     event->type == GDK_3BUTTON_PRESS ||
	     event->type == GDK_BUTTON_RELEASE)
	    && event->button.button == 3)
		event->button.button = 1;

	return TRUE;
}      

int 
main (int argc, char *argv[])
{
    gchar *GdmHosts;
    gchar **hosts_opt;
    GOptionContext *ctx;
    const char *gdm_version;
    int i;
    guint sid;

    stored_argv = g_new0 (char *, argc + 1);
    for (i = 0; i < argc; i++)
	    stored_argv[i] = g_strdup (argv[i]);
    stored_argv[i] = NULL;
    stored_argc = argc;

    if (g_getenv ("RUNNING_UNDER_GDM") != NULL)
	    RUNNING_UNDER_GDM = TRUE;

    gdm_common_openlog ("gdmchooser", LOG_PID, LOG_DAEMON);

    bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);

    gtk_init (&argc, &argv);

    ctx = g_option_context_new (_("- gdm login chooser")); 
    g_option_context_add_main_entries(ctx, chooser_options, _("main options"));
    g_option_context_parse(ctx, &argc, &argv, NULL);
    g_option_context_free(ctx);

    glade_init ();

    /* Read all configuration at once, so the values get cached */
    gdm_read_config ();

    GdmHosts = g_strdup (gdm_config_get_string (GDM_KEY_HOSTS));

    /* if broadcasting, then append BROADCAST to hosts */
    if (gdm_config_get_bool (GDM_KEY_BROADCAST)) {
	    gchar *tmp;
	    if (ve_string_empty (GdmHosts)) {
		    tmp = "BROADCAST";
	    } else {
		    tmp = g_strconcat (GdmHosts, ",BROADCAST", NULL);
	    }
	    g_free (GdmHosts);
	    GdmHosts = tmp;
    }

#ifdef ENABLE_IPV6
    if (gdm_config_get_bool (GDM_KEY_MULTICAST)) {
	    gchar *tmp;
	    if (ve_string_empty (GdmHosts)) {
		    tmp = "MULTICAST";
	    } else {
		    tmp = g_strconcat (GdmHosts, ",MULTICAST", NULL);
	    }
	    g_free (GdmHosts);
	    GdmHosts = tmp;
    }
#endif

    if (RUNNING_UNDER_GDM)
	    gdm_wm_screen_init (gdm_config_get_int (GDM_KEY_XINERAMA_SCREEN));

    gdm_version = g_getenv ("GDM_VERSION");

    /* Load the background as early as possible so GDM does not leave  */
    /* the background unfilled.   The cursor should be a watch already */
    /* but just in case */
    if (RUNNING_UNDER_GDM) {
	if (gdm_config_get_int (GDM_KEY_BACKGROUND_TYPE) != GDM_BACKGROUND_NONE)
		gdm_common_setup_background_color (gdm_config_get_string (GDM_KEY_BACKGROUND_COLOR));

	gdm_common_setup_cursor (GDK_WATCH);
    }

    if (RUNNING_UNDER_GDM &&
	gdm_version != NULL &&
	strcmp (gdm_version, VERSION) != 0) {
	    GtkWidget *dialog;
	    gchar *msg;

	    gdm_wm_init (0);

	    gdm_wm_focus_new_windows (TRUE);

	    msg = g_strdup_printf (_("The chooser version (%s) does not match the daemon "
	                             "version (%s).  "
	                             "You have probably just upgraded GDM.  "
	                             "Please restart the GDM daemon or the computer."),
	                           VERSION, gdm_version);

	    dialog = ve_hig_dialog_new (NULL /* parent */,
					GTK_DIALOG_MODAL /* flags */,
					GTK_MESSAGE_ERROR,
					GTK_BUTTONS_OK,
					_("Cannot run chooser"),
					msg);
	    g_free (msg);
	    
	    gtk_widget_show_all (dialog);
	    gdm_wm_center_window (GTK_WINDOW (dialog));

	    gdm_common_setup_cursor (GDK_LEFT_PTR);

	    gtk_dialog_run (GTK_DIALOG (dialog));

	    return EXIT_SUCCESS;
    }
    
    gtk_window_set_default_icon_from_file (DATADIR"/pixmaps/gdm-xnest.png", NULL);

    gdm_chooser_gui_init ();
    gdm_chooser_signals_init ();

    /* when no hosts on the command line, take them from the config */
    if (hosts_opt == NULL ||
	hosts_opt[0] == NULL) {
	    int i;
	    hosts_opt = g_strsplit (GdmHosts, ",", -1);
	    for (i = 0; hosts_opt != NULL && hosts_opt[i] != NULL; i++) {
		    g_strstrip (hosts_opt[i]);
	    }
    }
    gdm_chooser_xdmcp_init (hosts_opt);
    g_strfreev (chooser_hosts);

    sid = g_signal_lookup ("event",
				 GTK_TYPE_WIDGET);
    g_signal_add_emission_hook (sid,
				0 /* detail */,
				gdm_event,
				NULL /* data */,
				NULL /* destroy_notify */);

    gtk_widget_queue_resize (chooser);
    gtk_widget_show_now (chooser);

    if (RUNNING_UNDER_GDM)
	    gdm_wm_center_window (GTK_WINDOW (chooser));

    if (RUNNING_UNDER_GDM &&
	/* can it ever happen that it'd be NULL here ??? */
	chooser->window != NULL) {
	    gdm_wm_init (GDK_WINDOW_XWINDOW (chooser->window));

	    /* Run the focus, note that this will work no matter what
	     * since gdm_wm_init will set the display to the gdk one
	     * if it fails */
	    gdm_wm_focus_window (GDK_WINDOW_XWINDOW (chooser->window));
    }

    if (gdm_config_get_bool (GDM_KEY_ALLOW_ADD))
	    gtk_widget_grab_focus (add_entry);

    gdm_chooser_add_entry_changed ();

    if (RUNNING_UNDER_GDM) {
	    gdm_wm_restore_wm_order ();
	    gdm_common_setup_cursor (GDK_LEFT_PTR);
    }

    gtk_main ();

    exit (EXIT_SUCCESS);
}

/* EOF */