File: dm.c

package info (click to toggle)
kde-workspace 4:4.11.13-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 67,756 kB
  • ctags: 47,705
  • sloc: cpp: 358,638; ansic: 34,695; xml: 5,231; perl: 1,598; sh: 1,307; ruby: 1,135; python: 651; asm: 566; makefile: 37
file content (1798 lines) | stat: -rw-r--r-- 49,198 bytes parent folder | download
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
/*

Copyright 1988, 1998  The Open Group
Copyright 2000-2005 Oswald Buddenhagen <ossi@kde.org>

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 COPYRIGHT HOLDERS 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 a copyright holder 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 copyright holder.

*/

/*
 * xdm - display manager daemon
 * Author: Keith Packard, MIT X Consortium
 *
 * display manager
 */

#include "dm.h"
#include "dm_auth.h"
#include "dm_error.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <sys/stat.h>

#ifdef HAVE_VTS
# include <sys/ioctl.h>
#if defined(__linux__)
# include <sys/vt.h>
#elif defined(__FreeBSD_kernel__)
# include <sys/consio.h>
# include <sys/tty.h>
# include <sys/sysctl.h>
#endif
#endif

static void sigHandler(int n);
static int scanConfigs(int force);
static void startDisplay(struct display *d);
static void startDisplays(void);
#define XS_KEEP 0
#define XS_RESTART 1
#define XS_RETRY 2
static void exitDisplay(struct display *d, int endState, int serverCmd, int goodExit);
static void rStopDisplay(struct display *d, int endState);
static void mainLoop(void);

static int signalFds[2];

#if !defined(HAVE_SETPROCTITLE) && !defined(NOXDMTITLE)
static char *title;
static int titleLen;
#endif

static int storePid(void);

static int stopping;
SdRec sdRec = { 0, 0, 0, TO_INF, TO_INF, 0, 0, 0 };

time_t now;
#if (_POSIX_MONOTONIC_CLOCK >= 0)
time_t nowWallDelta;
# ifndef nowMonotonic
int nowMonotonic;
# endif
#endif

#if KDM_LIBEXEC_STRIP != -1
char *progpath;
#endif
#if KDM_LIBEXEC_STRIP
char *progname;
#endif
char *prog;

int
main(int argc, char **argv)
{
    int oldpid, oldumask, fd, parentPid;
    char *pt, *errorLogFile, **opts;

    /* make sure at least world write access is disabled */
    if (((oldumask = umask(022)) & 002) == 002)
        (void)umask(oldumask);

    /* give /dev/null as stdin */
    if ((fd = open("/dev/null", O_RDONLY)) > 0) {
        dup2(fd, 0);
        close(fd);
    }
    if (fcntl(1, F_GETFD) < 0)
        dup2(0, 1);
    if (fcntl(2, F_GETFD) < 0)
        dup2(0, 2);

#ifndef nowMonotonic
    nowMonotonic = sysconf(_SC_MONOTONIC_CLOCK) >= 200112L;
#endif

#if KDM_LIBEXEC_STRIP == -1
    prog = strrchr(argv[0], '/');
    progname = prog = prog ? prog + 1 : argv[0];
#else
    if (argv[0][0] == '/') {
        if (!strDup(&progpath, argv[0]))
            panic("Out of memory");
    } else
# ifdef __linux__
    {
        /* note that this will resolve symlinks ... */
        int len;
        char fullpath[PATH_MAX];
        if ((len = readlink("/proc/self/exe", fullpath, sizeof(fullpath))) < 0)
            panic("Invoke with full path specification or mount /proc");
        if (!strNDup(&progpath, fullpath, len))
            panic("Out of memory");
    }
# else
#  if 0
        panic("Must be invoked with full path specification");
#  else
    {
        char directory[PATH_MAX+1];
        if (!getcwd(directory, sizeof(directory)))
            panic("Can't find myself (getcwd failed)");
        if (strchr(argv[0], '/')) {
            strApp(&progpath, directory, "/", argv[0], (char *)0);
        } else {
            int len;
            char *path, *pathe, *name, *thenam, nambuf[PATH_MAX+1];

            if (!(path = getenv("PATH")))
                panic("Can't find myself (no PATH)");
            len = strlen(argv[0]);
            name = nambuf + PATH_MAX - len;
            memcpy(name, argv[0], len + 1);
            *--name = '/';
            do {
                if (!(pathe = strchr(path, ':')))
                    pathe = path + strlen(path);
                len = pathe - path;
                if (!len || (len == 1 && *path == '.')) {
                    len = strlen(directory);
                    path = directory;
                }
                thenam = name - len;
                if (thenam >= nambuf) {
                    memcpy(thenam, path, len);
                    if (!access(thenam, X_OK))
                        goto found;
                }
                path = pathe;
            } while (*path++ != '\0');
            panic("Can't find myself (not in PATH)");
          found:
            if (!strDup(&progpath, thenam))
                panic("Out of memory");
        }
    }
#  endif
# endif
    prog = strrchr(progpath, '/') + 1;
# if KDM_LIBEXEC_STRIP
    for (progname = pt = prog, fd = 0; fd < KDM_LIBEXEC_STRIP + 1; fd++) {
        for (;;) {
            pt--;
            if (pt == progpath)
                panic("Executable is obviously located outside BINDIR");
            if (*pt == '/')
                break;
        }
    }
    *pt = 0;
# endif
#endif

#if !defined(HAVE_SETPROCTITLE) && !defined(NOXDMTITLE)
    title = argv[0];
    titleLen = (argv[argc - 1] + strlen(argv[argc - 1])) - title;
#endif

    /*
     * Parse command line options
     */
    parentPid = getppid();
    errorLogFile = 0;
    if (!(opts = Malloc(2 * sizeof(char *))))
        return 1;
    opts[0] = (char *)"";
    opts[1] = 0;
    while (*++argv) {
        if (**argv != '-')
            break;
        pt = *argv + 1;
        if (*pt == '-')
            pt++;
        if (!strcmp(pt, "help") || !strcmp(pt, "h")) {
            printf("Usage: %s [options] [tty]\n"
"  -daemon\t  - Daemonize even when started by init\n"
"  -nodaemon\t  - Do not daemonize even when started from command line\n"
"  -config <file>  - Use alternative master configuration file\n"
"  -xrm <res>\t  - Override frontend-specific resource\n"
"  -error <file>\t  - Use alternative log file\n"
"  -debug <num>\t  - Debug option bitfield:\n"
"\t\t\t0x1 - core log\n"
"\t\t\t0x2 - config reader log\n"
"\t\t\t0x4 - greeter log\n"
"\t\t\t0x8 - IPC log\n"
"\t\t\t0x10 - session sub-daemon post-fork delay\n"
"\t\t\t0x20 - config reader post-start delay\n"
"\t\t\t0x40 - greeter post-start delay\n"
"\t\t\t0x80 - do not use syslog\n"
"\t\t\t0x100 - core Xauth log\n"
"\t\t\t0x200 - debug greeter theming\n"
"\t\t\t0x400 - valgrind config reader and greeter\n"
"\t\t\t0x800 - strace config reader and greeter\n"
                    , prog);
            exit(0);
        } else if (!strcmp(pt, "daemon")) {
            parentPid = 0;
        } else if (!strcmp(pt, "nodaemon")) {
            parentPid = 1;
        } else if (argv[1] && !strcmp(pt, "config")) {
            strDup(opts, *++argv);
        } else if (argv[1] && !strcmp(pt, "xrm")) {
            opts = addStrArr(opts, *++argv, -1);
        } else if (argv[1] && !strcmp(pt, "debug")) {
            sscanf(*++argv, "%i", &debugLevel);
        } else if (argv[1] && (!strcmp(pt, "error") || !strcmp(pt, "logfile"))) {
            errorLogFile = *++argv;
        } else {
            fprintf(stderr, "\"%s\" is an unknown option or is missing a parameter\n", *argv);
            exit(1);
        }
    }

    /*
     * Only allow root to run in non-debug mode to avoid problems
     */
    if (!debugLevel && getuid()) {
        fprintf(stderr, "Only root wants to run %s\n", prog);
        exit(1);
    }

    initErrorLog(errorLogFile);

    if (parentPid != 1)
        becomeDaemon();

    /*
     * Step 1 - load configuration parameters
     */
    if (!initResources(opts) || scanConfigs(False) < 0)
        logPanic("Config reader failed. Aborting ...\n");

    /* SUPPRESS 560 */
    if ((oldpid = storePid())) {
        if (oldpid == -1)
            logError("Cannot create/lock pid file %s\n", pidFile);
        else
            logError("Cannot lock pid file %s, another xdm is running (pid %d)\n",
                     pidFile, oldpid);
        exit(1);
    }

#ifdef NEED_ENTROPY
    addOtherEntropy();
#endif

    /*
     * We used to clean up old authorization files here. As authDir is
     * supposed to be /var/run/xauth or /tmp, we needn't to care for it.
     */

#ifdef XDMCP
    initXdmcp();
#else
    debug("not compiled for XDMCP\n");
#endif
    if (pipe(signalFds))
        logPanic("Unable to create signal notification pipe.\n");
    registerInput(signalFds[0]);
    registerCloseOnFork(signalFds[0]);
    registerCloseOnFork(signalFds[1]);
    (void)Signal(SIGTERM, sigHandler);
    (void)Signal(SIGINT, sigHandler);
    (void)Signal(SIGHUP, sigHandler);
    (void)Signal(SIGCHLD, sigHandler);
    (void)Signal(SIGUSR1, sigHandler);

    /*
     * Step 2 - run a sub-daemon for each entry
     */
    openCtrl(0);
#ifdef XDMCP
    updateListenSockets();
#endif
    mainLoop();
    closeCtrl(0);
    if (sdRec.how) {
        int pid;
        commitBootOption();
        if (Fork(&pid) <= 0) {
            char *cmd = sdRec.how == SHUT_HALT ? cmdHalt : cmdReboot;
            execute(parseArgs((char **)0, cmd), (char **)0);
            logError("Failed to execute shutdown command %\"s\n", cmd);
            exit(1);
        } else {
            sigset_t mask;
            sigemptyset(&mask);
            sigaddset(&mask, SIGCHLD);
            sigaddset(&mask, SIGHUP);
            sigsuspend(&mask);
        }
    }
    debug("nothing left to do, exiting\n");
    return 0;
}

