summaryrefslogtreecommitdiffstats
path: root/lib/vty.c
blob: d5d07676ffdca661761dfde09cc7b1a8d6182cd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
/* VTY top level
 * Copyright (C) 1997, 98 Kunihiro Ishiguro
 *
 * Revisions: Copyright (C) 2010 Chris Hall (GMCH), Highwayman
 *
 * This file is part of GNU Zebra.
 *
 * GNU Zebra is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * GNU Zebra is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Zebra; see the file COPYING.  If not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#include "zebra.h"
#include <stdbool.h>
#include "lib/version.h"

#include "vty_io.h"
#include "vty.h"
#include "uty.h"
#include "vty_cli.h"

#include "list_util.h"

#include "command.h"
#include "command_queue.h"
#include "command_execute.h"
#include "memory.h"
#include "log.h"
#include "mqueue.h"

/*==============================================================================
 * Variables etc. (see uty.h)
 */

/* The mutex and related debug counters                                 */
qpt_mutex_t vty_mutex ;

#if VTY_DEBUG

int vty_lock_count  = 0 ;
int vty_assert_fail = 0 ;

#endif

/* For thread handling -- initialised in vty_init                       */
struct thread_master* vty_master = NULL ;

/* In the qpthreads world, have nexus for the CLI and one for the Routeing
 * Engine.  Some commands are processed directly in the CLI, most have to
 * be sent to the Routeing Engine.
 */
qpn_nexus vty_cli_nexus  = NULL ;
qpn_nexus vty_cmd_nexus  = NULL ;

/* List of all known vio                                                */
vty_io vio_list_base      = NULL ;

/* List of all vty which are in monitor state.                          */
vty_io vio_monitors_base  = NULL ;

/* List of all vty which are on death watch                             */
vty_io vio_death_watch    = NULL ;

/* Vty timeout value -- see "exec timeout" command                      */
unsigned long vty_timeout_val = VTY_TIMEOUT_DEFAULT;

/* Vty access-class command                                             */
char *vty_accesslist_name = NULL;

/* Vty access-class for IPv6.                                           */
char *vty_ipv6_accesslist_name = NULL;

/* Current directory -- initialised in vty_init()                       */
static char *vty_cwd = NULL;

/* Configure lock -- only one vty may be in CONFIG_NODE or above !      */
bool vty_config = 0 ;

/* Login password check override.                                       */
bool no_password_check = 0;

/* Restrict unauthenticated logins?                                     */
const bool restricted_mode_default = 0 ;
      bool restricted_mode         = 0 ;

/* Watch-dog timer.                                                     */
union vty_watch_dog vty_watch_dog = { NULL } ;

/*------------------------------------------------------------------------------
 * VTYSH stuff
 */

/* Integrated configuration file path -- for VTYSH                      */
char integrate_default[] = SYSCONFDIR INTEGRATE_DEFAULT_CONFIG ;

/*------------------------------------------------------------------------------
 * Prototypes
 */
static void uty_reset (bool final, const char* why) ;
static void uty_init_commands (void) ;
static void vty_save_cwd (void) ;

/*------------------------------------------------------------------------------
 * Tracking the initialisation state.
 */
enum vty_init_state
{
  vty_init_pending     = 0,     /* first and lowest numbered state      */
  vty_init_1st_stage,
  vty_init_2nd_stage,
  vty_init_started,
  vty_init_reset,
  vty_init_terminated           /* final and highest numbered state     */
};

static enum vty_init_state vty_init_state ;

/*==============================================================================
 * Public Interface
 */

/*------------------------------------------------------------------------------
 * Initialise vty handling (threads and pthreads)
 *
 * Install vty's own commands like `who' command.
 *
 * This runs before any pthreads or nexus stuff starts -- so is, implicitly,
 * in the CLI thread.
 *
 * NB: may be called once and once only.
 */
extern void
vty_init (struct thread_master *master_thread)
{
  VTY_LOCK() ;                  /* Does nothing if !qpthreads_enabled   */
  VTY_ASSERT_CLI_THREAD() ;     /* True if !qpthreads_enabled           */

  assert(vty_init_state == vty_init_pending) ;

  vty_master = master_thread;   /* Local pointer to the master thread   */

  vty_save_cwd ();              /* need cwd for config reading          */

  vio_list_base       = NULL ;  /* no VTYs yet                          */
  vio_monitors_base   = NULL ;
  vio_death_watch     = NULL ;

  vty_cli_nexus       = NULL ;  /* not running qnexus-wise              */
  vty_cmd_nexus       = NULL ;

  vty_watch_dog.anon  = NULL ;  /* no watch dog                         */

  uty_init_commands() ;         /* install nodes                        */

  vty_init_state = vty_init_1st_stage ;

  VTY_UNLOCK() ;
}

/*------------------------------------------------------------------------------
 * Further initialisation for qpthreads.
 *
 * This is done during "second stage" initialisation, when all nexuses have
 * been set up and the qpthread_enabled state established.
 *
 * This is before any threads have been started, so is, implicitly, in the
 * CLI thread.
 *
 * Need to know where the CLI nexus and the Routeing Engine nexus are.
 *
 * Initialise mutex.
 *
 * Cannot lock or assert in CLI thread while initialising those things !
 *
 * NB: may be called once and once only.
 */
extern void
vty_init_r (qpn_nexus cli, qpn_nexus cmd)
{
  assert(vty_init_state == vty_init_1st_stage) ;

  vty_cli_nexus = cli ;
  vty_cmd_nexus = cmd ;

  qpt_mutex_init(&vty_mutex, qpt_mutex_recursive);

  vty_init_state = vty_init_2nd_stage ;
} ;

/*------------------------------------------------------------------------------
 * Initialisation for vtysh application.
 *
 * TODO: work out what this needs to do !  (If anything.)
 */
extern void
vty_init_vtysh (void)
{
  VTY_LOCK() ;

  VTY_UNLOCK() ;
} ;

/*------------------------------------------------------------------------------
 * Start the VTY going.
 *
 * This starts the listeners for VTY_TERM and VTY_SHELL_SERV.
 *
 * Also starts the watch dog.
 *
 * This is run during early morning start, after any daemonisation, but before
 * any threads are started -- so is, implicitly, in the CLI thread.
 *
 * NB: may be called once and once only.
 *
 * NB: MUST be in the CLI thread (if any).
 */
extern void
vty_start(const char *addr, unsigned short port, const char *path)
{
  VTY_LOCK() ;
  VTY_ASSERT_CLI_THREAD() ;

  assert( (vty_init_state == vty_init_1st_stage)
       || (vty_init_state == vty_init_2nd_stage) ) ;

  uty_watch_dog_start() ;

  uty_open_listeners(addr, port, path) ;

  vty_init_state = vty_init_started ;
  VTY_UNLOCK() ;
} ;

