Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*
 * Copyright (c) 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "telnetd.h"

RCSID("$Id$");

#if defined(_CRAY) || (defined(__hpux) && !defined(HAVE_UTMPX_H))
# define PARENT_DOES_UTMP
#endif

#ifdef HAVE_UTMP_H
#include <utmp.h>
#endif

#ifdef HAVE_UTMPX_H
#include <utmpx.h>
#endif

#ifdef HAVE_UTMPX_H
struct	utmpx wtmp;
#elif defined(HAVE_UTMP_H)
struct	utmp wtmp;
#endif /* HAVE_UTMPX_H */

#ifdef HAVE_STRUCT_UTMP_UT_HOST
int	utmp_len = sizeof(wtmp.ut_host);
#else
int	utmp_len = MaxHostNameLen;
#endif

#ifndef UTMP_FILE
#ifdef _PATH_UTMP
#define UTMP_FILE _PATH_UTMP
#else
#define UTMP_FILE "/etc/utmp"
#endif
#endif

/* really, mac os uses wtmpx (or asl) */
#ifdef __APPLE__
#undef _PATH_WTMP
#endif

#if !defined(WTMP_FILE) && defined(_PATH_WTMP)
#define WTMP_FILE _PATH_WTMP
#endif

#ifndef PARENT_DOES_UTMP
#ifdef WTMP_FILE
char	wtmpf[] = WTMP_FILE;
#else
char	wtmpf[]	= "/usr/adm/wtmp";
#endif
char	utmpf[] = UTMP_FILE;
#else /* PARENT_DOES_UTMP */
#ifdef WTMP_FILE
char	wtmpf[] = WTMP_FILE;
#else
char	wtmpf[]	= "/etc/wtmp";
#endif
#endif /* PARENT_DOES_UTMP */

#ifdef HAVE_TMPDIR_H
#include <tmpdir.h>
#endif	/* CRAY */

#if !(defined(__sgi) || defined(__linux) || defined(_AIX)) && defined(HAVE_SYS_TTY)
#include <sys/tty.h>
#endif
#ifdef	t_erase
#undef	t_erase
#undef	t_kill
#undef	t_intrc
#undef	t_quitc
#undef	t_startc
#undef	t_stopc
#undef	t_eofc
#undef	t_brkc
#undef	t_suspc
#undef	t_dsuspc
#undef	t_rprntc
#undef	t_flushc
#undef	t_werasc
#undef	t_lnextc
#endif

#ifdef HAVE_TERMIOS_H
#include <termios.h>
#else
#ifdef HAVE_TERMIO_H
#include <termio.h>
#endif
#endif

#ifdef HAVE_UTIL_H
#include <util.h>
#endif
#ifdef HAVE_LIBUTIL_H
#include <libutil.h>
#endif

# ifndef	TCSANOW
#  ifdef TCSETS
#   define	TCSANOW		TCSETS
#   define	TCSADRAIN	TCSETSW
#   define	tcgetattr(f, t)	ioctl(f, TCGETS, (char *)t)
#  else
#   ifdef TCSETA
#    define	TCSANOW		TCSETA
#    define	TCSADRAIN	TCSETAW
#    define	tcgetattr(f, t)	ioctl(f, TCGETA, (char *)t)
#   else
#    define	TCSANOW		TIOCSETA
#    define	TCSADRAIN	TIOCSETAW
#    define	tcgetattr(f, t)	ioctl(f, TIOCGETA, (char *)t)
#   endif
#  endif
#  define	tcsetattr(f, a, t)	ioctl(f, a, t)
#  define	cfsetospeed(tp, val)	(tp)->c_cflag &= ~CBAUD; \
(tp)->c_cflag |= (val)
#  define	cfgetospeed(tp)		((tp)->c_cflag & CBAUD)
#  ifdef CIBAUD
#   define	cfsetispeed(tp, val)	(tp)->c_cflag &= ~CIBAUD; \
     (tp)->c_cflag |= ((val)<<IBSHIFT)
#   define	cfgetispeed(tp)		(((tp)->c_cflag & CIBAUD)>>IBSHIFT)
#  else
#   define	cfsetispeed(tp, val)	(tp)->c_cflag &= ~CBAUD; \
     (tp)->c_cflag |= (val)
#   define	cfgetispeed(tp)		((tp)->c_cflag & CBAUD)
#  endif
# endif /* TCSANOW */
     struct termios termbuf, termbuf2;	/* pty control structure */
# ifdef  STREAMSPTY
     static int ttyfd = -1;
     int really_stream = 0;
# else
#define really_stream 0
# endif

     const char *new_login = _PATH_LOGIN;

/*
 * init_termbuf()
 * copy_termbuf(cp)
 * set_termbuf()
 *
 * These three routines are used to get and set the "termbuf" structure
 * to and from the kernel.  init_termbuf() gets the current settings.
 * copy_termbuf() hands in a new "termbuf" to write to the kernel, and
 * set_termbuf() writes the structure into the kernel.
 */

     void
     init_termbuf(void)
{
# ifdef  STREAMSPTY
    if (really_stream)
	tcgetattr(ttyfd, &termbuf);
    else
# endif
	tcgetattr(ourpty, &termbuf);
    termbuf2 = termbuf;
}

void
set_termbuf(void)
{
    /*
     * Only make the necessary changes.
	 */
    if (memcmp(&termbuf, &termbuf2, sizeof(termbuf))) {
# ifdef  STREAMSPTY
	if (really_stream)
	    tcsetattr(ttyfd, TCSANOW, &termbuf);
	else
# endif
	    tcsetattr(ourpty, TCSANOW, &termbuf);
    }
}


/*
 * spcset(func, valp, valpp)
 *
 * This function takes various special characters (func), and
 * sets *valp to the current value of that character, and
 * *valpp to point to where in the "termbuf" structure that
 * value is kept.
 *
 * It returns the SLC_ level of support for this function.
 */