void
updateNow(void)
{
#if (_POSIX_MONOTONIC_CLOCK >= 0)
    if (nowMonotonic) {
        struct timespec ts;
        clock_gettime(CLOCK_MONOTONIC, &ts);
        /* Linux' monotonic clock starts at zero, but this is assumed to mean "long ago". */
        now = ts.tv_sec + 10000;
        /* When we read wall clock dates (e.g. from UTMP), we need to map
           them to the monotonic clock. Of course, such mapping defeats the
           point of a monotonic clock in the first place, but we have little
           choice. */
        nowWallDelta = time(0) - now;
    } else
#endif
        time(&now);
}


#ifdef HAVE_VTS
int
TTYtoVT(const char *tty)
{
    if (!memcmp(tty, "ttyv", 4)) /* FreeBSD, tty no is in hex */
        return (int) strtoul(tty+4, NULL, 16);
    else if (!memcmp(tty, "tty", 3)) /* Linux */
        return atoi(tty + 3);
    else
        return 0;
}

int
activateVT(int vt)
{
    int ret = False;
    int con = open("/dev/console", O_RDONLY);
    if (con >= 0) {
        if (!ioctl(con, VT_ACTIVATE, vt))
            ret = True;
        close(con);
    }
    return ret;
}


static void
wakeDisplay(struct display *d)
{
    if (d->status == textMode)
        d->status = (d->displayType & d_lifetime) == dReserve ? reserve : notRunning;
}
#endif

enum utState {
    UtDead,   /* no such entry */
    UtWait,   /* waiting for user login */
    UtActive  /* user logged in */
};

struct utmps {
#ifndef HAVE_VTS
    struct utmps *next;
    struct display *d;
#endif
    time_t time;
    enum utState state;
    int hadSess;
};

#define TIME_LOG 40
#define TIME_RELOG 10

static struct utmps *utmpList;
static time_t utmpTimeout = TO_INF;

void
wakeDisplays(void)
{
#ifdef HAVE_VTS
    forEachDisplay(wakeDisplay);
    free(utmpList);
    utmpList = 0;
#else
    struct utmps *utp;
    while ((utp = utmpList)) {
        utp->d->status = notRunning;
        utmpList = utp->next;
        free(utp);
    }
#endif
}