/*------------------------------------------------------------------------------
 * Reset all VTY status for reasons unknown -- probably SIGHUP
 */
extern void
vty_reset()
{
  vty_reset_because("Reset") ;
}

/*------------------------------------------------------------------------------
 * Reset all VTY status
 *
 * This is done in response to SIGHUP -- and runs in the CLI thread.
 *
 * Half closes all VTY, leaving the death watch to tidy up once all output
 * and any command in progress have completed.
 *
 * Closes all listening sockets.
 *
 * TODO: revoke ?
 *
 * NB: old code discarded all output and hard closed all the VTY...
 */
extern void
vty_reset_because(const char* why)
{
  VTY_LOCK() ;
  VTY_ASSERT_CLI_THREAD() ;

  assert(vty_init_state == vty_init_started) ;

  uty_reset(0, why) ;   /* not final !  */

  vty_init_state = vty_init_reset ;
  VTY_UNLOCK() ;
}

/*------------------------------------------------------------------------------
 * Restart the VTY, following a vty_reset().
 *
 * This starts the listeners for VTY_TERM and VTY_SHELL_SERV, again.
 *
 * NB: may be called once, and once only, *after* a vty_reset().
 *
 * NB: need not be in the CLI thread (if any).
 */
struct vty_restart_args
{
  char*          addr ;
  unsigned short port ;
  char*          path ;
} ;
MQB_ARGS_SIZE_OK(vty_restart_args) ;

static void uty_restart_action(mqueue_block mqb, mqb_flag_t flag) ;
static void uty_restart(const char *addr, unsigned short port,
                                                             const char *path) ;
extern void
vty_restart(const char *addr, unsigned short port, const char *path)
{
  VTY_LOCK() ;

  /* If not running qnexus-wise, call uty_restart directly.
   *
   * Otherwise, construct and dispatch message to do a uty_restart.
   */
  if (!vty_cli_nexus)
    uty_restart(addr, port, path) ;
  else
    {
      mqueue_block mqb ;
      struct vty_restart_args* args ;

      mqb  = mqb_init_new(NULL, uty_restart_action, vty_cli_nexus) ;
      args = mqb_get_args(mqb) ;

      if (addr != NULL)
        args->addr = XSTRDUP(MTYPE_TMP, addr) ;
      else
        args->addr = NULL ;

      args->port = port ;

      if (path != NULL)
        args->path = XSTRDUP(MTYPE_TMP, path) ;
      else
        args->path = NULL ;

      mqueue_enqueue(vty_cli_nexus->queue, mqb, 0) ;
    } ;

  VTY_UNLOCK() ;
} ;

/* Deal with the uty_restart message                                    */
static void
uty_restart_action(mqueue_block mqb, mqb_flag_t flag)
{
  struct vty_restart_args* args ;
  args = mqb_get_args(mqb) ;

  if (flag == mqb_action)
    {
      VTY_LOCK() ;

      uty_restart(args->addr, args->port, args->path) ;

      VTY_UNLOCK() ;
    } ;

  if (args->addr != NULL)
    XFREE(MTYPE_TMP, args->addr) ;
  if (args->path != NULL)
    XFREE(MTYPE_TMP, args->path) ;
} ;

/* Do the actual restart                                                */
static void
uty_restart(const char *addr, unsigned short port, const char *path)
{
  VTY_ASSERT_LOCKED() ;
  assert(vty_init_state == vty_init_reset) ;

  uty_open_listeners(addr, port, path) ;

  vty_init_state = vty_init_started ;
} ;

/*------------------------------------------------------------------------------
 * System shut-down
 *
 * In the pthreads world, all threads other than the main (CLI) thread have
 * been joined -- so this is, implicitly, in the CLI thread.
 *
 * Close all known vty and release all memory -- discard all pending output.
 *
 * NB: this may be done in any initialisation state.
 *
 * Note that all the locking stuff does nothing if not qpthreads_enabled, so
 * these may be done in any state of initialisation.  (It is assumed that the
 * switch into qpthreads_enabled is an atomic action... so all second stage
 * initialisation completes together.)
 */
extern void
vty_terminate (void)
{
  if (  (vty_init_state == vty_init_pending)
     || (vty_init_state == vty_init_terminated)  )
    return ;            /* nothing to do !      */

  VTY_LOCK() ;
  VTY_ASSERT_CLI_THREAD() ;

  assert(  (vty_init_state > vty_init_pending)
        && (vty_init_state < vty_init_terminated)  ) ;

  uty_reset(1, "Shut down") ;   /* final reset          */

  VTY_UNLOCK() ;

  qpt_mutex_destroy(&vty_mutex, 0);

  vty_init_state = vty_init_terminated ;
}

/*------------------------------------------------------------------------------
 * Reset -- final or for SIGHUP
 *
 * Closes listeners.
 *
 * Closes (final) or half closes (SIGHUP) all VTY, and revokes any outstanding
 * commands.
 *
 * Resets the vty timeout and access lists.
 *
 * When reach final reset it should not be possible for there to be any
 * commands still in progress.  If there are, they are simply left on the
 * death-watch list... there is no pressing need to do anything more radical,
 * and the presence of anything on the death watch is grounds for some debug
 * activity !
 */
static void
uty_reset (bool curtains, const char* why)
{
  vty_io vio ;
  vty_io next ;

  VTY_ASSERT_LOCKED() ;
  VTY_ASSERT_CLI_THREAD() ;

  uty_close_listeners() ;

  next = sdl_head(vio_list_base) ;
  while (next != NULL)
    {
      vio  = next ;
      next = sdl_next(vio, vio_list) ;

      if (vio->type == VTY_TERM)
        cq_revoke(vio->vty) ;

      if (why != NULL)
        vio->close_reason = why ;

      if (curtains)
        uty_close(vio) ;
      else
        uty_half_close(vio, why) ;
    } ;

  vty_timeout_val = VTY_TIMEOUT_DEFAULT;

  if (vty_accesslist_name)
    {
      XFREE(MTYPE_VTY, vty_accesslist_name);
      vty_accesslist_name = NULL;
    }

  if (vty_ipv6_accesslist_name)
    {
      XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
      vty_ipv6_accesslist_name = NULL;
    }

  if (curtains && vty_cwd)
    XFREE (MTYPE_TMP, vty_cwd);

  if (curtains)
    uty_watch_dog_stop() ;      /* and final death watch run    */
} ;

/*==============================================================================
 * Opening and closing VTY.
 *
 * VTY without a socket may be opened and closed at will.
 *
 * TODO: sort out the relationship between the non-socket VTY and vty_reset()
 */

/*------------------------------------------------------------------------------
 * Create a new VTY of the given type
 *
 * The type may NOT be: VTY_TERM or VTY_SHELL_SERV
 */