int
spcset(int func, cc_t *valp, cc_t **valpp)
{

#define	setval(a, b)	*valp = termbuf.c_cc[a]; \
    *valpp = &termbuf.c_cc[a]; \
				   return(b);
#define	defval(a) *valp = ((cc_t)a); *valpp = (cc_t *)0; return(SLC_DEFAULT);

    switch(func) {
    case SLC_EOF:
	setval(VEOF, SLC_VARIABLE);
    case SLC_EC:
	setval(VERASE, SLC_VARIABLE);
    case SLC_EL:
	setval(VKILL, SLC_VARIABLE);
    case SLC_IP:
	setval(VINTR, SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
    case SLC_ABORT:
	setval(VQUIT, SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
    case SLC_XON:
#ifdef	VSTART
	setval(VSTART, SLC_VARIABLE);
#else
	defval(0x13);
#endif
    case SLC_XOFF:
#ifdef	VSTOP
	setval(VSTOP, SLC_VARIABLE);
#else
	defval(0x11);
#endif
    case SLC_EW:
#ifdef	VWERASE
	setval(VWERASE, SLC_VARIABLE);
#else
	defval(0);
#endif
    case SLC_RP:
#ifdef	VREPRINT
	setval(VREPRINT, SLC_VARIABLE);
#else
	defval(0);
#endif
    case SLC_LNEXT:
#ifdef	VLNEXT
	setval(VLNEXT, SLC_VARIABLE);
#else
	defval(0);
#endif
    case SLC_AO:
#if	!defined(VDISCARD) && defined(VFLUSHO)
# define VDISCARD VFLUSHO
#endif
#ifdef	VDISCARD
	setval(VDISCARD, SLC_VARIABLE|SLC_FLUSHOUT);
#else
	defval(0);
#endif
    case SLC_SUSP:
#ifdef	VSUSP
	setval(VSUSP, SLC_VARIABLE|SLC_FLUSHIN);
#else
	defval(0);
#endif
#ifdef	VEOL
    case SLC_FORW1:
	setval(VEOL, SLC_VARIABLE);
#endif
#ifdef	VEOL2
    case SLC_FORW2:
	setval(VEOL2, SLC_VARIABLE);
#endif
    case SLC_AYT:
#ifdef	VSTATUS
	setval(VSTATUS, SLC_VARIABLE);
#else
	defval(0);
#endif

    case SLC_BRK:
    case SLC_SYNCH:
    case SLC_EOR:
	defval(0);

    default:
	*valp = 0;
	*valpp = 0;
	return(SLC_NOSUPPORT);
    }
}

#ifdef _CRAY
/*
 * getnpty()
 *
 * Return the number of pty's configured into the system.
 */
int
getnpty()
{
#ifdef _SC_CRAY_NPTY
    int numptys;

    if ((numptys = sysconf(_SC_CRAY_NPTY)) != -1)
	return numptys;
    else
#endif /* _SC_CRAY_NPTY */
	return 128;
}
#endif /* CRAY */

/*
 * getpty()
 *
 * Allocate a pty.  As a side effect, the external character
 * array "line" contains the name of the slave side.
 *
 * Returns the file descriptor of the opened pty.
 */

static int ptyslavefd = -1;

static char Xline[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
char *line = Xline;

#ifdef	_CRAY
char myline[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
#endif	/* CRAY */

#if !defined(HAVE_PTSNAME) && defined(STREAMSPTY)
static char *ptsname(int fd)
{
#ifdef HAVE_TTYNAME
    return ttyname(fd);
#else
    return NULL;
#endif
}
#endif

int getpty(int *ptynum)
{
#if defined(HAVE_OPENPTY) || defined(__linux) || defined(__osf__) /* XXX */
    {
	int master;
	int slave;
	if(openpty(&master, &slave, line, 0, 0) == 0){
	    ptyslavefd = slave;
	    return master;
	}
    }
#endif /* HAVE_OPENPTY .... */
#ifdef HAVE__GETPTY
    {
	int master;
	char *p;
	p = _getpty(&master, O_RDWR, 0600, 1);
	if(p == NULL)
	    return -1;
	strlcpy(line, p, sizeof(Xline));
	return master;
    }
#endif

#ifdef	STREAMSPTY
    {
	char *clone[] = { "/dev/ptc", "/dev/ptmx", "/dev/ptm",
			  "/dev/ptym/clone", 0 };

	char **q;
	int p;
	for(q=clone; *q; q++){
	    p=open(*q, O_RDWR);
	    if(p >= 0){
#ifdef HAVE_GRANTPT
		grantpt(p);
#endif
#ifdef HAVE_UNLOCKPT
		unlockpt(p);
#endif
		strlcpy(line, ptsname(p), sizeof(Xline));
		really_stream = 1;
		return p;
	    }
	}
    }
#endif /* STREAMSPTY */
#ifndef _CRAY
    {
	int p;
	char *cp, *p1, *p2;
	int i;

#ifndef	__hpux
	snprintf(line, sizeof(Xline), "/dev/ptyXX");
	p1 = &line[8];
	p2 = &line[9];
#else
	snprintf(line, sizeof(Xline), "/dev/ptym/ptyXX");
	p1 = &line[13];
	p2 = &line[14];
#endif


	for (cp = "pqrstuvwxyzPQRST"; *cp; cp++) {
	    struct stat stb;

	    *p1 = *cp;
	    *p2 = '0';
	    /*
	     * This stat() check is just to keep us from
	     * looping through all 256 combinations if there
	     * aren't that many ptys available.
	     */
	    if (stat(line, &stb) < 0)
		break;
	    for (i = 0; i < 16; i++) {
		*p2 = "0123456789abcdef"[i];
		p = open(line, O_RDWR);
		if (p > 0) {
#if SunOS == 40
		    int dummy;
#endif

#ifndef	__hpux
		    line[5] = 't';
#else
		    for (p1 = &line[8]; *p1; p1++)
			*p1 = *(p1+1);
		    line[9] = 't';
#endif
		    chown(line, 0, 0);
		    chmod(line, 0600);
#if SunOS == 40
		    if (ioctl(p, TIOCGPGRP, &dummy) == 0
			|| errno != EIO) {
			chmod(line, 0666);
			close(p);
			line[5] = 'p';
		    } else
#endif /* SunOS == 40 */
			return(p);
		}
	    }
	}
    }
#else	/* CRAY */
    {
	extern lowpty, highpty;
	struct stat sb;
	int p;

	for (*ptynum = lowpty; *ptynum <= highpty; (*ptynum)++) {
	    snprintf(myline, sizeof(myline), "/dev/pty/%03d", *ptynum);
	    p = open(myline, 2);
	    if (p < 0)
		continue;
	    snprintf(line, sizeof(Xline), "/dev/ttyp%03d", *ptynum);
	    /*
	     * Here are some shenanigans to make sure that there
	     * are no listeners lurking on the line.
	     */
	    if(stat(line, &sb) < 0) {
		close(p);
		continue;
	    }
	    if(sb.st_uid || sb.st_gid || sb.st_mode != 0600) {
		chown(line, 0, 0);
		chmod(line, 0600);
		close(p);
		p = open(myline, 2);
		if (p < 0)
		    continue;
	    }
	    /*
	     * Now it should be safe...check for accessability.
	     */
	    if (access(line, 6) == 0)
		return(p);
	    else {
		/* no tty side to pty so skip it */
		close(p);
	    }
	}
    }
#endif	/* CRAY */
    return(-1);
}


int
tty_isecho(void)
{
    return (termbuf.c_lflag & ECHO);
}

int
tty_flowmode(void)
{
    return((termbuf.c_iflag & IXON) ? 1 : 0);
}

int
tty_restartany(void)
{
    return((termbuf.c_iflag & IXANY) ? 1 : 0);
}

void
tty_setecho(int on)
{
    if (on)
	termbuf.c_lflag |= ECHO;
    else
	termbuf.c_lflag &= ~ECHO;
}

int
tty_israw(void)
{
    return(!(termbuf.c_lflag & ICANON));
}

void
tty_binaryin(int on)
{
    if (on) {
	termbuf.c_iflag &= ~ISTRIP;
    } else {
	termbuf.c_iflag |= ISTRIP;
    }
}

void
tty_binaryout(int on)
{
    if (on) {
	termbuf.c_cflag &= ~(CSIZE|PARENB);
	termbuf.c_cflag |= CS8;
	termbuf.c_oflag &= ~OPOST;
    } else {
	termbuf.c_cflag &= ~CSIZE;
	termbuf.c_cflag |= CS7|PARENB;
	termbuf.c_oflag |= OPOST;
    }
}

int
tty_isbinaryin(void)
{
    return(!(termbuf.c_iflag & ISTRIP));
}

int
tty_isbinaryout(void)
{
    return(!(termbuf.c_oflag&OPOST));
}


int
tty_issofttab(void)
{
# ifdef	OXTABS
    return (termbuf.c_oflag & OXTABS);
# endif
# ifdef	TABDLY
    return ((termbuf.c_oflag & TABDLY) == TAB3);
# endif
}

void
tty_setsofttab(int on)
{
    if (on) {
# ifdef	OXTABS
	termbuf.c_oflag |= OXTABS;
# endif
# ifdef	TABDLY
	termbuf.c_oflag &= ~TABDLY;
	termbuf.c_oflag |= TAB3;
# endif
    } else {
# ifdef	OXTABS
	termbuf.c_oflag &= ~OXTABS;
# endif
# ifdef	TABDLY
	termbuf.c_oflag &= ~TABDLY;
	termbuf.c_oflag |= TAB0;
# endif
    }
}

int
tty_islitecho(void)
{
# ifdef	ECHOCTL
    return (!(termbuf.c_lflag & ECHOCTL));
# endif
# ifdef	TCTLECH
    return (!(termbuf.c_lflag & TCTLECH));
# endif
# if	!defined(ECHOCTL) && !defined(TCTLECH)
    return (0);	/* assumes ctl chars are echoed '^x' */
# endif
}

void
tty_setlitecho(int on)
{
# ifdef	ECHOCTL
    if (on)
	termbuf.c_lflag &= ~ECHOCTL;
    else
	termbuf.c_lflag |= ECHOCTL;
# endif
# ifdef	TCTLECH
    if (on)
	termbuf.c_lflag &= ~TCTLECH;
    else
	termbuf.c_lflag |= TCTLECH;
# endif
}

int
tty_iscrnl(void)
{
    return (termbuf.c_iflag & ICRNL);
}

/*
 * Try to guess whether speeds are "encoded" (4.2BSD) or just numeric (4.4BSD).
 */
#if B4800 != 4800
#define	DECODE_BAUD
#endif

#ifdef	DECODE_BAUD

/*
 * A table of available terminal speeds
 */
struct termspeeds {
    int	speed;
    int	value;
} termspeeds[] = {
    { 0,      B0 },      { 50,    B50 },    { 75,     B75 },
    { 110,    B110 },    { 134,   B134 },   { 150,    B150 },
    { 200,    B200 },    { 300,   B300 },   { 600,    B600 },
    { 1200,   B1200 },   { 1800,  B1800 },  { 2400,   B2400 },
    { 4800,   B4800 },
#ifdef	B7200
    { 7200,  B7200 },
#endif
    { 9600,   B9600 },
#ifdef	B14400
    { 14400,  B14400 },
#endif
#ifdef	B19200
    { 19200,  B19200 },
#endif
#ifdef	B28800
    { 28800,  B28800 },
#endif
#ifdef	B38400
    { 38400,  B38400 },
#endif
#ifdef	B57600
    { 57600,  B57600 },
#endif
#ifdef	B115200
    { 115200, B115200 },
#endif
#ifdef	B230400
    { 230400, B230400 },
#endif
    { -1,     0 }
};
#endif	/* DECODE_BUAD */

void
tty_tspeed(int val)
{
#ifdef	DECODE_BAUD
    struct termspeeds *tp;

    for (tp = termspeeds; (tp->speed != -1) && (val > tp->speed); tp++)
	;
    if (tp->speed == -1)	/* back up to last valid value */
	--tp;
    cfsetospeed(&termbuf, tp->value);
#else	/* DECODE_BUAD */
    cfsetospeed(&termbuf, val);
#endif	/* DECODE_BUAD */
}

void
tty_rspeed(int val)
{
#ifdef	DECODE_BAUD
    struct termspeeds *tp;

    for (tp = termspeeds; (tp->speed != -1) && (val > tp->speed); tp++)
	;
    if (tp->speed == -1)	/* back up to last valid value */
	--tp;
    cfsetispeed(&termbuf, tp->value);
#else	/* DECODE_BAUD */
    cfsetispeed(&termbuf, val);
#endif	/* DECODE_BAUD */
}

#ifdef PARENT_DOES_UTMP
extern	struct utmp wtmp;
extern char wtmpf[];

extern void utmp_sig_init (void);
extern void utmp_sig_reset (void);
extern void utmp_sig_wait (void);
extern void utmp_sig_notify (int);
# endif /* PARENT_DOES_UTMP */

#ifdef STREAMSPTY

/* I_FIND seems to live a life of its own */
static int my_find(int fd, char *module)
{
#if defined(I_FIND) && defined(I_LIST)
    static int flag;
    static struct str_list sl;
    int n;
    int i;

    if(!flag){
	n = ioctl(fd, I_LIST, 0);
	if(n < 0){
	    perror("ioctl(fd, I_LIST, 0)");
	    return -1;
	}
	sl.sl_modlist=(struct str_mlist*)malloc(n * sizeof(struct str_mlist));
	sl.sl_nmods = n;
	n = ioctl(fd, I_LIST, &sl);
	if(n < 0){
	    perror("ioctl(fd, I_LIST, n)");
	    return -1;
	}
	flag = 1;
    }

    for(i=0; i<sl.sl_nmods; i++)
	if(!strcmp(sl.sl_modlist[i].l_name, module))
	    return 1;
#endif
    return 0;
}

static void maybe_push_modules(int fd, char **modules)
{
    char **p;
    int err;

    for(p=modules; *p; p++){
	err = my_find(fd, *p);
	if(err == 1)
	    break;
	if(err < 0 && errno != EINVAL)
	    fatalperror(net, "my_find()");
	/* module not pushed or does not exist */
    }
    /* p points to null or to an already pushed module, now push all
       modules before this one */

    for(p--; p >= modules; p--){
	err = ioctl(fd, I_PUSH, *p);
	if(err < 0 && errno != EINVAL)
	    fatalperror(net, "I_PUSH");
    }
}
#endif

/*
 * getptyslave()
 *
 * Open the slave side of the pty, and do any initialization
 * that is necessary.  The return value is a file descriptor
 * for the slave side.
 */
void getptyslave(void)
{
    int t = -1;

    struct winsize ws;
    /*
     * Opening the slave side may cause initilization of the
     * kernel tty structure.  We need remember the state of
     * 	if linemode was turned on
     *	terminal window size
     *	terminal speed
     * so that we can re-set them if we need to.
     */


    /*
     * Make sure that we don't have a controlling tty, and
     * that we are the session (process group) leader.
     */

#ifdef HAVE_SETSID
    if(setsid()<0)
	fatalperror(net, "setsid()");
#else
# ifdef	TIOCNOTTY
    t = open(_PATH_TTY, O_RDWR);
    if (t >= 0) {
	ioctl(t, TIOCNOTTY, (char *)0);
	close(t);
    }
# endif
#endif

# ifdef PARENT_DOES_UTMP
    /*
     * Wait for our parent to get the utmp stuff to get done.
     */
    utmp_sig_wait();
# endif

    t = cleanopen(line);
    if (t < 0)
	fatalperror(net, line);

#ifdef  STREAMSPTY
    ttyfd = t;


    /*
     * Not all systems have (or need) modules ttcompat and pckt so
     * don't flag it as a fatal error if they don't exist.
     */

    if (really_stream)
	{
	    /* these are the streams modules that we want pushed. note
	       that they are in reverse order, ptem will be pushed
	       first. maybe_push_modules() will try to push all modules
	       before the first one that isn't already pushed. i.e if
	       ldterm is pushed, only ttcompat will be attempted.

	       all this is because we don't know which modules are
	       available, and we don't know which modules are already
	       pushed (via autopush, for instance).

	       */

	    char *ttymodules[] = { "ttcompat", "ldterm", "ptem", NULL };
	    char *ptymodules[] = { "pckt", NULL };

	    maybe_push_modules(t, ttymodules);
	    maybe_push_modules(ourpty, ptymodules);
	}
#endif
    /*
     * set up the tty modes as we like them to be.
     */
    init_termbuf();
# ifdef	TIOCSWINSZ
    if (def_row || def_col) {
	memset(&ws, 0, sizeof(ws));
	ws.ws_col = def_col;
	ws.ws_row = def_row;
	ioctl(t, TIOCSWINSZ, (char *)&ws);
    }
# endif

    /*
     * Settings for sgtty based systems
     */

    /*
     * Settings for UNICOS (and HPUX)
     */
# if defined(_CRAY) || defined(__hpux)
    termbuf.c_oflag = OPOST|ONLCR|TAB3;
    termbuf.c_iflag = IGNPAR|ISTRIP|ICRNL|IXON;
    termbuf.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK;
    termbuf.c_cflag = EXTB|HUPCL|CS8;
# endif

    /*
     * Settings for all other termios/termio based
     * systems, other than 4.4BSD.  In 4.4BSD the
     * kernel does the initial terminal setup.
     */
# if !(defined(_CRAY) || defined(__hpux)) && (BSD <= 43)
#  ifndef	OXTABS
#   define OXTABS	0
#  endif
    termbuf.c_lflag |= ECHO;
    termbuf.c_oflag |= ONLCR|OXTABS;
    termbuf.c_iflag |= ICRNL;
    termbuf.c_iflag &= ~IXOFF;
# endif
    tty_rspeed((def_rspeed > 0) ? def_rspeed : 9600);
    tty_tspeed((def_tspeed > 0) ? def_tspeed : 9600);

    /*
     * Set the tty modes, and make this our controlling tty.
     */
    set_termbuf();
    if (login_tty(t) == -1)
	fatalperror(net, "login_tty");
    if (net > 2)
	close(net);
    if (ourpty > 2) {
	close(ourpty);
	ourpty = -1;
    }
}

#ifndef	O_NOCTTY
#define	O_NOCTTY	0
#endif
/*
 * Open the specified slave side of the pty,
 * making sure that we have a clean tty.
 */

int cleanopen(char *line)
{
    int t;

    if (ptyslavefd != -1)
	return ptyslavefd;

#ifdef STREAMSPTY
    if (!really_stream)
#endif
	{
	    /*
	     * Make sure that other people can't open the
	     * slave side of the connection.
	     */
	    chown(line, 0, 0);
	    chmod(line, 0600);
	}

#ifdef HAVE_REVOKE
    revoke(line);
#endif

    t = open(line, O_RDWR|O_NOCTTY);

    if (t < 0)
	return(-1);

    /*
     * Hangup anybody else using this ttyp, then reopen it for
     * ourselves.
     */
# if !(defined(_CRAY) || defined(__hpux)) && (BSD <= 43) && !defined(STREAMSPTY)
    signal(SIGHUP, SIG_IGN);
#ifdef HAVE_VHANGUP
    vhangup();
#else
#endif
    signal(SIGHUP, SIG_DFL);
    t = open(line, O_RDWR|O_NOCTTY);
    if (t < 0)
	return(-1);
# endif
# if	defined(_CRAY) && defined(TCVHUP)
    {
	int i;
	signal(SIGHUP, SIG_IGN);
	ioctl(t, TCVHUP, (char *)0);
	signal(SIGHUP, SIG_DFL);

	i = open(line, O_RDWR);

	if (i < 0)
	    return(-1);
	close(t);
	t = i;
    }
# endif	/* defined(CRAY) && defined(TCVHUP) */
    return(t);
}

#if !defined(BSD4_4)

int login_tty(int t)
{
    /* Dont need to set this as the controlling PTY on steams sockets,
     * don't abort on failure. */
# if defined(TIOCSCTTY) && !defined(__hpux)
    if (ioctl(t, TIOCSCTTY, (char *)0) < 0 && !really_stream)
	fatalperror(net, "ioctl(sctty)");
#  ifdef _CRAY
    /*
     * Close the hard fd to /dev/ttypXXX, and re-open through
     * the indirect /dev/tty interface.
     */
    close(t);
    if ((t = open("/dev/tty", O_RDWR)) < 0)
	fatalperror(net, "open(/dev/tty)");
#  endif
# else
    /*
     * We get our controlling tty assigned as a side-effect
     * of opening up a tty device.  But on BSD based systems,
     * this only happens if our process group is zero.  The
     * setsid() call above may have set our pgrp, so clear
     * it out before opening the tty...
     */
#ifdef HAVE_SETPGID
    setpgid(0, 0);
#else
    setpgrp(0, 0); /* if setpgid isn't available, setpgrp
		      probably takes arguments */
#endif
    close(open(line, O_RDWR));
# endif
    if (t != 0)
	dup2(t, 0);
    if (t != 1)
	dup2(t, 1);
    if (t != 2)
	dup2(t, 2);
    if (t > 2)
	close(t);
    return(0);
}
#endif	/* BSD <= 43 */

/*
 * This comes from ../../bsd/tty.c and should not really be here.
 */

/*
 * Clean the tty name.  Return a pointer to the cleaned version.
 */

static char * clean_ttyname (char *) __attribute__((unused));

static char *
clean_ttyname (char *tty)
{
  char *res = tty;

  if (strncmp (res, _PATH_DEV, strlen(_PATH_DEV)) == 0)
    res += strlen(_PATH_DEV);
  if (strncmp (res, "pty/", 4) == 0)
    res += 4;
  if (strncmp (res, "ptym/", 5) == 0)
    res += 5;
  return res;
}

/*
 * Generate a name usable as an `ut_id', typically without `tty'.
 */

#ifdef HAVE_STRUCT_UTMP_UT_ID
static char *
make_id (char *tty)
{
  char *res = tty;

  if (strncmp (res, "pts/", 4) == 0)
    res += 4;
  if (strncmp (res, "tty", 3) == 0)
    res += 3;
  return res;
}
#endif

/*
 * startslave(host)
 *
 * Given a hostname, do whatever
 * is necessary to startup the login process on the slave side of the pty.
 */

/* ARGSUSED */
void
startslave(const char *host, const char *utmp_host,
	   int autologin, char *autoname)
{
    int i;

#ifdef AUTHENTICATION
    if (!autoname || !autoname[0])
	autologin = 0;

    if (autologin < auth_level) {
	fatal(net, "Authorization failed");
	exit(1);
    }
#endif

    {
	char *tbuf =
	    "\r\n*** Connection not encrypted! "
	    "Communication may be eavesdropped. ***\r\n";
#ifdef ENCRYPTION
	if (!no_warn && (encrypt_output == 0 || decrypt_input == 0))
#endif
	    writenet(tbuf, strlen(tbuf));
    }
# ifdef	PARENT_DOES_UTMP
    utmp_sig_init();
# endif	/* PARENT_DOES_UTMP */

    if ((i = fork()) < 0)
	fatalperror(net, "fork");
    if (i) {
# ifdef PARENT_DOES_UTMP
	/*
	 * Cray parent will create utmp entry for child and send
	 * signal to child to tell when done.  Child waits for signal
	 * before doing anything important.
	 */
	int pid = i;
	void sigjob (int);

	setpgrp();
	utmp_sig_reset();		/* reset handler to default */
	/*
	 * Create utmp entry for child
	 */
	wtmp.ut_time = time(NULL);
	wtmp.ut_type = LOGIN_PROCESS;
	wtmp.ut_pid = pid;
	strncpy(wtmp.ut_user,  "LOGIN", sizeof(wtmp.ut_user));
	strncpy(wtmp.ut_host,  utmp_host, sizeof(wtmp.ut_host));
	strncpy(wtmp.ut_line,  clean_ttyname(line), sizeof(wtmp.ut_line));
#ifdef HAVE_STRUCT_UTMP_UT_ID
	strncpy(wtmp.ut_id, wtmp.ut_line + 3, sizeof(wtmp.ut_id));
#endif

	pututline(&wtmp);
	endutent();
	if ((i = open(wtmpf, O_WRONLY|O_APPEND)) >= 0) {
	    write(i, &wtmp, sizeof(struct utmp));
	    close(i);
	}
#ifdef	_CRAY
	signal(WJSIGNAL, sigjob);
#endif
	utmp_sig_notify(pid);
# endif	/* PARENT_DOES_UTMP */
    } else {
	getptyslave();
#if defined(DCE)
	/* if we authenticated via K5, try and join the PAG */
	kerberos5_dfspag();
#endif
	start_login(host, autologin, autoname);
	/*NOTREACHED*/
    }
}

char	*envinit[3];
#if !HAVE_DECL_ENVIRON
extern char **environ;
#endif

void
init_env(void)
{
    char **envp;

    envp = envinit;
    if ((*envp = getenv("TZ")))
	*envp++ -= 3;
#if defined(_CRAY) || defined(__hpux)
    else
	*envp++ = "TZ=GMT0";
#endif
    *envp = 0;
    environ = envinit;
}

/*
 * scrub_env()
 *
 * We only accept the environment variables listed below.
 */

static void
scrub_env(void)
{
    static const char *reject[] = {
	"TERMCAP=/",
	NULL
    };

    static const char *accept[] = {
	"XAUTH=", "XAUTHORITY=", "DISPLAY=",
	"TERM=",
	"EDITOR=",
	"PAGER=",
	"PRINTER=",
	"LOGNAME=",
	"POSIXLY_CORRECT=",
	"TERMCAP=",
	NULL
    };

    char **cpp, **cpp2;
    const char **p;

    for (cpp2 = cpp = environ; *cpp; cpp++) {
	int reject_it = 0;

	for(p = reject; *p; p++)
	    if(strncmp(*cpp, *p, strlen(*p)) == 0) {
		reject_it = 1;
		break;
	    }
	if (reject_it)
	    continue;

	for(p = accept; *p; p++)
	    if(strncmp(*cpp, *p, strlen(*p)) == 0)
		break;
	if(*p != NULL)
	    *cpp2++ = *cpp;
    }
    *cpp2 = NULL;
}


struct arg_val {
    int size;
    int argc;
    char **argv;
};

static void addarg(struct arg_val*, const char*);

/*
 * start_login(host)
 *
 * Assuming that we are now running as a child processes, this
 * function will turn us into the login process.
 */

void
start_login(const char *host, int autologin, char *name)
{
    struct arg_val argv;
    char *user;
    int save_errno;

#ifdef ENCRYPTION
    encrypt_output = NULL;
    decrypt_input = NULL;
#endif

#ifdef HAVE_UTMPX_H
    {
	int pid = getpid();
	struct utmpx utmpx;
	struct timeval tv;
	char *clean_tty;

	/*
	 * Create utmp entry for child
	 */

	clean_tty = clean_ttyname(line);
	memset(&utmpx, 0, sizeof(utmpx));
	strncpy(utmpx.ut_user,  ".telnet", sizeof(utmpx.ut_user));
	strncpy(utmpx.ut_line,  clean_tty, sizeof(utmpx.ut_line));
#ifdef HAVE_STRUCT_UTMP_UT_ID
	strncpy(utmpx.ut_id, make_id(clean_tty), sizeof(utmpx.ut_id));
#endif
	utmpx.ut_pid = pid;

	utmpx.ut_type = LOGIN_PROCESS;

	gettimeofday (&tv, NULL);
	utmpx.ut_tv.tv_sec = tv.tv_sec;
	utmpx.ut_tv.tv_usec = tv.tv_usec;

	if (pututxline(&utmpx) == NULL)
	    fatal(net, "pututxline failed");
    }
#endif

    scrub_env();

    /*
     * -h : pass on name of host.
     *		WARNING:  -h is accepted by login if and only if
     *			getuid() == 0.
     * -p : don't clobber the environment (so terminal type stays set).
     *
     * -f : force this login, he has already been authenticated
     */

    /* init argv structure */
    argv.size=0;
    argv.argc=0;
    argv.argv=malloc(0); /*so we can call realloc later */
    addarg(&argv, "login");
    addarg(&argv, "-h");
    addarg(&argv, host);
    addarg(&argv, "-p");
    if(name && name[0])
	user = name;
    else
	user = getenv("USER");
#ifdef AUTHENTICATION
    if (auth_level < 0 || autologin != AUTH_VALID) {
	if(!no_warn) {
	    printf("User not authenticated. ");
	    if (require_otp)
		printf("Using one-time password\r\n");
	    else
		printf("Using plaintext username and password\r\n");
	}
	if (require_otp) {
	    addarg(&argv, "-a");
	    addarg(&argv, "otp");
	}
	if(log_unauth)
	    syslog(LOG_INFO, "unauthenticated access from %s (%s)",
		   host, user ? user : "unknown user");
    }
    if (auth_level >= 0 && autologin == AUTH_VALID)
	addarg(&argv, "-f");
#endif
    if(user){
	addarg(&argv, "--");
	addarg(&argv, strdup(user));
    }
    if (getenv("USER")) {
	/*
	 * Assume that login will set the USER variable
	 * correctly.  For SysV systems, this means that
	 * USER will no longer be set, just LOGNAME by
	 * login.  (The problem is that if the auto-login
	 * fails, and the user then specifies a different
	 * account name, he can get logged in with both
	 * LOGNAME and USER in his environment, but the
	 * USER value will be wrong.
	 */
	unsetenv("USER");
    }
    closelog();
    /*
     * This sleep(1) is in here so that telnetd can
     * finish up with the tty.  There's a race condition
     * the login banner message gets lost...
     */
    sleep(1);

    execv(new_login, argv.argv);
    save_errno = errno;
    syslog(LOG_ERR, "%s: %m", new_login);
    fatalperror_errno(net, new_login, save_errno);
    /*NOTREACHED*/
}

static void
addarg(struct arg_val *argv, const char *val)
{
    if(argv->size <= argv->argc+1) {
	argv->argv = realloc(argv->argv, sizeof(char*) * (argv->size + 10));
	if (argv->argv == NULL)
	    fatal (net, "realloc: out of memory");
	argv->size+=10;
    }
    if((argv->argv[argv->argc++] = strdup(val)) == NULL)
	fatal (net, "strdup: out of memory");
    argv->argv[argv->argc]   = NULL;
}


/*
 * rmut()
 *
 * This is the function called by cleanup() to
 * remove the utmp entry for this person.
 */

#ifdef HAVE_UTMPX_H
static void
rmut(void)
{
    struct utmpx utmpx, *non_save_utxp;
    char *clean_tty = clean_ttyname(line);

    /*
     * This updates the utmpx and utmp entries and make a wtmp/x entry
     */

    setutxent();
    memset(&utmpx, 0, sizeof(utmpx));
    strncpy(utmpx.ut_line, clean_tty, sizeof(utmpx.ut_line));
    utmpx.ut_type = LOGIN_PROCESS;
    non_save_utxp = getutxline(&utmpx);
    if (non_save_utxp) {
	struct utmpx *utxp;
	struct timeval tv;
	char user0;

	utxp = malloc(sizeof(struct utmpx));
	*utxp = *non_save_utxp;
	user0 = utxp->ut_user[0];
	utxp->ut_user[0] = '\0';
	utxp->ut_type = DEAD_PROCESS;
#ifdef HAVE_STRUCT_UTMPX_UT_EXIT
#ifdef _STRUCT___EXIT_STATUS
	utxp->ut_exit.__e_termination = 0;
	utxp->ut_exit.__e_exit = 0;
#elif defined(__osf__) /* XXX */
	utxp->ut_exit.ut_termination = 0;
	utxp->ut_exit.ut_exit = 0;
#else
	utxp->ut_exit.e_termination = 0;
	utxp->ut_exit.e_exit = 0;
#endif
#endif
	gettimeofday (&tv, NULL);
	utxp->ut_tv.tv_sec = tv.tv_sec;
	utxp->ut_tv.tv_usec = tv.tv_usec;

	pututxline(utxp);
#ifdef WTMPX_FILE
	utxp->ut_user[0] = user0;
	updwtmpx(WTMPX_FILE, utxp);
#elif defined(WTMP_FILE)
	/* This is a strange system with a utmpx and a wtmp! */
	{
	  int f = open(wtmpf, O_WRONLY|O_APPEND);
	  struct utmp wtmp;
	  if (f >= 0) {
	    strncpy(wtmp.ut_line,  clean_tty, sizeof(wtmp.ut_line));
	    strncpy(wtmp.ut_name,  "", sizeof(wtmp.ut_name));
#ifdef HAVE_STRUCT_UTMP_UT_HOST
	    strncpy(wtmp.ut_host,  "", sizeof(wtmp.ut_host));
#endif
	    wtmp.ut_time = time(NULL);
	    write(f, &wtmp, sizeof(wtmp));
	    close(f);
	  }
	}
#endif
	free (utxp);
    }
    endutxent();
}  /* end of rmut */
#endif

#if !defined(HAVE_UTMPX_H) && !(defined(_CRAY) || defined(__hpux)) && BSD <= 43
static void
rmut(void)
{
    int f;
    int found = 0;
    struct utmp *u, *utmp;
    int nutmp;
    struct stat statbf;
    char *clean_tty = clean_ttyname(line);

    f = open(utmpf, O_RDWR);
    if (f >= 0) {
	fstat(f, &statbf);
	utmp = (struct utmp *)malloc((unsigned)statbf.st_size);
	if (!utmp)
	    syslog(LOG_ERR, "utmp malloc failed");
	if (statbf.st_size && utmp) {
	    nutmp = read(f, utmp, (int)statbf.st_size);
	    nutmp /= sizeof(struct utmp);

	    for (u = utmp ; u < &utmp[nutmp] ; u++) {
		if (strncmp(u->ut_line,
			    clean_tty,
			    sizeof(u->ut_line)) ||
		    u->ut_name[0]==0)
		    continue;
		lseek(f, ((long)u)-((long)utmp), L_SET);
		strncpy(u->ut_name,  "", sizeof(u->ut_name));
#ifdef HAVE_STRUCT_UTMP_UT_HOST
		strncpy(u->ut_host,  "", sizeof(u->ut_host));
#endif
		u->ut_time = time(NULL);
		write(f, u, sizeof(wtmp));
		found++;
	    }
	}
	close(f);
    }
    if (found) {
	f = open(wtmpf, O_WRONLY|O_APPEND);
	if (f >= 0) {
	    strncpy(wtmp.ut_line,  clean_tty, sizeof(wtmp.ut_line));
	    strncpy(wtmp.ut_name,  "", sizeof(wtmp.ut_name));
#ifdef HAVE_STRUCT_UTMP_UT_HOST
	    strncpy(wtmp.ut_host,  "", sizeof(wtmp.ut_host));
#endif
	    wtmp.ut_time = time(NULL);
	    write(f, &wtmp, sizeof(wtmp));
	    close(f);
	}
    }
    chmod(line, 0666);
    chown(line, 0, 0);
    line[strlen("/dev/")] = 'p';
    chmod(line, 0666);
    chown(line, 0, 0);
}  /* end of rmut */
#endif	/* CRAY */

#if defined(__hpux) && !defined(HAVE_UTMPX_H)
static void
rmut (char *line)
{
    struct utmp utmp;
    struct utmp *utptr;
    int fd;			/* for /etc/wtmp */

    utmp.ut_type = USER_PROCESS;
    strncpy(utmp.ut_line, clean_ttyname(line), sizeof(utmp.ut_line));
    setutent();
    utptr = getutline(&utmp);
    /* write it out only if it exists */
    if (utptr) {
	utptr->ut_type = DEAD_PROCESS;
	utptr->ut_time = time(NULL);
	pututline(utptr);
	/* set wtmp entry if wtmp file exists */
	if ((fd = open(wtmpf, O_WRONLY | O_APPEND)) >= 0) {
	    write(fd, utptr, sizeof(utmp));
	    close(fd);
	}
    }
    endutent();

    chmod(line, 0666);
    chown(line, 0, 0);
    line[14] = line[13];
    line[13] = line[12];
    line[8] = 'm';
    line[9] = '/';
    line[10] = 'p';
    line[11] = 't';
    line[12] = 'y';
    chmod(line, 0666);
    chown(line, 0, 0);
}
#endif

/*
 * cleanup()
 *
 * This is the routine to call when we are all through, to
 * clean up anything that needs to be cleaned up.
 */

#ifdef PARENT_DOES_UTMP

void
cleanup(int sig)
{
#ifdef _CRAY
    static int incleanup = 0;
    int t;
    int child_status; /* status of child process as returned by waitpid */
    int flags = WNOHANG|WUNTRACED;

    /*
     * 1: Pick up the zombie, if we are being called
     *    as the signal handler.
     * 2: If we are a nested cleanup(), return.
     * 3: Try to clean up TMPDIR.
     * 4: Fill in utmp with shutdown of process.
     * 5: Close down the network and pty connections.
     * 6: Finish up the TMPDIR cleanup, if needed.
     */
    if (sig == SIGCHLD) {
	while (waitpid(-1, &child_status, flags) > 0)
	    ;	/* VOID */
	/* Check if the child process was stopped
	 * rather than exited.  We want cleanup only if
	 * the child has died.
	 */
	if (WIFSTOPPED(child_status)) {
	    return;
	}
    }
    t = sigblock(sigmask(SIGCHLD));
    if (incleanup) {
	sigsetmask(t);
	return;
    }
    incleanup = 1;
    sigsetmask(t);

    t = cleantmp(&wtmp);
    setutent();	/* just to make sure */
#endif /* CRAY */
    rmut(line);
    close(ourpty);
    shutdown(net, 2);
#ifdef _CRAY
    if (t == 0)
	cleantmp(&wtmp);
#endif /* CRAY */
    exit(1);
}

#else /* PARENT_DOES_UTMP */

void
cleanup(int sig)
{
#if defined(HAVE_UTMPX_H) || !defined(HAVE_LOGWTMP)
    rmut();
#ifdef HAVE_VHANGUP
#ifndef __sgi
    vhangup(); /* XXX */
#endif
#endif
#else
    char *p;

    p = line + sizeof("/dev/") - 1;
    if (logout(p))
	logwtmp(p, "", "");
    chmod(line, 0666);
    chown(line, 0, 0);
    *p = 'p';
    chmod(line, 0666);
    chown(line, 0, 0);
#endif
    shutdown(net, 2);
    exit(1);
}

#endif /* PARENT_DOES_UTMP */

#ifdef PARENT_DOES_UTMP
/*
 * _utmp_sig_rcv
 * utmp_sig_init
 * utmp_sig_wait
 *	These three functions are used to coordinate the handling of
 *	the utmp file between the server and the soon-to-be-login shell.
 *	The server actually creates the utmp structure, the child calls
 *	utmp_sig_wait(), until the server calls utmp_sig_notify() and
 *	signals the future-login shell to proceed.
 */
static int caught=0;		/* NZ when signal intercepted */
static void (*func)();		/* address of previous handler */

void
_utmp_sig_rcv(sig)
     int sig;
{
    caught = 1;
    signal(SIGUSR1, func);
}

void
utmp_sig_init()
{
    /*
     * register signal handler for UTMP creation
     */
    if ((int)(func = signal(SIGUSR1, _utmp_sig_rcv)) == -1)
	fatalperror(net, "telnetd/signal");
}

void
utmp_sig_reset()
{
    signal(SIGUSR1, func);	/* reset handler to default */
}

# ifdef __hpux
# define sigoff() /* do nothing */
# define sigon() /* do nothing */
# endif

void
utmp_sig_wait()
{
    /*
     * Wait for parent to write our utmp entry.
	 */
    sigoff();
    while (caught == 0) {
	pause();	/* wait until we get a signal (sigon) */
	sigoff();	/* turn off signals while we check caught */
    }
    sigon();		/* turn on signals again */
}

void
utmp_sig_notify(pid)
{
    kill(pid, SIGUSR1);
}

#ifdef _CRAY
static int gotsigjob = 0;

	/*ARGSUSED*/
void
sigjob(sig)
     int sig;
{
    int jid;
    struct jobtemp *jp;

    while ((jid = waitjob(NULL)) != -1) {
	if (jid == 0) {
	    return;
	}
	gotsigjob++;
	jobend(jid, NULL, NULL);
    }
}

/*
 *	jid_getutid:
 *		called by jobend() before calling cleantmp()
 *		to find the correct $TMPDIR to cleanup.
 */

struct utmp *
jid_getutid(jid)
     int jid;
{
    struct utmp *cur = NULL;

    setutent();	/* just to make sure */
    while (cur = getutent()) {
	if ( (cur->ut_type != NULL) && (jid == cur->ut_jid) ) {
	    return(cur);
	}
    }

    return(0);
}

/*
 * Clean up the TMPDIR that login created.
 * The first time this is called we pick up the info
 * from the utmp.  If the job has already gone away,
 * then we'll clean up and be done.  If not, then
 * when this is called the second time it will wait
 * for the signal that the job is done.
 */
int
cleantmp(wtp)
     struct utmp *wtp;
{
    struct utmp *utp;
    static int first = 1;
    int mask, omask, ret;
    extern struct utmp *getutid (const struct utmp *_Id);


    mask = sigmask(WJSIGNAL);

    if (first == 0) {
	omask = sigblock(mask);
	while (gotsigjob == 0)
	    sigpause(omask);
	return(1);
    }
    first = 0;
    setutent();	/* just to make sure */

    utp = getutid(wtp);
    if (utp == 0) {
	syslog(LOG_ERR, "Can't get /etc/utmp entry to clean TMPDIR");
	return(-1);
    }
    /*
     * Nothing to clean up if the user shell was never started.
     */
    if (utp->ut_type != USER_PROCESS || utp->ut_jid == 0)
	return(1);

    /*
     * Block the WJSIGNAL while we are in jobend().
     */
    omask = sigblock(mask);
    ret = jobend(utp->ut_jid, utp->ut_tpath, utp->ut_user);
    sigsetmask(omask);
    return(ret);
}

int
jobend(jid, path, user)
     int jid;
     char *path;
     char *user;
{
    static int saved_jid = 0;
    static int pty_saved_jid = 0;
    static char saved_path[sizeof(wtmp.ut_tpath)+1];
    static char saved_user[sizeof(wtmp.ut_user)+1];

    /*
     * this little piece of code comes into play
     * only when ptyreconnect is used to reconnect
     * to an previous session.
     *
     * this is the only time when the
     * "saved_jid != jid" code is executed.
     */

    if ( saved_jid && saved_jid != jid ) {
	if (!path) {	/* called from signal handler */
	    pty_saved_jid = jid;
	} else {
	    pty_saved_jid = saved_jid;
	}
    }

    if (path) {
	strlcpy(saved_path, path, sizeof(saved_path));
	strlcpy(saved_user, user, sizeof(saved_user));
    }
    if (saved_jid == 0) {
	saved_jid = jid;
	return(0);
    }

    /* if the jid has changed, get the correct entry from the utmp file */

    if ( saved_jid != jid ) {
	struct utmp *utp = NULL;
	struct utmp *jid_getutid();

	utp = jid_getutid(pty_saved_jid);

	if (utp == 0) {
	    syslog(LOG_ERR, "Can't get /etc/utmp entry to clean TMPDIR");
	    return(-1);
	}

	cleantmpdir(jid, utp->ut_tpath, utp->ut_user);
	return(1);
    }

    cleantmpdir(jid, saved_path, saved_user);
    return(1);
}

/*
 * Fork a child process to clean up the TMPDIR
 */
cleantmpdir(jid, tpath, user)
     int jid;
     char *tpath;
     char *user;
{
    switch(fork()) {
    case -1:
	syslog(LOG_ERR, "TMPDIR cleanup(%s): fork() failed: %m\n",
	       tpath);
	break;
    case 0:
	execl(CLEANTMPCMD, CLEANTMPCMD, user, tpath, NULL);
	syslog(LOG_ERR, "TMPDIR cleanup(%s): execl(%s) failed: %m\n",
	       tpath, CLEANTMPCMD);
	exit(1);
    default:
	/*
	 * Forget about child.  We will exit, and
	 * /etc/init will pick it up.
	 */
	break;
    }
}
#endif /* CRAY */
#endif	/* defined(PARENT_DOES_UTMP) */