static void
checkUtmp(void)
{
    static time_t modtim;
    time_t nck;
    time_t ends;
    struct utmps *utp;
#ifndef HAVE_VTS
    struct utmps **utpp;
#endif
    struct stat st;
#ifdef BSD_UTMP
    int fd;
    struct utmp ut[1];
#else
    STRUCTUTMP *ut;
#endif

    if (!utmpList)
        return;
    if (stat(UTMP_FILE, &st)) {
        logError(UTMP_FILE " not found - cannot use console mode\n");
        wakeDisplays();
        return;
    }
    if (modtim != st.st_mtime) {
        debug("rescanning " UTMP_FILE "\n");
#ifdef HAVE_VTS
        utp = utmpList;
#else
        for (utp = utmpList; utp; utp = utp->next)
#endif
            utp->state = UtDead;
#ifdef BSD_UTMP
        if ((fd = open(UTMP_FILE, O_RDONLY)) < 0) {
            logError("Cannot open " UTMP_FILE " - cannot use console mode\n");
            wakeDisplays();
            return;
        }
        while (reader(fd, ut, sizeof(ut[0])) == sizeof(ut[0]))
#else
        SETUTENT();
        while ((ut = GETUTENT()))
#endif
        {
            /* first, match the tty to a utemps */
#ifdef HAVE_VTS
            char **line;
            for (line = consoleTTYs; *line; line++)
                if (!strncmp(*line, ut->ut_line, sizeof(ut->ut_line)))
#else
            for (utp = utmpList; utp; utp = utp->next)
                if (!strncmp(utp->d->console, ut->ut_line, sizeof(ut->ut_line)))
#endif
                    goto hitlin;
            continue;
          hitlin:
            /* then, update the utemps accordingly */
#ifdef BSD_UTMP
            if (!*ut->ut_user) {
#else
            if (ut->ut_type != USER_PROCESS) {
#endif
#ifdef HAVE_VTS
                /* don't allow "downgrading" the singular utemps */
                if (utp->state == UtActive)
                    continue;
#endif
                utp->state = UtWait;
            } else {
                utp->hadSess = True;
                utp->state = UtActive;
            }
            nck = ut->ut_time - nowWallDelta;
            if (nck > now)
                nck = 0; /* Clock jumped. Time out immediately. */
#ifdef HAVE_VTS
            /* tty with latest activity wins */
            if (utp->time < nck)
#endif
                utp->time = nck;
        }
#ifdef BSD_UTMP
        close(fd);
#else
        ENDUTENT();
#endif
        modtim = st.st_mtime;
    }
#ifdef HAVE_VTS
    utp = utmpList;
#else
    for (utpp = &utmpList; (utp = *utpp);) {
#endif
        if (utp->state != UtActive) {
            if (utp->state == UtDead) /* shouldn't happen ... */
                utp->time = 0;
            ends = utp->time + (utp->hadSess ? TIME_RELOG : TIME_LOG);
            if (ends <= now) {
#ifdef HAVE_VTS
                wakeDisplays();
                debug("console login timed out\n");
                return;
#else
                utp->d->status = notRunning;
                debug("console login for %s at %s timed out\n",
                       utp->d->name, utp->d->console);
                *utpp = utp->next;
                free(utp);
                continue;
#endif
            } else
                nck = ends;
        } else
            nck = TIME_RELOG + now;
        if (nck < utmpTimeout)
            utmpTimeout = nck;
#ifndef HAVE_VTS
        utpp = &(*utpp)->next;
    }
#endif
}

static void
#ifdef HAVE_VTS
switchToTTY(void)
#else
switchToTTY(struct display *d)
#endif
{
    struct utmps *utp;
#ifdef HAVE_VTS
    int vt;
#endif

    if (!(utp = Malloc(sizeof(*utp)))) {
#ifdef HAVE_VTS
        wakeDisplays();
#else
        d->status = notRunning;
#endif
        return;
    }
#ifndef HAVE_VTS
    d->status = textMode;
    utp->d = d;
    utp->next = utmpList;
#endif
    utp->time = now;
    utp->hadSess = False;
    utmpList = utp;
    checkUtmp();

#ifdef HAVE_VTS
    if ((vt = TTYtoVT(*consoleTTYs)))
        activateVT(vt);
#endif
}

#ifdef HAVE_VTS
static void
stopToTTY(struct display *d)
{
    if ((d->displayType & d_location) == dLocal)
        switch (d->status) {
        default:
            rStopDisplay(d, DS_TEXTMODE | DS_SCHEDULE);
        case reserve:
        case textMode:
            break;
        }
}

static void
checkTTYMode(void)
{
    struct display *d;

    for (d = displays; d; d = d->next)
        if (d->status == zombie)
            return;

    switchToTTY();
}

#else

void
switchToX(struct display *d)
{
    struct utmps *utp, **utpp;

    for (utpp = &utmpList; (utp = *utpp); utpp = &(*utpp)->next)
        if (utp->d == d) {
            *utpp = utp->next;
            free(utp);
            d->status = notRunning;
            return;
        }
}
#endif

#ifdef XDMCP
static void
startRemoteLogin(struct display *d)
{
    char **argv;

    debug("startRemoteLogin for %s\n", d->name);
    /* HACK: omitting loadDisplayResources(d) here! */
    switch (Fork(&d->serverPid)) {
    case 0:
        argv = prepareServerArgv(d, d->serverArgsRemote);
        if (!(argv = addStrArr(argv, "-once", 5)) ||
            !(argv = addStrArr(argv, "-query", 6)) ||
            !(argv = addStrArr(argv, d->remoteHost, -1)))
            exit(1);
        debug("exec %\"[s\n", argv);
        (void)execv(argv[0], argv);

        /* Let's try again with a standard path */
        argv[0] = "/usr/bin/X";
        debug( "exec %\"[s\n", argv );
        (void)execv( argv[0], argv );

        logError( "X server %\"s cannot be executed\n", argv[0] );
        exit(1);
    case -1:
        logError("Forking X server for remote login failed: %m");
        d->status = notRunning;
        return;
    default:
        break;
    }
    debug("X server forked, pid %d\n", d->serverPid);

    d->status = remoteLogin;
}
#endif


static void
stopInactiveDisplay(struct display *d)
{
    if (d->status != remoteLogin && d->userSess < 0)
        stopDisplay(d);
}

static void
stoppen(int force)
{
#ifdef XDMCP
    requestPort = 0;
    updateListenSockets();
#endif
    if (force)
        forEachDisplay(stopDisplay);
    else
        forEachDisplay(stopInactiveDisplay);
    stopping = True;
}


static void
sessionDone(struct display *d)
{
    d->userSess = -1;
    free(d->userName);
    free(d->sessName);
    d->userName = d->sessName = 0;
}

void
setNLogin(struct display *d,
          const char *nuser, const char *npass, const char *nargs, int rl)
{
    struct disphist *he = d->hstent;
    he->rLogin =
        (reStr(&he->nuser, nuser) &&
         reStr(&he->npass, npass) &&
         reStr(&he->nargs, nargs)) ? rl : 0;
    debug("set next login for %s, level %d\n", nuser, rl);
}

static void
processDPipe(struct display *d)
{
    char *user, *pass, *args;
    int cmd;
    GTalk dpytalk;
#ifdef XDMCP
    int ct, len;
    ARRAY8 ca, cp, ha;
#endif

    dpytalk.pipe = &d->pipe;
    if (Setjmp(dpytalk.errjmp)) {
        stopDisplay(d);
        return;
    }
    gSet(&dpytalk);
    if (!gRecvCmd(&cmd)) {
        /* process already exited */
        unregisterInput(d->pipe.fd.r);
        return;
    }
    switch (cmd) {
    case D_User:
        d->userSess = gRecvInt();
        d->userName = gRecvStr();
        d->sessName = gRecvStr();
        break;
    case D_UnUser:
        sessionDone(d);
        if (d->sdRec.how) {
            if (d->sdRec.force == SHUT_ASK &&
                (anyUserLogins(-1) || d->allowShutdown == SHUT_ROOT))
            {
                gSendInt(True);
            } else {
                if (!sdRec.how || sdRec.force != SHUT_FORCE ||
                    !((d->allowNuke == SHUT_NONE && sdRec.uid != d->sdRec.uid) ||
                      (d->allowNuke == SHUT_ROOT && d->sdRec.uid)))
                {
                    free(sdRec.osname);
                    sdRec = d->sdRec;
                } else {
                    free(d->sdRec.osname);
                }
                d->sdRec.how = 0;
                d->sdRec.osname = 0;
                gSendInt(False);
            }
        } else {
            gSendInt(False);
        }
        break;
    case D_ReLogin:
        user = gRecvStr();
        pass = gRecvStr();
        args = gRecvStr();
        setNLogin(d, user, pass, args, 1);
        free(args);
        free(pass);
        free(user);
        break;
#ifdef XDMCP
    case D_ChooseHost:
        ca.data = (unsigned char *)gRecvArr(&len);
        ca.length = (CARD16)len;
        cp.data = (unsigned char *)gRecvArr(&len);
        cp.length = (CARD16)len;
        ct = gRecvInt();
        ha.data = (unsigned char *)gRecvArr(&len);
        ha.length = (CARD16)len;
        registerIndirectChoice(&ca, &cp, ct, &ha);
        XdmcpDisposeARRAY8(&ha);
        XdmcpDisposeARRAY8(&cp);
        XdmcpDisposeARRAY8(&ca);
        break;
    case D_RemoteHost:
        free(d->remoteHost);
        d->remoteHost = gRecvStr();
        break;
#endif
    case D_XConnOk:
        startingServer = 0;
        break;
    default:
        logError("Internal error: unknown D_* command %d\n", cmd);
        stopDisplay(d);
        break;
    }
}

static void
emitXSessG(struct display *di, struct display *d, void *ctx ATTR_UNUSED)
{
    gSendStr(di->name);
    gSendStr("");
#ifdef HAVE_VTS
    gSendInt(di->serverVT);
#endif
#ifdef XDMCP
    if (di->status == remoteLogin) {
        gSendStr("");
        gSendStr(di->remoteHost);
    } else
#endif
    {
        gSendStr(di->userName);
        gSendStr(di->sessName);
    }
    gSendInt(di == d ? isSelf : 0);
}

static void
emitTTYSessG(STRUCTUTMP *ut, struct display *d ATTR_UNUSED, void *ctx ATTR_UNUSED)
{
    gSendStrN(ut->ut_line, sizeof(ut->ut_line));
    gSendStrN(ut->ut_host, sizeof(ut->ut_host));
#ifdef HAVE_VTS
    gSendInt(TTYtoVT(ut->ut_line));
#endif
#ifdef BSD_UTMP
    gSendStrN(*ut->ut_user ? ut->ut_user : 0, sizeof(ut->ut_user));
#else
    gSendStrN(ut->ut_type == USER_PROCESS ? ut->ut_user : 0, sizeof(ut->ut_user));
#endif
    gSendStr(0); /* session type unknown */
    gSendInt(isTTY);
}

static void
processGPipe(struct display *d)
{
    char **opts, *option;
    int cmd, ret, dflt, curr;
    GTalk dpytalk;

    dpytalk.pipe = &d->gpipe;
    if (Setjmp(dpytalk.errjmp)) {
        stopDisplay(d);
        return;
    }
    gSet(&dpytalk);
    if (!gRecvCmd(&cmd)) {
        /* process already exited */
        unregisterInput(d->gpipe.fd.r);
        return;
    }
    switch (cmd) {
    case G_ListBootOpts:
        ret = getBootOptions(&opts, &dflt, &curr);
        gSendInt(ret);
        if (ret == BO_OK) {
            gSendArgv(opts);
            freeStrArr(opts);
            gSendInt(dflt);
            gSendInt(curr);
        }
        break;
    case G_Shutdown:
        sdRec.how = gRecvInt();
        sdRec.start = gRecvInt();
        sdRec.timeout = gRecvInt();
        sdRec.force = gRecvInt();
        sdRec.uid = gRecvInt();
        option = gRecvStr();
        setBootOption(option, &sdRec);
        free(option);
        break;
    case G_QueryShutdown:
        gSendInt(sdRec.how);
        gSendInt(sdRec.start);
        gSendInt(sdRec.timeout);
        gSendInt(sdRec.force);
        gSendInt(sdRec.uid);
        gSendStr(sdRec.osname);
        break;
    case G_QryDpyShutdown:
        gSendInt(d->sdRec.how);
        gSendInt(d->sdRec.uid);
        gSendStr(d->sdRec.osname);
        break;
    case G_List:
        listSessions(gRecvInt(), d, 0, emitXSessG, emitTTYSessG);
        gSendInt(0);
        break;
#ifdef HAVE_VTS
    case G_Activate:
        activateVT(gRecvInt());
        break;
#endif
    case G_Console:
#ifdef HAVE_VTS
        if (*consoleTTYs) { /* sanity check against greeter */
            forEachDisplay(stopToTTY);
            checkTTYMode();
        }
#else
        if (*d->console) /* sanity check against greeter */
            rStopDisplay(d, DS_TEXTMODE);
#endif
        break;
    default:
        logError("Internal error: unknown G_* command %d\n", cmd);
        stopDisplay(d);
        break;
    }
}


static int
scanConfigs(int force)
{
    int ret;

    if ((ret = loadDMResources(force)) <= 0)
        return ret;
    scanServers();
#ifdef XDMCP
    scanAccessDatabase(force);
#endif
    return 1;
}

static void
markDisplay(struct display *d)
{
    d->stillThere = False;
}

static void
rescanConfigs(int force)
{
    if (scanConfigs(force) > 0) {
#ifdef XDMCP
        updateListenSockets();
#endif
        updateCtrl();
    }
}

void
cancelShutdown(void)
{
    sdRec.how = 0;
    free(sdRec.osname);
    sdRec.osname = 0;
    stopping = False;
    rescanConfigs(True);
}


static void
reapChildren(void)
{
    int pid;
    struct display *d;
    int status;

    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
        debug("manager wait returns  pid %d  sig %d  core %d  code %d\n",
              pid, waitSig(status), waitCore(status), waitCode(status));
        /* SUPPRESS 560 */
        if ((d = findDisplayByPid(pid))) {
            d->pid = -1;
            unregisterInput(d->pipe.fd.r);
            gClosen(&d->pipe);
            unregisterInput(d->gpipe.fd.r);
            gClosen(&d->gpipe);
            closeCtrl(d);
            switch (wcFromWait(status)) {
#ifdef XDMCP
            case EX_REMOTE:
                debug("display exited with EX_REMOTE\n");
                exitDisplay(d, DS_REMOTE, 0, False);
                break;
#endif
            case EX_NORMAL:
                /* (any type of) session ended */
                debug("display exited with EX_NORMAL\n");
                if ((d->displayType & d_lifetime) == dReserve)
                    exitDisplay(d, DS_RESERVE, 0, False);
                else
                    exitDisplay(d, DS_RESTART, XS_KEEP, True);
                break;
            case EX_RESERVE:
                debug("display exited with EX_RESERVE\n");
                exitDisplay(d, DS_RESERVE, 0, False);
                break;
#if 0
            case EX_REMANAGE_DPY:
                /* user session ended */
                debug("display exited with EX_REMANAGE_DPY\n");
                exitDisplay(d, DS_RESTART, XS_KEEP, True);
                break;
#endif
            case EX_OPENFAILED_DPY:
                /* waitForServer() failed */
                logError("Display %s cannot be opened\n", d->name);
#ifdef XDMCP
                /*
                 * no display connection was ever made, tell the
                 * terminal that the open attempt failed
                 */
                if ((d->displayType & d_origin) == dFromXDMCP)
                    sendFailed(d, "cannot open display");
#endif
                exitDisplay(d, DS_RESTART, XS_RETRY, False);
                break;
            case wcCompose(SIGTERM, 0, 0):
                /* killed before/during waitForServer()
                   - local Xserver died
                   - display stopped (is zombie)
                   - "login now" and "suicide" pipe commands (is raiser)
                */
                debug("display exited on SIGTERM\n");
                exitDisplay(d, DS_RESTART, XS_RETRY, False);
                break;
            case EX_AL_RESERVER_DPY:
                /* - killed after waitForServer()
                   - Xserver dead after remote session exit
                */
                debug("display exited with EX_AL_RESERVER_DPY\n");
                exitDisplay(d, DS_RESTART, XS_RESTART, False);
                break;
            case EX_RESERVER_DPY:
                /* induced by greeter:
                   - could not secure display
                   - requested by user
                */
                debug("display exited with EX_RESERVER_DPY\n");
                exitDisplay(d, DS_RESTART, XS_RESTART, True);
                break;
            case EX_UNMANAGE_DPY:
                /* some fatal error */
                debug("display exited with EX_UNMANAGE_DPY\n");
                exitDisplay(d, DS_REMOVE, 0, False);
                break;
            default:
                /* prolly crash */
                logError("Unknown session exit code %d (sig %d) from manager process\n",
                         waitCode(status), waitSig(status));
                exitDisplay(d, DS_REMOVE, 0, False);
                break;
            }
        } else if ((d = findDisplayByServerPid(pid))) {
            d->serverPid = -1;
            switch (d->status) {
            case zombie:
                debug("zombie X server for display %s reaped\n", d->name);
#ifdef HAVE_VTS
                if (d->serverVT && d->zstatus != DS_REMOTE) {
                    if (d->follower) {
                        d->follower->serverVT = d->serverVT;
                        d->follower = 0;
                    } else {
                        int con = open("/dev/console", O_RDONLY);
                        if (con >= 0) {
                            int activevt;
#if defined(__linux__)
                            struct vt_stat vtstat;
                            ioctl(con, VT_GETSTATE, &vtstat);
                            activevt = vtstat.v_active;
#elif defined(__FreeBSD_kernel__)
                            ioctl(con, VT_GETACTIVE, &activevt);
#endif
                            if (activevt == d->serverVT) {
                                int vt = 1;
                                struct display *di;
                                for (di = displays; di; di = di->next)
                                    if (di != d && di->serverVT)
                                        vt = di->serverVT;
                                for (di = displays; di; di = di->next)
                                    if (di != d && di->serverVT &&
                                        (di->userSess >= 0 ||
                                         di->status == remoteLogin))
                                        vt = di->serverVT;
                                ioctl(con, VT_ACTIVATE, vt);
                            }
#ifdef __linux__
                            ioctl(con, VT_DISALLOCATE, d->serverVT);
#endif
                            close(con);
                        }
                    }
                    d->serverVT = 0;
                }
#endif
                rStopDisplay(d, d->zstatus);
                break;
            case phoenix:
                debug("phoenix X server arises, restarting display %s\n",
                      d->name);
                d->status = notRunning;
                break;
            case remoteLogin:
                debug("remote login X server for display %s exited\n",
                      d->name);
                d->status = ((d->displayType & d_lifetime) == dReserve) ?
                            reserve : notRunning;
                break;
            case raiser:
                logError("X server for display %s terminated unexpectedly\n",
                         d->name);
                /* don't kill again */
                break;
            case running:
                if (startingServer == d && d->serverStatus != ignore) {
                    if (d->serverStatus == starting && waitCode(status) != 47)
                        logError("X server died during startup\n");
                    startServerFailed();
                    break;
                }
                logError("X server for display %s terminated unexpectedly\n",
                         d->name);
                if (d->pid != -1) {
                    debug("terminating session pid %d\n", d->pid);
                    terminateProcess(d->pid, SIGTERM);
                }
                break;
            case notRunning:
            case textMode:
            case reserve:
                /* this cannot happen */
                debug("X server exited for passive (%d) session on display %s\n",
                      (int)d->status, d->name);
                break;
            }
        } else {
            debug("unknown child termination\n");
        }
    }
#ifdef NEED_ENTROPY
    addOtherEntropy();
#endif
}