extern struct vty *
vty_open(enum vty_type type)
{
  struct vty* vty ;

  VTY_LOCK() ;
  vty = uty_new(type, -1) ;   /* fails for VTY_TERM or VTY_SHELL_SERV   */
  VTY_UNLOCK() ;

  return vty ;
} ;

/*------------------------------------------------------------------------------
 * Close the given VTY
 */
extern void
vty_close (struct vty *vty)
{
  VTY_LOCK() ;
  uty_close(vty->vio) ;
  VTY_UNLOCK() ;
}

/*==============================================================================
 * General VTY output.
 *
 * This is mostly used during command execution, to output the results of the
 * command.
 *
 * All these end up in uty_vout -- see vty_io.
 */

/*------------------------------------------------------------------------------
 * VTY output -- cf fprintf !
 */
extern int
vty_out (struct vty *vty, const char *format, ...)
{
  int result;

  VTY_LOCK() ;
  va_list args;
  va_start (args, format);
  result = uty_vout(vty, format, args);
  va_end (args);
  VTY_UNLOCK() ;
  return result;
}

/*------------------------------------------------------------------------------
 * VTY output -- output a given numnber of spaces
 */

/*                                         1         2         3         4 */
/*                                1234567890123456789012345678901234567890 */
const char vty_spaces_string[] = "                                        " ;
CONFIRM(VTY_MAX_SPACES == (sizeof(vty_spaces_string) - 1)) ;

extern void
vty_out_indent(struct vty *vty, int indent)
{
  while (indent > 0)
    {
      vty_out(vty, VTY_SPACES(indent)) ;
      indent -= VTY_MAX_SPACES ;
    }
} ;

/*------------------------------------------------------------------------------
 * VTY output -- output the current time in standard form, to the second.
 */
extern void
vty_time_print (struct vty *vty, int cr)
{
  char buf [timestamp_buffer_len];

  quagga_timestamp(0, buf, sizeof(buf)) ;

  if (cr)
    vty_out (vty, "%s%s", buf, VTY_NEWLINE);
  else
    vty_out (vty, "%s ", buf);

  return;
}

/*------------------------------------------------------------------------------
 * Say hello to vty interface.
 */
void
vty_hello (struct vty *vty)
{
  VTY_LOCK() ;

#ifdef QDEBUG
  uty_out (vty, "%s%s", debug_banner, VTY_NEWLINE);
#endif
  if (host.motdfile)
    {
      FILE *f;
      char buf[4096];

      f = fopen (host.motdfile, "r");
      if (f)
        {
          while (fgets (buf, sizeof (buf), f))
            {
              char *s;
              /* work backwards to ignore trailing isspace() */
              for (s = buf + strlen (buf); (s > buf) && isspace ((int)*(s - 1));
                   s--);
              *s = '\0';
              uty_out (vty, "%s%s", buf, VTY_NEWLINE);
            }
          fclose (f);
        }
      else
        uty_out (vty, "MOTD file %s not found%s", host.motdfile, VTY_NEWLINE);
    }
  else if (host.motd)
    uty_out (vty, "%s", host.motd);

  VTY_UNLOCK() ;
}

/*------------------------------------------------------------------------------
 * Clear the contents of the command output FIFO etc.
 */
extern void
vty_out_clear(struct vty* vty)
{
  VTY_LOCK() ;
  uty_out_clear(vty->vio) ;
  VTY_UNLOCK() ;
} ;

/*==============================================================================
 * Command Execution
 */

/*------------------------------------------------------------------------------
 * Execute command -- adding to history is not empty or just comment
 *
 * This is for VTY_TERM type VTY.
 *
 * Outputs diagnostics if fails to parse.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
uty_command(struct vty *vty)
{
  enum cmd_return_code ret;

  VTY_ASSERT_LOCKED() ;
  VTY_ASSERT_CLI_THREAD() ;

  assert(vty->vio->type == VTY_TERM) ;

  /* Parse the command and add to history (if not empty)                */
  ret = cmd_parse_command(vty,
                         cmd_parse_completion + cmd_parse_do + cmd_parse_tree) ;
  if (ret != CMD_EMPTY)
    uty_cli_hist_add (vty->vio, vty->buf) ;

  /* If parsed and not empty, dispatch                                  */
  if (ret == CMD_SUCCESS)
    {
#ifdef CONSUMED_TIME_CHECK
      RUSAGE_T before;
      RUSAGE_T after;
      unsigned long realtime, cputime;

      GETRUSAGE(&before);
#endif /* CONSUMED_TIME_CHECK */

      ret = cmd_dispatch(vty, cmd_may_queue) ;

#ifdef CONSUMED_TIME_CHECK
      GETRUSAGE(&after);
      if ((realtime = thread_consumed_time(&after, &before, &cputime)) >
                                                            CONSUMED_TIME_CHECK)
        /* Warn about CPU hog that must be fixed. */
        uzlog(NULL, LOG_WARNING,
                     "SLOW COMMAND: command took %lums (cpu time %lums): %s",
                                        realtime/1000, cputime/1000, vty->buf) ;
#endif /* CONSUMED_TIME_CHECK */
    } ;

  /* Deal with the return code                                          */
  switch (ret)
  {
    case CMD_ERR_AMBIGUOUS:
      uty_out (vty, "%% Ambiguous command.%s", VTY_NEWLINE);
      break;

    case CMD_ERR_NO_MATCH:
      uty_out (vty, "%% Unknown command.%s", VTY_NEWLINE) ;
      break;

    case CMD_ERR_INCOMPLETE:
      uty_out (vty, "%% Command incomplete.%s", VTY_NEWLINE);
      break;

    default:
      break ;
  } ;

  return ret ;
} ;