static int
wouldShutdown(void)
{
    switch (sdRec.force) {
    case SHUT_FORCE:
        return True;
    case SHUT_FORCEMY:
        return !anyUserLogins(sdRec.uid);
    case SHUT_CANCEL:
    default:
        return !anyUserLogins(-1);
    }
}

fd_set wellKnownSocketsMask;
int wellKnownSocketsMax;
int wellKnownSocketsCount;

void
registerInput(int fd)
{
    /* can be omited, as it is always called right after opening a socket
    if (!FD_ISSET(fd, &wellKnownSocketsMask))
    */
    {
        FD_SET(fd, &wellKnownSocketsMask);
        if (fd > wellKnownSocketsMax)
            wellKnownSocketsMax = fd;
        wellKnownSocketsCount++;
    }
}

void
unregisterInput(int fd)
{
    /* the check _is_ necessary, as some handles are unregistered before
       the regular close sequence.
    */
    if (FD_ISSET(fd, &wellKnownSocketsMask)) {
        FD_CLR(fd, &wellKnownSocketsMask);
        wellKnownSocketsCount--;
    }
}

static void
sigHandler(int n)
{
    int olderrno = errno;
    char buf = (char)n;
    /* debug("caught signal %d\n", n); this hangs in syslog() */
    write(signalFds[1], &buf, 1);
#ifdef __EMX__
    (void)Signal(n, sigHandler);
#endif
    errno = olderrno;
}

static void
mainLoop(void)
{
    struct display *d;
    struct timeval *tvp, tv;
    time_t to;
    int nready;
    char buf;
    fd_set reads;

    debug("mainLoop\n");
    updateNow();
    while (
#ifdef XDMCP
           anyListenSockets() ||
#endif
           (stopping ? anyRunningDisplays() : anyDisplaysLeft()))
    {
        if (!stopping)
            startDisplays();
#ifdef XDMCP
        to = disposeIndirectHosts();
#else
        to = TO_INF;
#endif
        if (sdRec.how) {
            if (sdRec.start != TO_INF && now < sdRec.start) {
                /*if (sdRec.start < to)*/
                    to = sdRec.start;
            } else {
                sdRec.start = TO_INF;
                if (now >= sdRec.timeout) {
                    sdRec.timeout = TO_INF;
                    if (wouldShutdown())
                        stoppen(True);
                    else
                        cancelShutdown();
                } else {
                    stoppen(False);
                    /*if (sdRec.timeout < to)*/
                        to = sdRec.timeout;
                }
            }
        }
        if (serverTimeout < to)
            to = serverTimeout;
        if (utmpTimeout < to)
            to = utmpTimeout;
        if (to == TO_INF) {
            tvp = 0;
        } else {
            to -= now;
            if (to < 0)
                to = 0;
            tv.tv_sec = to;
            tv.tv_usec = 0;
            tvp = &tv;
        }
        reads = wellKnownSocketsMask;
        nready = select(wellKnownSocketsMax + 1, &reads, 0, 0, tvp);
        debug("select returns %d\n", nready);
        updateNow();
#ifdef NEED_ENTROPY
        addTimerEntropy();
#endif
        if (now >= serverTimeout) {
            serverTimeout = TO_INF;
            startServerTimeout();
        }
        if (now >= utmpTimeout) {
            utmpTimeout = TO_INF;
            checkUtmp();
        }
        if (nready > 0) {
            /*
             * we restart after the first handled fd, as
             * a) it makes things simpler
             * b) the probability that multiple fds trigger at once is
             *    ridiculously small. we handle it in the next iteration.
             */
            /* XXX a cleaner solution would be a callback mechanism */
            if (FD_ISSET(signalFds[0], &reads)) {
                if (read(signalFds[0], &buf, 1) != 1)
                    logPanic("Signal notification pipe broken.\n");
                switch (buf) {
                case SIGTERM:
                case SIGINT:
                    debug("shutting down entire manager\n");
                    stoppen(True);
                    break;
                case SIGHUP:
                    logInfo("Rescanning all config files\n");
                    forEachDisplay(markDisplay);
                    rescanConfigs(True);
                    break;
                case SIGCHLD:
                    reapChildren();
                    if (!stopping && autoRescan)
                        rescanConfigs(False);
                    break;
                case SIGUSR1:
                    if (startingServer && startingServer->serverStatus == starting)
                        startServerSuccess();
                    break;
                }
                continue;
            }
#ifdef XDMCP
            if (processListenSockets(&reads))
                continue;
#endif
            if (handleCtrl(&reads, 0))
                continue;
            /* Must be last (because of the breaks)! */
          again:
            for (d = displays; d; d = d->next) {
                if (handleCtrl(&reads, d))
                    goto again;
                if (d->pipe.fd.r >= 0 && FD_ISSET(d->pipe.fd.r, &reads)) {
                    processDPipe(d);
                    break;
                }
                if (d->gpipe.fd.r >= 0 && FD_ISSET(d->gpipe.fd.r, &reads)) {
                    processGPipe(d);
                    break;
                }
            }
        }
    }
}