/*------------------------------------------------------------------------------
 * Authentication of vty
 *
 * During AUTH_NODE and AUTH_ENABLE_NODE, when a command line is dispatched by
 * any means this function is called.
 *
 * Note that if the AUTH_NODE password fails too many times, the terminal is
 * closed.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
uty_auth (struct vty *vty, const char *buf, enum cli_do cli_do)
{
  char *passwd = NULL;
  enum node_type next_node = 0;
  int fail;
  char *crypt (const char *, const char *);
  enum cmd_return_code ret ;

  vty_io  vio = vty->vio ;

  VTY_ASSERT_LOCKED() ;
  VTY_ASSERT_CLI_THREAD() ;

  /* What to do ?
   *
   * In fact, all the exotic command terminators simply discard any input
   * and return.
   */
  switch (cli_do)
  {
    case cli_do_nothing:
    case cli_do_ctrl_c:
    case cli_do_ctrl_z:
      return CMD_SUCCESS ;

    case cli_do_command:
      break ;

    case cli_do_ctrl_d:
    case cli_do_eof:
      return uty_cmd_close(vty, "End") ;

    default:
      zabort("unknown or invalid cli_do") ;
  } ;

  /* Ordinary command dispatch -- see if password is OK.                */
  switch (vty->node)
  {
    case AUTH_NODE:
      if (host.encrypt)
	passwd = host.password_encrypt;
      else
	passwd = host.password;
      if (host.advanced)
	next_node = host.enable ? VIEW_NODE : ENABLE_NODE;
      else
	next_node = VIEW_NODE;
      break;

    case AUTH_ENABLE_NODE:
      if (host.encrypt)
	passwd = host.enable_encrypt;
      else
	passwd = host.enable;
      next_node = ENABLE_NODE;
      break;

    default:
      zabort("unknown node type") ;
  }

  if (passwd)
    {
      if (host.encrypt)
	fail = strcmp (crypt(buf, passwd), passwd);
      else
	fail = strcmp (buf, passwd);
    }
  else
    fail = 1;

  ret = CMD_SUCCESS ;

  if (! fail)
    {
      vio->fail = 0;
      vty->node = next_node;	/* Success ! */
    }
  else
    {
      vio->fail++;
      if (vio->fail >= 3)
	{
	  if (vty->node == AUTH_NODE)
	    {
	      ret = uty_cmd_close(vty, "Bad passwords, too many failures!%s") ;
	    }
	  else
	    {
	      /* AUTH_ENABLE_NODE */
	      vio->fail = 0;
	      uty_out (vty, "%% Bad enable passwords, too many failures!%s",
	                                                           VTY_NEWLINE);
	      vty->node = restricted_mode ? RESTRICTED_NODE : VIEW_NODE;

	      ret = CMD_WARNING ;
	    }
	}
    }

  return ret ;
} ;

/*------------------------------------------------------------------------------
 * Command line "exit" command -- aka "quit"
 *
 * Falls back one NODE level.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
vty_cmd_exit(struct vty* vty)
{
  enum cmd_return_code ret ;

  VTY_LOCK() ;

  ret = CMD_SUCCESS ;
  switch (vty->node)
    {
    case VIEW_NODE:
    case ENABLE_NODE:
    case RESTRICTED_NODE:
      if (vty_shell (vty))
        exit (0);
      else
        ret = uty_cmd_close(vty, "Exit") ;
      break;
    case CONFIG_NODE:
      uty_config_unlock (vty, ENABLE_NODE);
      break;
    case INTERFACE_NODE:
    case ZEBRA_NODE:
    case BGP_NODE:
    case RIP_NODE:
    case RIPNG_NODE:
    case OSPF_NODE:
    case OSPF6_NODE:
    case ISIS_NODE:
    case KEYCHAIN_NODE:
    case MASC_NODE:
    case RMAP_NODE:
    case VTY_NODE:
      vty->node = CONFIG_NODE ;
      break;
    case BGP_VPNV4_NODE:
    case BGP_IPV4_NODE:
    case BGP_IPV4M_NODE:
    case BGP_IPV6_NODE:
    case BGP_IPV6M_NODE:
      vty->node = BGP_NODE ;
      break;
    case KEYCHAIN_KEY_NODE:
      vty->node = KEYCHAIN_NODE ;
      break;
    default:
      break;
    }

  VTY_UNLOCK() ;
  return ret ;
}

/*------------------------------------------------------------------------------
 * Command line "end" command
 *
 * Falls back to ENABLE_NODE.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
vty_cmd_end(struct vty* vty)
{
  VTY_LOCK() ;

  switch (vty->node)
    {
    case VIEW_NODE:
    case ENABLE_NODE:
    case RESTRICTED_NODE:
      /* Nothing to do. */
      break;
    case CONFIG_NODE:
    case INTERFACE_NODE:
    case ZEBRA_NODE:
    case RIP_NODE:
    case RIPNG_NODE:
    case BGP_NODE:
    case BGP_VPNV4_NODE:
    case BGP_IPV4_NODE:
    case BGP_IPV4M_NODE:
    case BGP_IPV6_NODE:
    case BGP_IPV6M_NODE:
    case RMAP_NODE:
    case OSPF_NODE:
    case OSPF6_NODE:
    case ISIS_NODE:
    case KEYCHAIN_NODE:
    case KEYCHAIN_KEY_NODE:
    case MASC_NODE:
    case VTY_NODE:
      uty_config_unlock (vty, ENABLE_NODE);
      break;
    default:
      break;
    }

  VTY_UNLOCK() ;
  return CMD_SUCCESS ;
} ;

/*------------------------------------------------------------------------------
 * Result of command is to close the input.
 *
 * Posts the reason for the close.
 *
 * Returns: CMD_CLOSE
 */
extern enum cmd_return_code
uty_cmd_close(struct vty *vty, const char* reason)
{
  vty->vio->close_reason = reason ;
  return CMD_CLOSE ;
} ;

/*------------------------------------------------------------------------------
 * Command line ^C action.
 *
 * Ignores contents of command line (including not adding to history).
 *
 * Fall back to ENABLE_NODE if in any one of a number of nodes.
 *
 * Resets the history pointer.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
uty_stop_input(struct vty *vty)
{
  vty_io  vio = vty->vio ;

  VTY_ASSERT_LOCKED() ;

  switch (vty->node)
    {
    case CONFIG_NODE:
    case INTERFACE_NODE:
    case ZEBRA_NODE:
    case RIP_NODE:
    case RIPNG_NODE:
    case BGP_NODE:
    case RMAP_NODE:
    case OSPF_NODE:
    case OSPF6_NODE:
    case ISIS_NODE:
    case KEYCHAIN_NODE:
    case KEYCHAIN_KEY_NODE:
    case MASC_NODE:
    case VTY_NODE:
      uty_config_unlock (vty, ENABLE_NODE) ;
      break;
    default:
      /* Unknown node, we have to ignore it. */
      break;
    }

  /* Set history pointer to the latest one. */
  vio->hp = vio->hindex;

  return CMD_SUCCESS ;
} ;

/*------------------------------------------------------------------------------
 * Command ^Z action.
 *
 * Ignores contents of command line (including not adding to history).
 *
 * Fall back to ENABLE_NODE if in any one of a number of nodes.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
uty_end_config (struct vty *vty)
{
  VTY_ASSERT_LOCKED() ;

  switch (vty->node)
    {
    case VIEW_NODE:
    case ENABLE_NODE:
    case RESTRICTED_NODE:
      /* Nothing to do. */
      break;
    case CONFIG_NODE:
    case INTERFACE_NODE:
    case ZEBRA_NODE:
    case RIP_NODE:
    case RIPNG_NODE:
    case BGP_NODE:
    case BGP_VPNV4_NODE:
    case BGP_IPV4_NODE:
    case BGP_IPV4M_NODE:
    case BGP_IPV6_NODE:
    case BGP_IPV6M_NODE:
    case RMAP_NODE:
    case OSPF_NODE:
    case OSPF6_NODE:
    case ISIS_NODE:
    case KEYCHAIN_NODE:
    case KEYCHAIN_KEY_NODE:
    case MASC_NODE:
    case VTY_NODE:
      uty_config_unlock (vty, ENABLE_NODE) ;
      break;
    default:
      /* Unknown node, we have to ignore it. */
      break;
    }

  return CMD_SUCCESS ;
}