static void
checkDisplayStatus(struct display *d)
{
    if ((d->displayType & d_origin) == dFromFile && !d->stillThere)
        stopDisplay(d);
    else if (d->status == notRunning)
        if (loadDisplayResources(d) < 0) {
            logError("Unable to read configuration for display %s; "
                     "stopping it.\n", d->name);
            stopDisplay(d);
            return;
        }
}

static void
kickDisplay(struct display *d)
{
    if (d->status == notRunning)
        startDisplay(d);
    if (d->serverStatus == awaiting && !startingServer)
        startServer(d);
}

#ifdef HAVE_VTS
static int activeVTs;

static int
getBusyVTs(void)
{
    if (activeVTs == -1) {
#if defined(__linux__)
        struct vt_stat vtstat;
        int con;

        vtstat.v_state = 0;
        if ((con = open("/dev/console", O_RDONLY)) >= 0) {
            ioctl(con, VT_GETSTATE, &vtstat);
            close(con);
        }
        activeVTs = vtstat.v_state;
#elif defined(__FreeBSD_kernel__)
        struct xtty *ttys;
        size_t s, i, firstvt;
        struct stat st;

        activeVTs = 0;
        firstvt = ~0;
        /* We need rdev of the first tty */
        if (stat("/dev/ttyv0", &st))
            firstvt = 0; /* If stat fails, 0 should be safe default */

        if (!sysctlbyname("kern.ttys", NULL, &s, NULL, 0)) {
            ttys = (struct xtty *) malloc(s);
            sysctlbyname("kern.ttys", ttys, &s, NULL, 0);
            for (i = 0; (i < s / sizeof(struct xtty)) &&
                (i < sizeof(activeVTs) * 8); i++)
            {
                if (firstvt == ~0 && st.st_rdev == ttys[i].xt_dev)
                    firstvt = i;
                if (i >= firstvt)
                    activeVTs |= !!(ttys[i].xt_flags & TF_OPENED) << (i - firstvt);
            }
        }
#endif
    }
    return activeVTs;
}

static void
allocateVT(struct display *d)
{
    struct display *cd;
    int i, tvt, volun;

    if ((d->displayType & d_location) == dLocal &&
        d->status == notRunning && !d->serverVT && d->reqSrvVT >= 0)
    {
        if (d->reqSrvVT && d->reqSrvVT < 16) {
            d->serverVT = d->reqSrvVT;
        } else {
            for (i = tvt = 0;;) {
                if (serverVTs[i]) {
                    tvt = atoi(serverVTs[i++]);
                    volun = False;
                    if (tvt < 0) {
                        tvt = -tvt;
                        volun = True;
                    }
                    if (!tvt || tvt >= 16)
                        continue;
                } else {
                    if (++tvt >= 16)
                        break;
                    volun = True;
                }
                for (cd = displays; cd; cd = cd->next) {
                    if (cd->reqSrvVT == tvt && /* protect from lusers */
                            (cd->status != zombie || cd->zstatus != DS_REMOVE))
                        goto next;
                    if (cd->serverVT == tvt) {
                        if (cd->status != zombie || cd->zstatus == DS_REMOTE)
                            goto next;
                        if (!cd->follower) {
                            d->serverVT = -1;
                            cd->follower = d;
                            return;
                        }
                    }
                }
                if (!volun || !((1 << tvt) & getBusyVTs())) {
                    d->serverVT = tvt;
                    return;
                }
          next: ;
            }
        }
    }
}
#endif

static void
startDisplays(void)
{
    forEachDisplay(checkDisplayStatus);
    closeGetter();
#ifdef HAVE_VTS
    activeVTs = -1;
    forEachDisplayRev(allocateVT);
#endif
    forEachDisplay(kickDisplay);
}

static void
startDisplay(struct display *d)
{
    if (stopping) {
        debug("stopping display %s because shutdown is scheduled\n", d->name);
        stopDisplay(d);
        return;
    }

#ifdef HAVE_VTS
    if (d->serverVT < 0)
        return;
#endif

    d->status = running;
    if ((d->displayType & d_location) == dLocal) {
        debug("startDisplay %s\n", d->name);
        /* don't bother pinging local displays; we'll
         * certainly notice when they exit
         */
        d->pingInterval = 0;
        if (d->authorize) {
            setLocalAuthorization(d);
            /*
             * reset the server after writing the authorization information
             * to make it read the file (for compatibility with old
             * servers which read auth file only on reset instead of
             * at first connection)
             */
            if (d->serverPid != -1 && d->resetForAuth)
                kill(d->serverPid, SIGHUP);
        }
        if (d->serverPid == -1) {
            d->serverStatus = awaiting;
            return;
        }
    } else {
        debug("startDisplay %s, try %d\n", d->name, d->startTries + 1);
        /* this will only happen when using XDMCP */
        if (d->authorizations)
            saveServerAuthorizations(d, d->authorizations, d->authNum);
    }
    startDisplayP2(d);
}

void
startDisplayP2(struct display *d)
{
    char *cname, *cgname;

    openCtrl(d);
    debug("forking session\n");
    ASPrintf(&cname, "sub-daemon for display %s", d->name);
    ASPrintf(&cgname, "greeter for display %s", d->name);
    switch (gFork(&d->pipe, "master daemon", cname,
                  &d->gpipe, cgname, 0, &d->pid)) {
    case 0:
        td = d;
#ifndef NOXDMTITLE
        setproctitle("%s", d->name);
#endif
        ASPrintf(&prog, "%s: %s", prog, d->name);
        reInitErrorLog();
        if (debugLevel & DEBUG_WSESS)
            sleep(100);
        mstrtalk.pipe = &d->pipe;
        (void)Signal(SIGPIPE, SIG_IGN);
        setAuthorization(d);
        waitForServer(d);
        if ((d->displayType & d_location) == dLocal) {
            gSet(&mstrtalk);
            if (Setjmp(mstrtalk.errjmp))
                exit(EX_UNMANAGE_DPY);
            gSendInt(D_XConnOk);
        }
        manageSession();
        /* NOTREACHED */
    case -1:
        closeCtrl(d);
        d->status = notRunning;
        break;
    default:
        debug("forked session, pid %d\n", d->pid);

        /* (void) fcntl (d->pipe.fd.r, F_SETFL, O_NONBLOCK); */
        /* (void) fcntl (d->gpipe.fd.r, F_SETFL, O_NONBLOCK); */
        registerInput(d->pipe.fd.r);
        registerInput(d->gpipe.fd.r);

        d->hstent->lock = d->hstent->rLogin = d->hstent->goodExit =
            d->sdRec.how = 0;
        d->lastStart = now;
        break;
    }
}