/*------------------------------------------------------------------------------
 * Command ^D action -- when nothing else on command line.
 *
 * Same as "exit" command.
 *
 * Returns: command return code
 */
extern enum cmd_return_code
uty_down_level (struct vty *vty)
{
  return vty_cmd_exit(vty) ;
} ;

/*==============================================================================
 * Reading of configuration file
 *
 * The reading of the configuration file occurs at two times:
 *
 *   1. early in the morning, before daemonisation, and before any threads
 *      or nexuses have been set up.
 *
 *      In the qpthreads world, this means that it is running in the main (CLI)
 *      and only thread and nexus.
 *
 *   2. at SIGHUP time.
 *
 *      In the qpthreads world, this is running in whatever thread is executing
 *      commands.
 *
 * Sets up a VTY_CONFIG_READ in which to execute commands.  This has no CLI
 * and no socket.  All output is buffered in the cmd_obuf.  All commands are
 * run directly in the thread -- no commands are queued.
 */

static FILE * vty_use_backup_config (char *fullpath) ;
static void vty_read_file (FILE *confp, struct cmd_element* first_cmd,
                                                         bool ignore_warnings) ;

/*------------------------------------------------------------------------------
 * Read the given configuration file.
 */
extern void
vty_read_config (char *config_file,
                 char *config_default)
{
  vty_read_config_first_cmd_special(config_file, config_default, NULL, 1);
}

/*------------------------------------------------------------------------------
 * Read the given configuration file.
 *
 * The config_file (-f argument) is used if specified.
 *
 * If config_file is NULL, use the config_default.
 *
 * If using the config_default, if VTYSH_ENABLED, look for "vtysh" in the name.
 * If find "vtysh" and find the "integrate_default" file, then do nothing
 * now -- expect vtysh to connect in due course and provide the configuration.
 *
 * The config_file or config_default may be relative file names.
 *
 * May have a function to call after the first actual command is processed.
 * This mechanism supports the setting of qpthreads-ness by configuration file
 * command.
 */
extern void
vty_read_config_first_cmd_special(char *config_file,
                                  char *config_default,
                                  struct cmd_element* first_cmd,
                                  bool ignore_warnings)
{
  char cwd[MAXPATHLEN];
  FILE *confp = NULL;
  char *fullpath;
  char *tmp = NULL;

  /* Deal with VTYSH_ENABLED magic                                      */
  if (VTYSH_ENABLED && (config_file == NULL))
    {
      int ret;
      struct stat conf_stat;

      /* !!!!PLEASE LEAVE!!!!
       * This is NEEDED for use with vtysh -b, or else you can get
       * a real configuration food fight with a lot garbage in the
       * merged configuration file it creates coming from the per
       * daemon configuration files.  This also allows the daemons
       * to start if there default configuration file is not
       * present or ignore them, as needed when using vtysh -b to
       * configure the daemons at boot - MAG
       */

      /* Stat for vtysh Zebra.conf, if found startup and wait for
       * boot configuration
       */

      if ( strstr(config_default, "vtysh") == NULL)
        {
          ret = stat (integrate_default, &conf_stat);
          if (ret >= 0)
            return;
        }
    } ;

  /* Use default if necessary, and deal with constructing full path     */
  if (config_file == NULL)
    config_file = config_default ;

  if (! IS_DIRECTORY_SEP (config_file[0]))
    {
      getcwd (cwd, sizeof(cwd)) ;
      tmp = XMALLOC (MTYPE_TMP, strlen (cwd) + strlen (config_file) + 2) ;
      sprintf (tmp, "%s/%s", cwd, config_file);
      fullpath = tmp;
    }
  else
    {
      tmp = NULL ;
      fullpath = config_file;
    } ;

  /* try to open the configuration file                                 */
  confp = fopen (fullpath, "r");

  if (confp == NULL)
    {
      fprintf (stderr, "%s: failed to open configuration file %s: %s\n",
                                    __func__, fullpath, errtostr(errno, 0).str);

      confp = vty_use_backup_config (fullpath);
      if (confp)
        fprintf (stderr, "WARNING: using backup configuration file!\n");
      else
        {
          fprintf (stderr, "can't open backup configuration file [%s%s]\n",
                                                    fullpath, CONF_BACKUP_EXT);
          exit(1);
        }
    } ;

#ifdef QDEBUG
  fprintf(stderr, "Reading config file: %s\n", fullpath);
#endif

  vty_read_file (confp, first_cmd, ignore_warnings);
  fclose (confp);

  host_config_set (fullpath);

#ifdef QDEBUG
  fprintf(stderr, "Finished reading config file\n");
#endif

  if (tmp)
    XFREE (MTYPE_TMP, tmp);
}

/*------------------------------------------------------------------------------
 * Try to use a backup configuration file.
 *
 * Having failed to open the file "<fullpath>", if there is a file called
 * "<fullpath>.sav" that can be opened for reading, then:
 *
 *   - make a copy of that file
 *   - call it "<fullpath>"
 *   - return an open FILE
 *
 * Returns: NULL => no "<fullpath>.sav", or faild doing any of the above
 *          otherwise, returns FILE* for open file.
 */
static FILE *
vty_use_backup_config (char *fullpath)
{
  char *tmp_path ;
  struct stat buf;
  int ret, tmp, sav;
  int c;
  char buffer[4096] ;

  enum { xl = 32 } ;
  tmp_path = malloc(strlen(fullpath) + xl) ;

  /* construct the name "<fullname>.sav", and try to open it.           */
  confirm(xl > sizeof(CONF_BACKUP_EXT)) ;
  sprintf (tmp_path, "%s%s", fullpath, CONF_BACKUP_EXT) ;

  sav = -1 ;
  if (stat (tmp_path, &buf) != -1)
    sav = open (tmp_path, O_RDONLY);

  if (sav < 0)
    {
      free (tmp_path);
      return NULL;
    } ;

  /* construct a temporary file and copy "<fullpath.sav>" to it.        */
  confirm(xl > sizeof(".XXXXXX"))
  sprintf (tmp_path, "%s%s", fullpath, ".XXXXXX") ;

  /* Open file to configuration write. */
  tmp = mkstemp (tmp_path);
  if (tmp < 0)
    {
      free (tmp_path);
      close(sav);
      return NULL;
    }

  while((c = read (sav, buffer, sizeof(buffer))) > 0)
    write (tmp, buffer, c);

  close (sav);
  close (tmp);

  /* Make sure that have the required file status                       */
  if (chmod(tmp_path, CONFIGFILE_MASK) != 0)
    {
      unlink (tmp_path);
      free (tmp_path);
      return NULL;
    }

  /* Make <fullpath> be a name for the new file just created.           */
  ret = link (tmp_path, fullpath) ;

  /* Discard the temporary, now                                         */
  unlink (tmp_path) ;
  free (tmp_path) ;

  /* If link was successful, try to open -- otherwise, failed.          */
  return (ret == 0) ? fopen (fullpath, "r") : NULL ;
} ;

/*------------------------------------------------------------------------------
 * Read the given configuration file.
 *
 * May have a function to call after the first actual command is processed.
 * This mechanism supports the setting of qpthreads-ness by configuration file
 * command.
 *
 * In the qpthreads world:
 *
 *   * when the configuration is first read, this runs in the CLI thread
 *     (the main and only thread).
 *
 *   * when the configuration is reread, this runs in the command processor
 *     thread.
 *
 *     All consoles are shut down, so there can be no interference from that
 *     quarter.
 *
 * so all commands are executed directly.
 */
static void
vty_read_file (FILE *confp, struct cmd_element* first_cmd, bool ignore_warnings)
{
  enum cmd_return_code ret ;
  struct vty *vty ;
  qtime_t taking ;

  /* Set up configuration file reader VTY -- which buffers all output   */
  vty = vty_open(VTY_CONFIG_READ);
  vty->node = CONFIG_NODE;

  /* Make sure we have a suitable buffer, and set vty->buf to point at
   * it -- same like other command execution.
   */
  qs_need(&vty->vio->clx, VTY_BUFSIZ) ;
  vty->buf = qs_chars(&vty->vio->clx) ;

  taking = qt_get_monotonic() ;

  /* Execute configuration file                                         */
  ret = config_from_file (vty, confp, first_cmd, &vty->vio->clx,
                                                              ignore_warnings) ;

  taking = (qt_get_monotonic() - taking) / (QTIME_SECOND / 1000) ;

  zlog_info("Finished reading configuration in %d.%dsecs%s",
                            (int)(taking / 1000), (int)(taking % 1000),
                                   (ret == CMD_SUCCESS) ? "." : " -- FAILED") ;

  VTY_LOCK() ;

  if (ret != CMD_SUCCESS)
    {
      fprintf (stderr, "%% while processing line %u of the configuration:\n"
                       "%s", vty->lineno, vty->buf) ;

      switch (ret)
      {
        case CMD_WARNING:
          fprintf (stderr, "%% Warning...\n");
          break;

        case CMD_ERROR:
          fprintf (stderr, "%% Error...\n");
          break;

        case CMD_ERR_AMBIGUOUS:
           fprintf (stderr, "%% Ambiguous command.\n");
           break;

        case CMD_ERR_NO_MATCH:
          fprintf (stderr, "%% There is no such command.\n");
          break;

        case CMD_ERR_INCOMPLETE:
          fprintf (stderr, "%% Incomplete command.\n");
          break;

        default:
          fprintf(stderr, "%% (unknown cause %d)\n", ret) ;
          break ;
       } ;

      uty_out_fflush(vty->vio, stderr) ;  /* flush command output buffer   */

      exit (1);
    } ;

  uty_close(vty->vio) ;
  VTY_UNLOCK() ;
} ;

/*==============================================================================
 * Configuration node/state handling
 *
 * At most one VTY may hold the configuration symbol of power at any time.
 */

/*------------------------------------------------------------------------------
 * Attempt to gain the configuration symbol of power
 *
 * If succeeds, set the given node.
 *
 * Returns: true <=> now own the symbol of power.
 */
extern bool
vty_config_lock (struct vty *vty, enum node_type node)
{
  bool result;

  VTY_LOCK() ;

  if (vty_config == 0)
    {
      vty->vio->config = 1 ;
      vty_config       = 1 ;
    } ;

  result = vty->vio->config;

  if (result)
    vty->node = node ;

  VTY_UNLOCK() ;

  return result;
}

/*------------------------------------------------------------------------------
 * Give back the configuration symbol of power -- if own it.
 *
 * Set the given node -- which must be <= MAX_NON_CONFIG_NODE
 */
extern void
vty_config_unlock (struct vty *vty, enum node_type node)
{
  VTY_LOCK() ;
  uty_config_unlock(vty, node);
  VTY_UNLOCK() ;
}

/*------------------------------------------------------------------------------
 * Give back the configuration symbol of power -- if own it.
 *
 * Set the given node -- which must be <= MAX_NON_CONFIG_NODE
 */
extern void
uty_config_unlock (struct vty *vty, enum node_type node)
{
  VTY_ASSERT_LOCKED() ;
  if ((vty_config == 1) && (vty->vio->config == 1))
    {
      vty->vio->config = 0;
      vty_config       = 0;
    }

  assert(node <= MAX_NON_CONFIG_NODE) ;
  vty->node = node ;
} ;

/*==============================================================================
 * Commands
 *
 */