/*
 * transition from running to zombie, textmode, reserve or deleted
 */

static void
rStopDisplay(struct display *d, int endState)
{
    debug("stopping display %s to state %d\n", d->name, endState);
    abortStartServer(d);
    if (d->serverPid != -1 || d->pid != -1) {
        if (d->pid != -1)
            terminateProcess(d->pid, SIGTERM);
        if (d->serverPid != -1)
            terminateProcess(d->serverPid, SIGTERM);
        d->status = zombie;
        d->zstatus = endState & DS_MASK;
        debug(" zombiefied\n");
    } else if (endState == DS_TEXTMODE) {
#ifdef HAVE_VTS
        d->status = textMode;
        checkTTYMode();
    } else if (endState == (DS_TEXTMODE | DS_SCHEDULE)) {
        d->status = textMode;
#else
        switchToTTY(d);
#endif
    } else if (endState == DS_RESERVE) {
        d->status = reserve;
        d->hstent->lastExit = 0;
#ifdef XDMCP
    } else if (endState == DS_REMOTE) {
        startRemoteLogin(d);
#endif
    } else {
#ifndef HAVE_VTS
        switchToX(d);
#endif
        removeDisplay(d);
    }
}

void
stopDisplay(struct display *d)
{
    rStopDisplay(d, DS_REMOVE);
}

static void
exitDisplay(struct display *d, int endState, int serverCmd, int goodExit)
{
    struct disphist *he;

    if (d->status == raiser) {
        serverCmd = XS_KEEP;
        goodExit = True;
    }

    debug("exitDisplay %s, "
          "endState = %d, serverCmd = %d, GoodExit = %d\n",
          d->name, endState, serverCmd, goodExit);

    sessionDone(d);
    he = d->hstent;
    he->lastExit = now;
    he->goodExit = goodExit;
    if (sdRec.how && sdRec.start == TO_INF)
        endState = DS_REMOVE;
    if (d->status == zombie) {
        rStopDisplay(d, d->zstatus);
    } else {
        if (stopping) {
            stopDisplay(d);
            return;
        }
        if (endState != DS_RESTART ||
            (d->displayType & d_lifetime) == dTransient)
        {
            rStopDisplay(d, endState);
        } else {
            if (serverCmd == XS_RETRY) {
                if ((d->displayType & d_location) == dLocal) {
                    if (he->lastExit - d->lastStart < 120) {
                        logError("Unable to fire up local display %s;"
                                 " disabling.\n", d->name);
                        stopDisplay(d);
                        return;
                    }
                } else {
                    if (++d->startTries > d->startAttempts) {
                        logError("Disabling foreign display %s"
                                 " (too many attempts)\n", d->name);
                        stopDisplay(d);
                        return;
                    }
                }
            } else {
                d->startTries = 0;
            }
            if (d->serverPid != -1 &&
                (serverCmd != XS_KEEP || d->terminateServer))
            {
                debug("killing X server for %s\n", d->name);
                terminateProcess(d->serverPid, SIGTERM);
                d->status = phoenix;
            } else {
                d->status = notRunning;
            }
        }
    }
}


static int pidFd;
static FILE *pidFilePtr;

static int
storePid(void)
{
    int oldpid;

    if (pidFile[0] != '\0') {
        pidFd = open(pidFile, O_RDWR);
        if (pidFd == -1 && errno == ENOENT)
            pidFd = open(pidFile, O_RDWR | O_CREAT, 0666);
        if (pidFd == -1 || !(pidFilePtr = fdopen(pidFd, "r+"))) {
            logError("process-id file %s cannot be opened\n",
                     pidFile);
            return -1;
        }
        if (fscanf(pidFilePtr, "%d\n", &oldpid) != 1)
            oldpid = -1;
        fseek(pidFilePtr, 0l, 0);
        if (lockPidFile) {
#ifdef F_SETLK
# ifndef SEEK_SET
#  define SEEK_SET 0
# endif
            struct flock lock_data;
            lock_data.l_type = F_WRLCK;
            lock_data.l_whence = SEEK_SET;
            lock_data.l_start = lock_data.l_len = 0;
            if (fcntl(pidFd, F_SETLK, &lock_data) == -1) {
                if (errno == EAGAIN)
                    return oldpid;
                else
                    return -1;
            }
#else
# ifdef LOCK_EX
            if (flock(pidFd, LOCK_EX | LOCK_NB) == -1) {
                if (errno == EWOULDBLOCK)
                    return oldpid;
                else
                    return -1;
            }
# else
            if (lockf(pidFd, F_TLOCK, 0) == -1) {
                if (errno == EACCES)
                    return oldpid;
                else
                    return -1;
            }
# endif
#endif
        }
        fprintf(pidFilePtr, "%ld\n", (long)getpid());
        if (fflush(pidFilePtr) == EOF)
            logError("Cannot write PID file %s: %m", pidFile);
        registerCloseOnFork(pidFd);
    }
    return 0;
}

#if 0
void
UnlockPidFile(void)
{
    if (lockPidFile)
# ifdef F_SETLK
    {
        struct flock lock_data;
        lock_data.l_type = F_UNLCK;
        lock_data.l_whence = SEEK_SET;
        lock_data.l_start = lock_data.l_len = 0;
        (void)fcntl(pidFd, F_SETLK, &lock_data);
    }
# else
#  ifdef F_ULOCK
        lockf(pidFd, F_ULOCK, 0);
#  else
        flock(pidFd, LOCK_UN);
#  endif
# endif
    close(pidFd);
    fclose(pidFilePtr);
}
#endif

#if !defined(HAVE_SETPROCTITLE) && !defined(NOXDMTITLE)
void
setproctitle(const char *fmt, ...)
{
    const char *name;
    char *oname;
    char *p = title;
    int left = titleLen;
    va_list args;

    va_start(args, fmt);
    VASPrintf(&oname, fmt, args);
    va_end(args);

    if ((name = oname)) {
        *p++ = '-';
        --left;
        while (*name && left > 0) {
            *p++ = *name++;
            --left;
        }
        while (left > 0) {
            *p++ = '\0';
            --left;
        }

        free(oname);
    }
}
#endif