DEFUN_CALL (config_who,
       config_who_cmd,
       "who",
       "Display who is on vty\n")
{
  unsigned int i = 0;
  vty_io vio ;

  VTY_LOCK() ;

  vio = vio_list_base ;
  while (vio != NULL)   /* TODO: show only VTY_TERM ???         */
    {
      uty_out (vty, "%svty[%d] connected from %s.%s",
	       vio->config ? "*" : " ",
	       i, uty_get_name(vio), VTY_NEWLINE);
      vio = sdl_next(vio, vio_list) ;
    } ;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/* Move to vty configuration mode. */
DEFUN_CALL (line_vty,
       line_vty_cmd,
       "line vty",
       "Configure a terminal line\n"
       "Virtual terminal\n")
{
  VTY_LOCK() ;
  vty->node = VTY_NODE;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/* Set time out value. */
static int
exec_timeout (struct vty *vty, const char *min_str, const char *sec_str)
{
  unsigned long timeout = 0;

  VTY_LOCK() ;

  /* min_str and sec_str are already checked by parser.  So it must be
     all digit string. */
  if (min_str)
    {
      timeout = strtol (min_str, NULL, 10);
      timeout *= 60;
    }
  if (sec_str)
    timeout += strtol (sec_str, NULL, 10);

  vty_timeout_val = timeout;

  if (vty_term(vty) || vty_shell_serv(vty))
    uty_sock_set_timer(&vty->vio->sock, timeout) ;

  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (exec_timeout_min,
       exec_timeout_min_cmd,
       "exec-timeout <0-35791>",
       "Set timeout value\n"
       "Timeout value in minutes\n")
{
  return exec_timeout (vty, argv[0], NULL);
}

DEFUN_CALL (exec_timeout_sec,
       exec_timeout_sec_cmd,
       "exec-timeout <0-35791> <0-2147483>",
       "Set the EXEC timeout\n"
       "Timeout in minutes\n"
       "Timeout in seconds\n")
{
  return exec_timeout (vty, argv[0], argv[1]);
}

DEFUN_CALL (no_exec_timeout,
       no_exec_timeout_cmd,
       "no exec-timeout",
       NO_STR
       "Set the EXEC timeout\n")
{
  return exec_timeout (vty, NULL, NULL);
}

/* Set vty access class. */
DEFUN_CALL (vty_access_class,
       vty_access_class_cmd,
       "access-class WORD",
       "Filter connections based on an IP access list\n"
       "IP access list\n")
{
  VTY_LOCK() ;

  if (vty_accesslist_name)
    XFREE(MTYPE_VTY, vty_accesslist_name);

  vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[0]);

  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/* Clear vty access class. */
DEFUN_CALL (no_vty_access_class,
       no_vty_access_class_cmd,
       "no access-class [WORD]",
       NO_STR
       "Filter connections based on an IP access list\n"
       "IP access list\n")
{
  int result = CMD_SUCCESS;

  VTY_LOCK() ;
  if (! vty_accesslist_name || (argc && strcmp(vty_accesslist_name, argv[0])))
    {
      uty_out (vty, "Access-class is not currently applied to vty%s",
	       VTY_NEWLINE);
      result = CMD_WARNING;
    }
  else
    {
      XFREE(MTYPE_VTY, vty_accesslist_name);
      vty_accesslist_name = NULL;
    }

  VTY_UNLOCK() ;
  return result;
}

#ifdef HAVE_IPV6
/* Set vty access class. */
DEFUN_CALL (vty_ipv6_access_class,
       vty_ipv6_access_class_cmd,
       "ipv6 access-class WORD",
       IPV6_STR
       "Filter connections based on an IP access list\n"
       "IPv6 access list\n")
{
  VTY_LOCK() ;
  if (vty_ipv6_accesslist_name)
    XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);

  vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[0]);

  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/* Clear vty access class. */
DEFUN_CALL (no_vty_ipv6_access_class,
       no_vty_ipv6_access_class_cmd,
       "no ipv6 access-class [WORD]",
       NO_STR
       IPV6_STR
       "Filter connections based on an IP access list\n"
       "IPv6 access list\n")
{
  int result = CMD_SUCCESS;

  VTY_LOCK() ;

  if (! vty_ipv6_accesslist_name ||
      (argc && strcmp(vty_ipv6_accesslist_name, argv[0])))
    {
      uty_out (vty, "IPv6 access-class is not currently applied to vty%s",
	       VTY_NEWLINE);
      result = CMD_WARNING;
    }
  else
    {
      XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);

      vty_ipv6_accesslist_name = NULL;
    }

  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}
#endif /* HAVE_IPV6 */

/* vty login. */
DEFUN_CALL (vty_login,
       vty_login_cmd,
       "login",
       "Enable password checking\n")
{
  VTY_LOCK() ;
  no_password_check = 0;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (no_vty_login,
       no_vty_login_cmd,
       "no login",
       NO_STR
       "Enable password checking\n")
{
  VTY_LOCK() ;
  no_password_check = 1;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/* initial mode. */
DEFUN_CALL (vty_restricted_mode,
       vty_restricted_mode_cmd,
       "anonymous restricted",
       "Restrict view commands available in anonymous, unauthenticated vty\n")
{
  VTY_LOCK() ;
  restricted_mode = 1;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (vty_no_restricted_mode,
       vty_no_restricted_mode_cmd,
       "no anonymous restricted",
       NO_STR
       "Enable password checking\n")
{
  VTY_LOCK() ;
  restricted_mode = 0;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (service_advanced_vty,
       service_advanced_vty_cmd,
       "service advanced-vty",
       "Set up miscellaneous service\n"
       "Enable advanced mode vty interface\n")
{
  VTY_LOCK() ;
  host.advanced = 1;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (no_service_advanced_vty,
       no_service_advanced_vty_cmd,
       "no service advanced-vty",
       NO_STR
       "Set up miscellaneous service\n"
       "Enable advanced mode vty interface\n")
{
  VTY_LOCK() ;
  host.advanced = 0;
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (terminal_monitor,
       terminal_monitor_cmd,
       "terminal monitor",
       "Set terminal line parameters\n"
       "Copy debug output to the current terminal line\n")
{
  VTY_LOCK() ;
  uty_set_monitor(vty->vio, true);
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

DEFUN_CALL (terminal_no_monitor,
       terminal_no_monitor_cmd,
       "terminal no monitor",
       "Set terminal line parameters\n"
       NO_STR
       "Copy debug output to the current terminal line\n")
{
  VTY_LOCK() ;
  uty_set_monitor(vty->vio, false);
  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

ALIAS_CALL (terminal_no_monitor,
       no_terminal_monitor_cmd,
       "no terminal monitor",
       NO_STR
       "Set terminal line parameters\n"
       "Copy debug output to the current terminal line\n")

DEFUN_CALL (show_history,
       show_history_cmd,
       "show history",
       SHOW_STR
       "Display the session command history\n")
{
  int index;

  VTY_LOCK() ;

  for (index = vty->vio->hindex + 1; index != vty->vio->hindex;)
    {
      qstring line ;

      if (index == VTY_MAXHIST)
	{
	  index = 0;
	  continue;
	}

      line = vector_get_item(&vty->vio->hist, index) ;
      if (line != NULL)
	uty_out (vty, "  %s%s", line->char_body, VTY_NEWLINE);

      index++;
    }

  VTY_UNLOCK() ;
  return CMD_SUCCESS;
}

/*==============================================================================
 * Output the current configuration
 *
 * Returns: CMD_SUCCESS
 */
static int
vty_config_write (struct vty *vty)
{
  vty_out (vty, "line vty%s", VTY_NEWLINE);

  if (vty_accesslist_name)
    vty_out (vty, " access-class %s%s",
	     vty_accesslist_name, VTY_NEWLINE);

  if (vty_ipv6_accesslist_name)
    vty_out (vty, " ipv6 access-class %s%s",
	     vty_ipv6_accesslist_name, VTY_NEWLINE);

  /* exec-timeout */
  if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
    vty_out (vty, " exec-timeout %ld %ld%s",
	     vty_timeout_val / 60,
	     vty_timeout_val % 60, VTY_NEWLINE);

  /* login */
  if (no_password_check)
    vty_out (vty, " no login%s", VTY_NEWLINE);

  if (restricted_mode != restricted_mode_default)
    {
      if (restricted_mode_default)
        vty_out (vty, " no anonymous restricted%s", VTY_NEWLINE);
      else
        vty_out (vty, " anonymous restricted%s", VTY_NEWLINE);
    }

  vty_out (vty, "!%s", VTY_NEWLINE);

  return CMD_SUCCESS;
}

/*==============================================================================
 * The cwd at start-up.
 */

/*------------------------------------------------------------------------------
 * Save cwd
 *
 * This is done early in the morning so that any future operations on files
 * can use the original cwd if required.
 */
static void
vty_save_cwd (void)
{
  char cwd[MAXPATHLEN];
  char *c;

  c = getcwd (cwd, MAXPATHLEN);

  if (!c)
    {
      chdir (SYSCONFDIR);
      getcwd (cwd, MAXPATHLEN);
    }

  vty_cwd = XSTRDUP(MTYPE_TMP, cwd) ;
} ;

/*------------------------------------------------------------------------------
 * Get cwd as at start-up.  Never changed -- so no locking required.
 */
char *
vty_get_cwd ()
{
  return vty_cwd;
}

/*==============================================================================
 * Access functions for VTY values, where locking is or might be required.
 */

bool
vty_shell (struct vty *vty)
{
  bool result;
  VTY_LOCK() ;
  result = (vty->vio->type == VTY_SHELL) ;
  VTY_UNLOCK() ;
  return result;
}

bool
vty_term(struct vty *vty)
{
  bool result;
  VTY_LOCK() ;
  result = (vty->vio->type == VTY_TERM);
  VTY_UNLOCK() ;
  return result;
}

bool
vty_shell_serv (struct vty *vty)
{
  bool result;
  VTY_LOCK() ;
  result = (vty->vio->type == VTY_SHELL_SERV);
  VTY_UNLOCK() ;
  return result;
}

enum node_type
vty_get_node(struct vty *vty)
{
  int result;
  VTY_LOCK() ;
  result = vty->node;
  VTY_UNLOCK() ;
  return result;
}

void
vty_set_node(struct vty *vty, enum node_type node)
{
  VTY_LOCK() ;
  vty->node = node;
  VTY_UNLOCK() ;
}

void
vty_set_lines(struct vty *vty, int lines)
{
  VTY_LOCK() ;
  vty->vio->lines     = lines;
  vty->vio->lines_set = 1 ;
  uty_set_height(vty->vio) ;
  VTY_UNLOCK() ;
}

/*==============================================================================
 *
 */
const char* wordlist[] =
  {
      "Lorem",
      "ipsum",
      "dolor",
      "magna",
      "vita",
      "brevis",
      "Aliquot",
      "in",
      "tempura",
      "mores",
      "ad",
      "Astronomica",
      "per",
      "impedimenta",
      "quod",
      "et",
      "sed",
      "semper",
      "ut",
      "Elisium",
      "est",
  };


DEFUN (delay_secs,
       delay_secs_cmd,
       "delay <0-600> secs <0-10000> lines",
       "Delay for a number of seconds and spit out a number of lines\n"
       "Delay time\n"
       "Delay time units\n"
       "How much to output\n"
       "Output units\n")
{
  unsigned long delay ;
  unsigned long lines ;

  unsigned long unit ;

  delay = strtol(argv[0], NULL, 10) ;
  lines = strtol(argv[1], NULL, 10) ;

  vty_out(vty, "delay %d secs %d lines\n", (int)delay, (int)lines) ;

  unit = (lines * 100) / delay ;

  while (delay--)
    {
      char  buf[200] ;
      char* e ;
      int   n ;
      int   w = sizeof(wordlist) / sizeof(char*) ;

      sleep(1) ;

      n = ((rand() % (unit + 1)) + (unit / 2)) / 100 ;

      if ((n > (int)lines) || (delay == 0))
        n = lines ;

      lines -= n ;

      while (n--)
        {
          char* q ;
          const char* p ;
          int a ;

          q = buf ;
          e = buf + (rand() % 120) + 30 ;

          if ((rand() % 6) == 0)
            e = buf ;

          a = (rand() % 4) == 1 ;
          while (q < e)
            {
              int s ;
              s = 0 ;
              if (a == 1)
                s = (rand() % 5) + 1 ;
              else if (a > 1)
                s = 1 ;

              while (s--)
                *q++ = ' ' ;

              p = wordlist[rand() % w] ;
              while (*p != '\0')
                *q++ = *p++ ;

              a = (rand() % 4) + 1 ;
            } ;

          *q++ = '\n' ;
          *q++ = '\0' ;

          vty_out(vty, buf) ;
        } ;
    } ;

  return CMD_SUCCESS;
}

/*==============================================================================
 * The VTY command nodes
 */

struct cmd_node vty_node =
{
  VTY_NODE,
  "%s(config-line)# ",
  1,
};

/*------------------------------------------------------------------------------
 * Install vty's own commands like `who' command.
 */
static void
uty_init_commands (void)
{
  VTY_ASSERT_LOCKED() ;

  install_node (&vty_node, vty_config_write);

  install_element (VIEW_NODE, &delay_secs_cmd);
  install_element (ENABLE_NODE, &delay_secs_cmd);

  install_element (RESTRICTED_NODE, &config_who_cmd);
  install_element (RESTRICTED_NODE, &show_history_cmd);
  install_element (VIEW_NODE, &config_who_cmd);
  install_element (VIEW_NODE, &show_history_cmd);
  install_element (ENABLE_NODE, &config_who_cmd);
  install_element (CONFIG_NODE, &line_vty_cmd);
  install_element (CONFIG_NODE, &service_advanced_vty_cmd);
  install_element (CONFIG_NODE, &no_service_advanced_vty_cmd);
  install_element (CONFIG_NODE, &show_history_cmd);
  install_element (ENABLE_NODE, &terminal_monitor_cmd);
  install_element (ENABLE_NODE, &terminal_no_monitor_cmd);
  install_element (ENABLE_NODE, &no_terminal_monitor_cmd);
  install_element (ENABLE_NODE, &show_history_cmd);

  install_default (VTY_NODE);
  install_element (VTY_NODE, &exec_timeout_min_cmd);
  install_element (VTY_NODE, &exec_timeout_sec_cmd);
  install_element (VTY_NODE, &no_exec_timeout_cmd);
  install_element (VTY_NODE, &vty_access_class_cmd);
  install_element (VTY_NODE, &no_vty_access_class_cmd);
  install_element (VTY_NODE, &vty_login_cmd);
  install_element (VTY_NODE, &no_vty_login_cmd);
  install_element (VTY_NODE, &vty_restricted_mode_cmd);
  install_element (VTY_NODE, &vty_no_restricted_mode_cmd);
#ifdef HAVE_IPV6
  install_element (VTY_NODE, &vty_ipv6_access_class_cmd);
  install_element (VTY_NODE, &no_vty_ipv6_access_class_cmd);
#endif /* HAVE_IPV6 */
} ;