|
root / base / usr / src / cmd / tsol / misc
misc Plain Text 2020 lines 45.1 KB
   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
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
#ident	"%Z%%M%	%I%	%E% SMI"
#

#
# cmd/tsol/misc
#
SCRIPT=txzonemgr
ETCTSOLFILES=relabel

include ../../Makefile.cmd

$(ROOTETCTSOL)/relabel : FILEMODE= 0755

.KEEP_STATE:

all: $(SCRIPT) $(ETCTSOLFILES)

install: all $(ROOTUSRSBINSCRIPT) $(ROOTETCTSOLFILES)

clean:
	$(RM) $(SCRIPT) $(ETCTSOLFILES)

lint:

_msg:

include ../Makefile.targ
#!/bin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# This program is invoked to do the actual file transfer
# associated with an invocation of the setflabel(3TSOL) function.
#
# It executes in the global zone with the user's identity and
# basic privileges plus the file_dac_search privilege.  This
# script should not not assume that stdio is available or that
# any particular environment variables are set.  In particular,
# the DISPLAY variable will not normally be pre-set.
#
# Authorization checks and zone limit privilege checks
# are done before calling this script. Auditing is done
# upon return.
#
##############################################################
#
# Calling sequence:
#
# $1 is the global zone real pathname of the source file
#
# $2 is the global zone real destination pathname
#
# Exit status:
#
# 0 on success
# 1 on error
#
##############################################################
#
# This script can be customized or replaced to perform
# additional processing such as tranquility checks, dirty
# word filtering, copying instead of moving, etc.
#
# By default it does a check to determine if the source file
# is in use by calling fuser(1). However, this check
# does not work for filesystems that were automounted in
# non-global zones.
#
# Perform a simple tranquility check
#
inuse=`/usr/sbin/fuser $1 2>&1 | /usr/bin/cut -d ":" -f2`
if [ $inuse ]; then
#
#	file is in use
#
	exit 1
else
#
# Perform an inter-zone move of the data
	/bin/mv $1 $2
	exit $?
fi
#!/bin/ksh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2014 Garrett D'Amore
#
#

# This script provides a simple GUI for managing labeled zones.
# It provides contextual menus which provide appropriate choices.
# It must be run in the global zone as root.

# These arguments are accepted, and will result in non-interactive
# (text-only) mode:
#
#	txzonemgr [-c | -d[f]]
#
#	-c	create default zones
#	-d	destroy all zones; prompts for confirmation unless
#		the -f flag is also specified
#	-f	force
#

# DISP - use GUI (otherwise use non-interactive mode)
DISP=1
# CREATEDEF - make default zones (non-interactive)
CREATEDEF=0
# DESTROYZONES - tear down all zones (non-interactive)
DESTROYZONES=0
# FORCE - force
FORCE=0

NSCD_PER_LABEL=0
NSCD_INDICATOR=/var/tsol/doors/nscd_per_label
if [ -f $NSCD_INDICATOR ] ; then
	NSCD_PER_LABEL=1
fi

myname=$(basename $0)

TXTMP=/tmp/txzonemgr
TNRHTP=/etc/security/tsol/tnrhtp
TNRHDB=/etc/security/tsol/tnrhdb
TNZONECFG=/etc/security/tsol/tnzonecfg
PUBZONE=public
INTZONE=internal

PATH=/usr/bin:/usr/sbin:/usr/lib export PATH
title="Labeled Zone Manager 2.1"

msg_defzones=$(gettext "Create default zones using default settings?")
msg_confirmkill=$(gettext "OK to destroy all zones?")
msg_continue=$(gettext "(exit to resume $(basename $0) when ready)")
msg_getlabel=$(gettext "Select a label for the")
msg_getremote=$(gettext "Select a remote host or network from the list below:")
msg_getnet=$(gettext "Select a network configuration for the")
msg_getzone=$(gettext "Select a zone from the list below:
(select global for zone creation and shared settings)")
msg_getcmd=$(gettext "Select a command from the list below:")
msg_inuse=$(gettext "That label is already assigned\nto the")
msg_getmin=$(gettext "Select the minimum network label for the")
msg_getmax=$(gettext "Select the maximum network label for the")
msg_badip=$(gettext " is not a valid IP address")


process_options()
{
	typeset opt optlist

	optlist='cdf'

	while getopts ":$optlist" opt
	do
		case $opt in
		c)	CREATEDEF=1
			DISP=0
			;;
		d)	DESTROYZONES=1
			DISP=0
			;;
		f)	FORCE=1
			;;
		*)	gettext "invalid option -$OPTARG\n"
			usage
			return 2
			;;
		esac
	done

	if [ $CREATEDEF -eq 1 -a $DESTROYZONES -eq 1 ] ; then
		gettext "cannot combine options -c and -d\n"
		usage
		return 2
	fi
	if [ $CREATEDEF -eq 1 -a $FORCE -eq 1 ] ; then
		gettext "option -f not allowed with -c\n"
		usage
		return 2
	fi
	if [ $FORCE -eq 1 -a $CREATEDEF -eq 0 -a $DESTROYZONES -eq 0 ] ; then
		gettext "option -f specified without any other options\n"
		usage
		return 2
	fi

	shift $((OPTIND - 1))
	if [ "x$1" != "x" ] ; then
		usage
		return 2
	fi

	return 0
}

usage() {
	gettext "usage: $myname [-c | -d[f]]\n"
}

consoleCheck() {
	if [ $zonename != global ] ; then
		zconsole=$(pgrep -f "zlogin -C $zonename")
		if [ $? != 0 ] ; then
			console="Zone Console...\n"
		fi
	fi
}

labelCheck() {
	hexlabel=$(grep "^$zonename:" $TNZONECFG|cut -d : -f2);
	if [[ $hexlabel ]] ; then
		label=
		if [ $zonename = global ] ; then
			template="admin_low"
			addcipsohost="Add Multilevel Access to Remote Host...\n"
			removecipsohost="Remove Multilevel Access to Remote Host...\n"
			setmlps="Configure Multilevel Ports...\n"
		else
			template=${zonename}_unlab
			addcipsohost=
			removecipsohost=
			setmlps=

			net=$(zonecfg -z $zonename info net)
			if [[ -n $net ]] ; then
				setmlps="Configure Multilevel Ports...\n"
			elif [ $zonestate = configured ] ; then
				addnet="Configure Network Interfaces...\n"
			fi
		fi
		addremotehost="Add Single-level Access to Remote Host...\n"
		remotes=$(grep -v "^#" $TNRHDB|grep $template)
		if [ $? = 0 ] ; then
			removeremotehost="Remove Single-level Access to Remote Host...\n"
		else
			removeremotehost=
		fi
	else
		label="Select Label...\n"
		addremotehost=
		removeremotehost=
		addcipsohost=
		removecipsohost=
		setmlps=
	fi
}

cloneCheck() {
	set -A zonelist
	integer clone_cnt=0
	for p in $(zoneadm list -ip) ; do
		z=$(echo "$p"|cut -d : -f2)
		s=$(echo "$p"|cut -d : -f3)
		if [ $z = $zonename ] ; then
			continue
		elif [ $s = "installed" ] ; then
			zonelist[clone_cnt]=$z
			clone_cnt+=1
		fi
	done
	if [ $clone_cnt -gt 0 ] ; then
		clone="Clone...\n"; \
	fi
}

relabelCheck() {
	macstate=$(zonecfg -z $zonename info|grep win_mac_write)
	if [[ -n $macstate ]] ; then
		permitrelabel="Deny Relabeling\n"
	else
		permitrelabel="Permit Relabeling\n"
	fi
}

autobootCheck() {
	bootmode=$(zonecfg -z $zonename info autoboot)
	if [[ $bootmode == 'autoboot: true' ]] ; then
		autoboot="Set Manual Booting\n"
	else
		autoboot="Set Automatic Booting\n"
	fi
}

newZone() { 
		if [[ ! -n $zonename ]] ; then
			zonename=$(zenity --entry \
			    --title="$title" \
			    --width=330 \
			    --entry-text="" \
			    --text="Enter Zone Name: ")

			if [[ ! -n $zonename ]] ; then
				zonename=global
				return
			fi
		fi
		zonecfg -z $zonename "create -t SUNWtsoldef;\
		     set zonepath=/zone/$zonename"
}

removeZoneBEs() {
	delopt=$*

	zfs list -H $ZDSET/$zonename 1>/dev/null 2>&1
	if [ $? = 0 ] ; then
		for zbe in $(zfs list -rHo name $ZDSET/$zonename|grep ROOT/zbe) ; do
			zfs destroy $delopt $zbe
		done
	fi
}

updateTemplate () {
	if [ $hostType = cipso ] ; then
		template=${zonename}_cipso
		deflabel=
	else
		template=${zonename}_unlab
		deflabel="def_label=${hexlabel};"
	fi

	tnzone=$(grep "^${template}:" $TNRHTP 2>/dev/null)
	if [ $? -eq 0 ] ; then
		sed -e "/^${template}/d" $TNRHTP > $TXTMP/tnrhtp.$$ 2>/dev/null
		mv $TXTMP/tnrhtp.$$ $TNRHTP
	fi
	print "${template}:host_type=${hostType};doi=1;min_sl=${minlabel};max_sl=${maxlabel};$deflabel" >> $TNRHTP
	tnctl -t $template
}
		
setTNdata () {
	tnzline="$zonename:${hexlabel}:0::"
	grep "^$tnzline" $TNZONECFG 1>/dev/null 2>&1
	if [ $? -eq 1 ] ; then
		print "$tnzline" >> $TNZONECFG
	fi

	#
	# Add matching entries in tnrhtp if necessary
	#
	minlabel=admin_low
	maxlabel=admin_high
	hostType=cipso
	updateTemplate

	hostType=unlabeled
	updateTemplate
}

selectLabel() {
	hexlabel=$(tgnome-selectlabel \
		--title="$title" \
		--text="$msg_getlabel $zonename zone:" \
		--min="${DEFAULTLABEL}"  \
		--default="${DEFAULTLABEL}"  \
		--max=$(chk_encodings -X) \
		--accredcheck=yes \
		--mode=sensitivity \
		--format=internal)
	if [ $? = 0 ] ; then
		x=$(grep -i :{$hexlabel}: $TNZONECFG)
		if [ $? = 0 ] ; then
			z=$(print $x|cut -d : -f1)
			x=$(zenity --error \
			    --title="$title" \
			    --text="$msg_inuse $z zone.")
		else
			setTNdata
		fi
	fi	
}

getLabelRange() {
	deflabel=$(hextoalabel $hexlabel)
	minlabel=$(tgnome-selectlabel \
		--title="$title" \
		--text="$msg_getmin $zonename zone:" \
		--min="${DEFAULTLABEL}"  \
		--max="$deflabel" \
		--default="$hexlabel" \
		--accredcheck=no \
		--mode=sensitivity \
		--format=internal)
	[ $? != 0 ] && return
	
	maxlabel=$(tgnome-selectlabel \
		--title="$title" \
		--text="$msg_getmax $zonename zone:" \
		--min="$deflabel"  \
		--max=$(chk_encodings -X) \
		--default="$hexlabel" \
		--accredcheck=no \
		--mode=sensitivity \
		--format=internal)
	[ $? != 0 ] && return

	hostType=cipso
	updateTemplate
}


encryptionValues() {
	echo $(zfs get 2>&1 | grep encryption | sed -e s/^.*YES// -e s/\|//g)
}

getPassphrase() {
	pass1=$(zenity --entry --title="$title" --text="Enter passphrase:" \
	    --width=330 --hide-text)
	pass2=$(zenity --entry --title="$title" --text="Re-enter passphrase:" \
	    --width=330 --hide-text)
	if [[ "$pass1" != "$pass2" ]]; then
		zenity --error --title="$title" \
			--text="Passphrases do not match"
		return ""
	fi
	file=$(mktemp)
	echo "$pass1" > $file
	echo "$file"
}

createZDSET() {
	options=$1
	pool=${2%%/*}

	# First check if ZFS encrytption support is available
	pversion=$(zpool list -H -o version $pool)
	cversion=$(zpool upgrade -v | grep Crypto | awk '{ print $1 }')
	if (( cversion == 0 || pversion < cversion )); then
		zfs create $options $ZDSET
		return
	fi

	encryption=$(zenity --list --title="$title" --height=320 \
		--text="Select cipher for encryption of all labels:" \
		--column="encryption" $(encryptionValues))

	if [[ $? != 0 || $encryption == "off" ]]; then
		zfs create $options $ZDSET
		return
	fi

	format=$(zenity --list --title="$title" \
		--text "Select encryption key source:" \
		--column="Key format and location" \
		"Passphrase" "Generate Key in file")
	[ $? != 0 ] && exit 

	if [[ $format == "Passphrase" ]]; then
		file=$(getPassphrase)
		if [[ $file == "" ]]; then
			exit
		fi
		keysource="passphrase,file://$file"
		removefile=1;
	elif [[ $format == "Generate Key in file" ]]; then
		file=$(zenity --file-selection \
			--title="$title: Location of key file" \
			--save --confirm-overwrite)
		[ $? != 0 ] && exit 
		if [[ $encryption == "on" ]]; then
			keylen=128
		else
			t=${encryption#aes-} && keylen=${t%%-*}
		fi
		pktool genkey keystore=file keytype=aes \
		    keylen=$keylen outkey=$file
		keysource="raw,file:///$file"
	fi

	options="$options -o encryption=$encryption -o keysource=$keysource"
	zfs create $options $ZDSET
	if (( removefile == 1 )); then
		zfs set keysource=passphrase,prompt $ZDSET
		rm $file
	fi
}


initialize() {
	zonepath=$(zoneadm -z $zonename list -p|cut -d : -f4)
	ZONE_ETC_DIR=$zonepath/root/etc
	SYSIDCFG=${ZONE_ETC_DIR}/sysidcfg

	if [ -f /var/ldap/ldap_client_file ] ; then
		ldapaddress=$(ldapclient list | \
		    grep "^NS_LDAP_SERVERS" | cut -d " " -f2)
		print "name_service=LDAP {" > ${SYSIDCFG}
		domain=$(domainname)
		print "domain_name=$domain" >> ${SYSIDCFG}
		profName=$(ldapclient list | \
		    grep "^NS_LDAP_PROFILE" | cut -d " " -f2)
		proxyPwd=$(ldapclient list | \
		    grep "^NS_LDAP_BINDPASSWD" | cut -d " " -f2)
		proxyDN=$(ldapclient list | \
		    grep "^NS_LDAP_BINDDN" | cut -d " " -f 2)
		if [ "$proxyDN" ] ; then
			print "proxy_dn=\"$proxyDN\"" >> ${SYSIDCFG}
			print "proxy_password=\"$proxyPwd\"" >> ${SYSIDCFG}
		fi
		print "profile=$profName" >> ${SYSIDCFG}
		print "profile_server=$ldapaddress }" >> ${SYSIDCFG}
		cp /etc/nsswitch.conf $ZONE_ETC_DIR/nsswitch.ldap
	else
		print "name_service=NONE" > ${SYSIDCFG}
		fi
	print "security_policy=NONE" >> ${SYSIDCFG}
	locale=$(locale|grep LANG | cut -d "=" -f2)
	if [[ -z $locale ]] ; then
		locale="C"
	fi
	print "system_locale=$locale" >> ${SYSIDCFG}
	timezone=$(grep "^TZ" /etc/default/init|cut -d "=" -f2)
	print "timezone=$timezone" >> ${SYSIDCFG}
	print "terminal=vt100" >> ${SYSIDCFG}
	rootpwd=$(grep "^root:" /etc/shadow|cut -d : -f2)
 
#	There are two problems with setting the root password:
#		The zone's shadow file may be read-only
#		The password contains unparsable characters
#	so the following line is commented out until this is resolved.

	#print "root_password=$rootpwd" >> ${SYSIDCFG}
	print "nfs4_domain=dynamic" >> ${SYSIDCFG}
	print "network_interface=PRIMARY {" >> ${SYSIDCFG}

	net=$(zonecfg -z $zonename info net)
	ipType=$(zonecfg -z $zonename info ip-type|cut -d" " -f2)
	if [ $ipType = exclusive ] ; then
		hostname=$(zenity --entry \
		    --title="$title" \
		    --width=330 \
		    --text="${zonename}0: Enter Hostname or dhcp: ")
		[ $? != 0 ] && return

		if [ $hostname = dhcp ] ; then
			print "dhcp" >> ${SYSIDCFG}
		else
			print "hostname=$hostname" >> ${SYSIDCFG}
			ipaddr=$(getent hosts $hostname|cut -f1)
			if [ $? != 0 ] ; then
				ipaddr=$(zenity --entry \
				    --title="$title" \
				    --text="$nic: Enter IP address: " \
				    --entry-text a.b.c.d)
				[ $? != 0 ] && return
				
				validateIPaddr
				if [[ -z $ipaddr ]] ; then
					return
				fi
			fi
			print "ip_address=$ipaddr" >> ${SYSIDCFG}
			getNetmask
			print "netmask=$nm" >> ${SYSIDCFG}
			print "default_route=none" >> ${SYSIDCFG}
			template=${zonename}_cipso
			cidr=32
			updateTnrhdb
		fi
	elif [[ -n $net ]] ; then
		hostname=$(hostname)
		hostname=$(zenity --entry \
		    --title="$title" \
		    --width=330 \
		    --text="Enter Hostname: " \
		    --entry-text $hostname)
		[ $? != 0 ] && return
		
		print "hostname=$hostname" >> ${SYSIDCFG}
		ipaddr=$(getent hosts $hostname|cut -f1)
		if [ $? = 0 ] ; then
			print "ip_address=$ipaddr" >> ${SYSIDCFG}
		fi
	else
		getAllZoneNICs
		for i in ${aznics[*]} ; do
			ipaddr=$(ifconfig $i|grep inet|cut -d " " -f2)
		done
		print "hostname=$(hostname)" >> ${SYSIDCFG}
		print "ip_address=$ipaddr" >> ${SYSIDCFG}
	fi
		
	print "protocol_ipv6=no }" >> ${SYSIDCFG}
	cp /etc/default/nfs ${ZONE_ETC_DIR}/default/nfs
	touch ${ZONE_ETC_DIR}/.NFS4inst_state.domain
}

clone() {
	image=$1
	if [[ -z $image ]] ; then
		msg_clone=$(gettext "Clone the $zonename zone using a
snapshot of one of the following halted zones:")
		image=$(zenity --list \
		    --title="$title" \
		    --text="$msg_clone" \
		    --height=300 \
		    --width=330 \
		    --column="Installed Zones" ${zonelist[*]})
	fi

	if [[ -n $image ]] ; then
		removeZoneBEs
		zoneadm -z $zonename clone $image

		if [ $NSCD_PER_LABEL = 0 ] ; then
			sharePasswd $zonename
		else
			unsharePasswd $zonename
		fi

		ipType=$(zonecfg -z $zonename info ip-type|cut -d" " -f2)
		if [ $ipType = exclusive ] ; then
			zoneadm -z $zonename ready
			zonepath=$(zoneadm -z $zonename list -p|cut -d : -f4)
			sys-unconfig -R $zonepath/root 2>/dev/null
			initialize
			zoneadm -z $zonename halt
		fi
	fi
}

install() {
	removeZoneBEs
	if [ $DISP -eq 0 ] ; then
		gettext "installing zone $zonename ...\n"
		zoneadm -z $zonename install
	else
		# sleep is needed here to avoid occasional timing
		# problem with gnome-terminal display...
		sleep 2
		gnome-terminal \
		    --title="$title: Installing $zonename zone" \
		    --command "zoneadm -z $zonename install" \
		    --disable-factory \
		    --hide-menubar
	fi

	zonestate=$(zoneadm -z $zonename list -p | cut -d : -f 3)
	if [ $zonestate != installed ] ; then
		gettext "error installing zone $zonename.\n"
		return 1
	fi

	if [ $NSCD_PER_LABEL = 0 ] ; then
		sharePasswd $zonename
	else
		unsharePasswd $zonename
	fi

	zoneadm -z $zonename ready
	zonestate=$(zoneadm -z $zonename list -p | cut -d : -f 3)
	if [ $zonestate != ready ] ; then
		gettext "error making zone $zonename ready.\n"
		return 1
	fi

	initialize
	zoneadm -z $zonename halt
}

delete() {
	delopt=$*

	# if there is an entry for this zone in tnzonecfg, remove it
	# before deleting the zone.

	tnzone=$(grep "^$zonename:" $TNZONECFG 2>/dev/null)
	if [ -n "${tnzone}" ] ; then
		sed -e "/^$zonename:/d" $TNZONECFG > \
		    $TXTMP/tnzonefg.$$ 2>/dev/null
		mv $TXTMP/tnzonefg.$$ $TNZONECFG
	fi

	for tnzone in $(grep ":${zonename}_unlab" $TNRHDB 2>/dev/null) ; do
		tnctl -dh "$tnzone"
		sed -e "/:${zonename}_unlab/d" $TNRHDB > \
		    $TXTMP/tnrhdb.$$ 2>/dev/null
		mv $TXTMP/tnrhdb.$$ $TNRHDB
	done

	for tnzone in $(grep "^${zonename}_unlab:" $TNRHTP 2>/dev/null) ; do
		tnctl -dt ${zonename}_unlab
		sed -e "/^${zonename}_unlab:/d" $TNRHTP > \
		    $TXTMP/tnrhtp.$$ 2>/dev/null
		mv $TXTMP/tnrhtp.$$ $TNRHTP
	done

	for tnzone in $(grep ":${zonename}_cipso" $TNRHDB 2>/dev/null) ; do
		tnctl -dh "$tnzone"
		sed -e "/:${zonename}_cipso/d" $TNRHDB > \
		    $TXTMP/tnrhdb.$$ 2>/dev/null
		mv $TXTMP/tnrhdb.$$ $TNRHDB
	done

	for tnzone in $(grep "^${zonename}_cipso:" $TNRHTP 2>/dev/null) ; do
		tnctl -dt ${zonename}_cipso
		sed -e "/^${zonename}_cipso:/d" $TNRHTP > \
		    $TXTMP/tnrhtp.$$ 2>/dev/null
		mv $TXTMP/tnrhtp.$$ $TNRHTP
	done

	zonecfg -z $zonename delete -F

	removeZoneBEs $delopt
	for snap in $(zfs list -Ho name -t snapshot|grep "\@${zonename}_snap") ; do
		zfs destroy -R $snap
	done
}

validateIPaddr () {
	OLDIFS=$IFS
	IFS=.
	integer octet_cnt=0
	integer dummy
	set -A octets $ipaddr
	IFS=$OLDIFS
	if [ ${#octets[*]} == 4 ] ; then
		while (( octet_cnt < ${#octets[*]} )); do
			dummy=${octets[octet_cnt]}
			if [ $dummy = ${octets[octet_cnt]} ] ; then
				if (( dummy >= 0 && \
				    dummy < 256 )) ; then
					octet_cnt+=1
					continue
				fi
			else
			x=$(zenity --error \
			    --title="$title" \
			    --text="$ipaddr $msg_badip")
			ipaddr=
			return
			fi
		done
	else
		x=$(zenity --error \
		    --title="$title" \
		    --text="$ipaddr $msg_badip")
		ipaddr=
	fi
}

getAllZoneNICs(){
	integer count=0
	for i in $(ifconfig -a4|grep  "^[a-z].*:")
	do
		print "$i" |grep "^[a-z].*:" >/dev/null 2>&1
		[ $? -eq 1 ] && continue
		
		i=${i%:} # Remove colon after interface name
		for j in $(ifconfig $i)
		do
			case $j in
				all-zones)
					aznics[count]=$i
					count+=1
					;;
			esac
		done
        done
}

getNetmask() {
	cidr=
	nm=$(zenity --entry \
	    --title="$title" \
	    --width=330 \
	    --text="$ipaddr: Enter netmask: " \
	    --entry-text 255.255.255.0)
	[ $? != 0 ] && return;

	cidr=$(perl -e 'use Socket; print unpack("%32b*",inet_aton($ARGV[0])), "\n";' $nm)
}

addNet() {
	getIPaddr
	if [[ -z $ipaddr ]] ; then
		return;
	fi
	getNetmask
	if [[ -z $cidr ]] ; then
		return;
	fi
	zonecfg -z $zonename "add net; \
	    set address=${ipaddr}/${cidr}; \
	    set physical=$nic; \
	    end"
	template=${zonename}_cipso
	cidr=32
	updateTnrhdb
}

getAttrs() {
	zone=global
	type=ignore
	for j in $(ifconfig $nic)
	do
		case $j in
			inet) type=$j;;
			zone) type=$j;;
			all-zones) zone=all-zones;;
			flags*) flags=$j;;
			*) case $type in
				inet) ipaddr=$j ;;
				zone) zone=$j ;;
				*) continue ;;
			   esac;
			   type=ignore;;
		esac
	done
	if [[ $flags == ~(E).UP, ]] ; then
		updown=Up
	else
		updown=Down
	fi
	if [[ $nic == ~(E).: ]] ; then
		linktype=logical
	else
		vnic=$(dladm show-vnic -po link $nic 2>/dev/null)
		if [[ -n $vnic ]] ; then
			linktype=virtual
		else
			linktype=physical
		fi
	fi
	if [ $ipaddr != 0.0.0.0 ] ; then
		x=$(grep "^${ipaddr}[^0-9]" $TNRHDB)
		if [ $? = 1 ] ; then
			template=cipso
			cidr=32
			updateTnrhdb
		else
			template=$(print "$x"|cut -d : -f2)
		fi
	else
		template="..."
		ipaddr="..."
	fi
}
deleteTnrhdbEntry() {
	remote=$(grep "^${ipaddr}[^0-9]" $TNRHDB)
	if [ $? = 0 ] ; then
		ip=$(print $remote|cut -d "/" -f1)
			if [[ $remote == ~(E)./ ]] ; then
				pr=$(print $remote|cut -d "/" -f2)
				remote="$ip\\/$pr"
			fi
		sed -e "/^${remote}/d" $TNRHDB > /tmp/tnrhdb.$$ 2>/dev/null
		mv /tmp/tnrhdb.$$ $TNRHDB
	fi
}

updateTnrhdb() {
	deleteTnrhdbEntry
	if [[ -n $cidr ]] ; then
		print "${ipaddr}/$cidr:$template" >> $TNRHDB
		tnctl -h ${ipaddr}/$cidr:$template
	else
		print "${ipaddr}:$template" >> $TNRHDB
		tnctl -h ${ipaddr}:$template
	fi
}

getIPaddr() {
        hostname=$(zenity --entry \
            --title="$title" \
	    --width=330 \
            --text="$nic: Enter Hostname: ")

        [ $? != 0 ] && return

	ipaddr=$(getent hosts $hostname|cut -f1)
        if [[ -z $ipaddr ]] ; then
		ipaddr=$(zenity --entry \
		    --title="$title" \
		    --text="$nic: Enter IP address: " \
		    --entry-text a.b.c.d)
		[ $? != 0 ] && return
		validateIPaddr
	fi

}

addHost() {
	# Update hosts
        if [[ -z $ipaddr ]] ; then
               return;
	fi
	grep "^${ipaddr}[^0-9]" /etc/inet/hosts >/dev/null
	if [ $? -eq 1 ] ; then
		print "$ipaddr\t$hostname" >> /etc/inet/hosts
	fi

	template=cipso
	cidr=32
	updateTnrhdb

	ifconfig $nic $ipaddr netmask + broadcast +
	#
	# TODO: better integration with nwam
	# TODO: get/set netmask for IP address
	#
	print $hostname > /etc/hostname.$nic
}

createInterface() {
	msg=$(ifconfig $nic addif 0.0.0.0)
	$(zenity --info \
	    --title="$title" \
	    --text="$msg" )
	nic=$(print "$msg"|cut -d" " -f5)

}
		    
createVNIC() {
	if [ $zonename != global ] ; then
		vnicname=${zonename}0
	else
		vnicname=$(zenity --entry \
		    --title="$title" \
		    --width=330 \
		    --entry-text="" \
		    --text="Enter VNIC Name: ")

		if [[ ! -n $vnicname ]] ; then
			return
		fi
	fi
	x=$(dladm show-vnic|grep "^$vnicname " )
	if [[ ! -n $x ]] ; then
		dladm create-vnic -l $nic $vnicname
	fi
	if [ $zonename = global ] ; then
		ifconfig $vnicname plumb
	else
		zonecfg -z $zonename "add net; \
		    set physical=$vnicname; \
		    end"
	fi
	nic=$vnicname
}

shareInterface() {
	#
	# TODO: better integration with nwam
	#
	ifconfig $nic all-zones;\
	if_file=/etc/hostname.$nic
	sed q | sed -e "s/$/ all-zones/" < $if_file >$TXTMP/txnetmgr.$$
	mv $TXTMP/txnetmgr.$$ $if_file
}

unshareInterface() {
	#
	# TODO: better integration with nwam
	#
	ifconfig $nic -zone;\
	if_file=/etc/hostname.$nic
	sed q | sed -e "s/all-zones/ /" < $if_file >$TXTMP/txnetmgr.$$
	mv $TXTMP/txnetmgr.$$ $if_file
}

addTnrhdb() {
	ipaddr=$(zenity --entry \
	    --title="$title" \
	    --width=330 \
	    --text="Zone:$zonename. Enter IP address of remote host or network: " \
	    --entry-text a.b.c.d)
	[ $? != 0 ] && return
	validateIPaddr
	if [[ -z $ipaddr ]] ; then
		return;
	fi
	if [ ${octets[3]} = 0 ] ; then
		nic="$ipaddr"
		getNetmask
		if [[ -z $cidr ]] ; then
			return;
		fi
	else
		cidr=32
	fi
	print "${ipaddr}/$cidr:$template" > $TXTMP/tnrhdb_new.$$
	x=$(tnchkdb -h $TXTMP/tnrhdb_new.$$ 2>$TXTMP/syntax_error.$$)
	if [ $? = 0 ] ; then
		updateTnrhdb
	else
		syntax=$(cat $TXTMP/syntax_error.$$)
		x=$(zenity --error \
		    --title="$title" \
		    --text="$syntax")
	fi
	rm $TXTMP/tnrhdb_new.$$
	rm $TXTMP/syntax_error.$$
}

removeTnrhdb() {
	while (( 1 )) do
		remotes=$(grep "^[^#][0-9.]" $TNRHDB|grep ":$template"|cut -d : -f1-2|tr : " ")
		if [ $template = cipso ] ; then
			templateHeading="from All Zones":
		else
			templateHeading="from this Zone":
		fi
		if [[ -n $remotes ]] ; then
			ipaddr=$(zenity --list \
			    --title="$title" \
			    --text="$msg_getremote" \
			    --height=250 \
			    --width=300 \
			    --column="Remove Access to:" \
			    --column="$templateHeading" \
			    $remotes)

			if [[ -n $ipaddr ]] ; then
				deleteTnrhdbEntry
				tnctl -dh ${ip}:$template
			else
				return
			fi
		else
			return
		fi
	done
}

setMLPs() {
	tnzone=$(grep "^$zonename:" $TNZONECFG 2>/dev/null)
	zoneMLPs=:$(print "$tnzone"|cut -d : -f4)
	sharedMLPs=:$(print "$tnzone"|cut -d : -f5)
	attrs="Private Interfaces$zoneMLPs\nShared Interfaces$sharedMLPs"
	ports=$(print "$attrs"|zenity --list \
	    --title="$title" \
	    --height=200 \
	    --width=450 \
	    --text="Zone: $zonename\nClick once to select, twice to edit.\nShift-click to select both rows." \
	    --column="Multilevel Ports (example: 80-81/tcp;111/udp;)" \
	    --editable \
	    --multiple
	    )

	if [[ -z $ports ]] ; then
		return
	fi

	# getopts needs another a blank and another dash
	ports=--$(print "$ports"|sed 's/ //g'|sed 's/|/ --/g'|sed 's/Interfaces:/ :/g')

	OPTIND=1
	while getopts "z:(Private)s:(Shared)" opt $ports ; do
		case $opt in
			z) zoneMLPs=$OPTARG ;;
			s) sharedMLPs=$OPTARG ;;
		esac
	done

	sed -e "/^$zonename:*/d" $TNZONECFG > $TXTMP/tnzonecfg.$$ 2>/dev/null
	tnzone=$(print "$tnzone"|cut -d : -f1-3)
	echo "${tnzone}${zoneMLPs}${sharedMLPs}" >> $TXTMP/tnzonecfg.$$

	x=$(tnchkdb -z $TXTMP/tnzonecfg.$$ 2>$TXTMP/syntax_error.$$)

	if [ $? = 0 ] ; then
		mv $TXTMP/tnzonecfg.$$ $TNZONECFG
		zenity --info \
		    --title="$title" \
		    --text="Multilevel ports for the $zonename zone\nwill be interpreted on next reboot."
		if [ $zonename != global ] ; then
			getLabelRange
		fi
	else
		syntax=$(cat $TXTMP/syntax_error.$$)
		x=$(zenity --error \
		    --title="$title" \
		    --text="$syntax")
		rm $TXTMP/tnzonecfg.$$
	fi
	rm $TXTMP/syntax_error.$$
}

enableAuthentication() {
	integer file_cnt=0

	zonepath=$(zoneadm -z $1 list -p|cut -d : -f4)
	ZONE_ETC_DIR=$zonepath/root/etc

	# If the zone's shadow file was previously read-only
	# there may be no root password entry for this zone.
	# If so, replace the root password entry with the global zone's.

	entry=$(grep ^root:: $ZONE_ETC_DIR/shadow)
	if [ $? -eq 0 ] ; then
		grep ^root: /etc/shadow > $TXTMP/shadow.$$
		sed -e "/^root::/d" $ZONE_ETC_DIR/shadow >> \
		    $TXTMP/shadow.$$ 2>/dev/null
		mv $TXTMP/shadow.$$ $ZONE_ETC_DIR/shadow
		chmod 400 $ZONE_ETC_DIR/shadow
	fi

	if [ $LOGNAME = "root" ]; then
		return
	fi

	file[0]="passwd"
	file[1]="shadow"
	file[2]="user_attr"
	#
	# Add the user who assumed the root role to each installed zone
	#
	while (( file_cnt < ${#file[*]} )); do
		exists=$(grep "^${LOGNAME}:" \
		    $ZONE_ETC_DIR/${file[file_cnt]} >/dev/null)
		if [ $? -ne 0 ] ; then
			entry=$(grep "^${LOGNAME}:" \
			    /etc/${file[file_cnt]})
			if [ $? -eq 0 ] ; then
				print "$entry" >> \
				    $ZONE_ETC_DIR/${file[file_cnt]}
			fi
		fi
		file_cnt+=1
	done
	chmod 400 $ZONE_ETC_DIR/shadow
}

unsharePasswd() {
	zonecfg -z $1 remove fs dir=/etc/passwd >/dev/null 2>&1 | grep -v such
	zonecfg -z $1 remove fs dir=/etc/shadow >/dev/null 2>&1 | grep -v such
	zoneadm -z $1 ready >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		enableAuthentication $1
		zoneadm -z $1 halt >/dev/null 2>&1
	else
		echo Skipping $1
	fi
}

sharePasswd() {
	passwd=$(zonecfg -z $1 info|grep /etc/passwd)
	if [ $? -eq 1 ] ; then
		zonecfg -z $1 "add fs; \
		    set special=/etc/passwd; \
		    set dir=/etc/passwd; \
		    set type=lofs; \
		    add options ro; \
		    end; \
		    add fs; \
		    set special=/etc/shadow; \
		    set dir=/etc/shadow; \
		    set type=lofs; \
		    add options ro; \
		    end"
	fi
	zoneadm -z $1 halt >/dev/null 2>&1
}

# This routine is a toggle -- if we find it configured for global nscd,
# change to nscd-per-label and vice-versa.
#
# The user was presented with only the choice to CHANGE the existing
# configuration.

manageNscd() {
	if [ $NSCD_PER_LABEL -eq 0 ] ; then
		# this MUST be a regular file for svc-nscd to detect
		touch $NSCD_INDICATOR
		NSCD_OPT="Unconfigure per-zone name service"
		NSCD_PER_LABEL=1
		for i in $(zoneadm list -i | grep -v global) ; do
			zoneadm -z $i halt >/dev/null 2>&1
			unsharePasswd $i
		done
	else
		rm -f $NSCD_INDICATOR
		NSCD_OPT="Configure per-zone name service"
		NSCD_PER_LABEL=0
		for i in $(zoneadm list -i | grep -v global) ; do
			zoneadm -z $i halt >/dev/null 2>&1
			sharePasswd $i
		done
	fi
}

manageZoneNets () {
	ncmds[0]="Only use all-zones interfaces"
	ncmds[1]="Add a logical interface"
	ncmds[2]="Add a virtual interface (VNIC)"

	stacks[0]="Shared Stack"
	stacks[1]="Exclusive Stack"

	getAllZoneNICs
	netOps[0]="1\n${ncmds[0]}\nShared Stack\n${aznics[*]}"

	integer nic_cnt=0
	integer netOp_cnt=2

	set -A nics $(dladm show-phys|grep -v LINK|cut -f1 -d " ")

	while (( nic_cnt < ${#nics[*]} )); do
		netOps[netOp_cnt - 1]="\n$netOp_cnt\n${ncmds[1]}\n${stacks[0]}\n${nics[nic_cnt]}"
		netOp_cnt+=1
		netOps[netOp_cnt - 1]="\n$netOp_cnt\n${ncmds[2]}\n${stacks[1]}\n${nics[nic_cnt]}"
		netOp_cnt+=1
		nic_cnt+=1
	done

	netOp=$(print "${netOps[*]}"|zenity --list \
	    --title="$title" \
	    --text="$msg_getnet $zonename zone:" \
	    --height=300 \
	    --width=500 \
	    --column="#" \
	    --column="Network Configuration " \
	    --column="IP Type" \
	    --column="Available Interfaces" \
	    --hide-column=1
	)
	
	# User picked cancel or no selection
	if [[ -z $netOp ]] ; then
		return
	fi

	# All-zones is the default, so just return
	if [ $netOp = 1 ] ; then
		return
	fi

	cmd=$(print "${netOps[$netOp - 1]}"|tr '\n' ';' |cut -d';' -f 3)
	nic=$(print "${netOps[$netOp - 1]}"|tr '\n' ';' |cut -d';' -f 5) 
	case $cmd in
	    ${ncmds[1]} )
		addNet;
		;;	
	    ${ncmds[2]} )
		zonecfg -z $zonename set ip-type=exclusive
		createVNIC
		;;
	esac
}

manageInterface () {
	while (( 1 )) do
		getAttrs

		# Clear list of commands

		share=
		setipaddr=
		newlogical=
		newvnic=
		unplumb=
		bringup=
		bringdown=

		if [ $updown = Down ] ; then
			bringup="Bring Up\n"
		else
			bringdown="Bring Down\n"
		fi

		case $linktype in
		physical )
			newlogical="Create Logical Interface...\n";
			newvnic="Create Virtual Interface (VNIC)...\n";
			;;
		logical )
			unplumb="Remove Logical Interface\n"
			;;
		virtual )
			newlogical="Create Logical Interface...\n";
			unplumb="Remove Virtual Interface\n" ;
			;;
		esac

		if [ $ipaddr = "..." ] ; then
			setipaddr="Set IP address...\n"
		elif [ $zone != all-zones ] ; then
			share="Share with Shared-IP Zones\n"
		else 
			share="Remove from Shared-IP Zones\n"
		fi

		command=$(print ""\
		    $share \
		    $setipaddr \
		    $newlogical \
		    $newvnic \
		    $unplumb \
		    $bringup \
		    $bringdown \
		    | zenity --list \
		    --title="$title" \
		    --text="Select a command from the list below:" \
		    --height=300 \
		    --column "Interface: $nic" )

		case $command in
		    " Create Logical Interface...")
			createInterface;;
		    " Create Virtual Interface (VNIC)...")
			createVNIC ;;	
		    " Set IP address...")
			getIPaddr
			addHost;;
		    " Share with Shared-IP Zones")
			shareInterface;;
		    " Remove from Shared-IP Zones")
			unshareInterface;;
		    " Remove Logical Interface")
			ifconfig $nic unplumb
			rm -f /etc/hostname.$nic
			return;;
		    " Remove Virtual Interface")
			ifconfig $nic unplumb
			dladm delete-vnic $nic
			rm -f /etc/hostname.$nic
			return;;
		    " Bring Up")
			ifconfig $nic up;;
		    " Bring Down")
			ifconfig $nic down;;
		    *) return;;
		esac
	done
}

sharePrimaryNic() {
	set -A ip $(getent hosts $(cat /etc/nodename))
	for i in $(ifconfig -au4|grep  "^[a-z].*:" |grep -v LOOPBACK)
	do
		print "$i" |grep "^[a-z].*:" >/dev/null 2>&1
		[ $? -eq 1 ] && continue
		
		nic=${i%:} # Remove colon after interface name
		getAttrs
		if [ ${ip[0]} = $ipaddr ]; then
			shareInterface
			break
		fi
	done
}

manageNets() {
	while (( 1 )) do
		attrs=
		for i in $(ifconfig -a4|grep  "^[a-z].*:" |grep -v LOOPBACK)
		do
			print "$i" |grep "^[a-z].*:" >/dev/null 2>&1
			[ $? -eq 1 ] && continue
			
			nic=${i%:} # Remove colon after interface name
			getAttrs
			attrs="$nic $linktype $zone $ipaddr $template $updown $attrs"
		done

		nic=$(zenity --list \
		    --title="$title" \
		    --text="Select an interface from the list below:" \
		    --height=300 \
		    --width=500 \
		    --column="Interface" \
		    --column="Type" \
		    --column="Zone Name" \
		    --column="IP Address" \
		    --column="Template" \
		    --column="State" \
		    $attrs)

		if [[ -z $nic ]] ; then
			return
		fi
		manageInterface
	done
}

createLDAPclient() {
	ldaptitle="$title: Create LDAP Client"
	ldapdomain=$(zenity --entry \
	    --width=400 \
	    --title="$ldaptitle" \
	    --text="Enter Domain Name: ")
	if [[ -n $ldapdomain ]] ; then
	ldapserver=$(zenity --entry \
	    --width=400 \
	    --title="$ldaptitle" \
	    --text="Enter Hostname of LDAP Server: ")
	else
		return
	fi
	if [[ -n $ldapserver ]] ; then
	ldapserveraddr=$(zenity --entry \
	    --width=400 \
	    --title="$ldaptitle" \
	    --text="Enter IP adddress of LDAP Server $ldapserver: ")
	else
		return
	fi
	ldappassword=""
	while [[ -z ${ldappassword} || "x$ldappassword" != "x$ldappasswordconfirm" ]] ; do
	    ldappassword=$(zenity --entry \
		--width=400 \
		--title="$ldaptitle" \
		--hide-text \
		--text="Enter LDAP Proxy Password:")
	    ldappasswordconfirm=$(zenity --entry \
		--width=400 \
		--title="$ldaptitle" \
		--hide-text \
		--text="Confirm LDAP Proxy Password:")
	done
	ldapprofile=$(zenity --entry \
	    --width=400 \
	    --title="$ldaptitle" \
	    --text="Enter LDAP Profile Name: ")
	whatnext=$(zenity --list \
	    --width=400 \
	    --height=250 \
	    --title="$ldaptitle" \
	    --text="Proceed to create LDAP Client?" \
	    --column=Parameter --column=Value \
	    "Domain Name" "$ldapdomain" \
	    "Hostname" "$ldapserver" \
	    "IP Address" "$ldapserveraddr" \
	    "Password" "$(print "$ldappassword" | sed 's/./*/g')" \
	    "Profile" "$ldapprofile")
	[ $? != 0 ] && return

	grep "^${ldapserveraddr}[^0-9]" /etc/hosts > /dev/null
	if [ $? -eq 1 ] ; then
		print "$ldapserveraddr $ldapserver" >> /etc/hosts
	fi

	grep "${ldapserver}:" $TNRHDB > /dev/null
	if [ $? -eq 1 ] ; then
		print "# ${ldapserver} - ldap server" \
		    >> $TNRHDB
		print "${ldapserveraddr}:cipso" \
		    >> $TNRHDB
		tnctl -h "${ldapserveraddr}:cipso"
	fi

	proxyDN=$(print $ldapdomain|awk -F"." \
	    "{ ORS = \"\" } { for (i = 1; i < NF; i++) print \"dc=\"\\\$i\",\" }{ print \"dc=\"\\\$NF }")

	zenity --info \
	    --title="$ldaptitle" \
	    --width=500 \
	    --text="global zone will be LDAP client of $ldapserver"

	ldapout=$TXTMP/ldapclient.$$

	ldapclient init -a profileName="$ldapprofile" \
	    -a domainName="$ldapdomain" \
	    -a proxyDN"=cn=proxyagent,ou=profile,$proxyDN" \
	    -a proxyPassword="$ldappassword" \
	    "$ldapserveraddr" >$ldapout 2>&1

	if [ $? -eq 0 ] ; then
	    ldapstatus=Success
	else
	    ldapstatus=Error
	fi

	zenity --text-info \
	    --width=700 \
	    --height=300 \
	    --title="$ldaptitle: $ldapstatus" \
	    --filename=$ldapout

	rm -f $ldapout


}

tearDownZones() {
	if [ $DISP -eq 0 ] ; then
		if [ $FORCE -eq 0 ] ; then
			gettext "OK to destroy all zones [y|N]? "
			read ans
			printf "%s\n" "$ans" \
			    | /bin/grep -Eq "$(locale yesexpr)"
			if [ $? -ne 0 ] ; then
				gettext "canceled.\n"
				return 1
			fi
		fi
		gettext "destroying all zones ...\n"
	else
		killall=$(zenity --question \
		    --title="$title" \
		    --width=330 \
		    --text="$msg_confirmkill")
		if [[ $? != 0 ]]; then
			return
		fi
	fi

	for p in $(zoneadm list -cp|grep -v global:) ; do
		zonename=$(echo "$p"|cut -d : -f2)
		if [ $DISP -eq 0 ] ; then
			gettext "destroying zone $zonename ...\n"
		fi
		zoneadm -z $zonename halt 1>/dev/null 2>&1
		zoneadm -z $zonename uninstall -F 1>/dev/null 2>&1
		delete -rRf
	done
	zonename=global
}

createDefaultZones() {
	# If GUI display is not used, skip the dialog
	if [ $DISP -eq 0 ] ; then
		createDefaultPublic
		if [ $? -ne 0 ] ; then
			return 1
		fi
		createDefaultInternal
		return
	fi

	msg_choose1=$(gettext "Choose one:")
	defpub=$(gettext "$PUBZONE zone only")
	defboth=$(gettext "$PUBZONE and $INTZONE zones")
	defskip=$(gettext "Main Menu...")
	command=$(echo ""\
	    "$defpub\n" \
	    "$defboth\n" \
	    "$defskip\n" \
	    | zenity --list \
	    --title="$title" \
	    --text="$msg_defzones" \
	    --column="$msg_choose1" \
	    --height=400 \
	    --width=330 )

	case $command in
	    " $defpub")
		createDefaultPublic ;;

	    " $defboth")
		createDefaultPublic
		if [ $? -ne 0 ] ; then
			return 1
		fi
		createDefaultInternal ;;

	    *)
		return;;
	esac
}

createDefaultPublic() {
	zonename=$PUBZONE
	if [ $DISP -eq 0 ] ; then
		gettext "creating default $zonename zone ...\n"
	fi
	newZone	
	zone_cnt+=1 
	hexlabel=$DEFAULTLABEL
	setTNdata
	sharePrimaryNic

	install
	if [ $? -ne 0 ] ; then
		return 1
	fi

	if [ $DISP -eq 0 ] ; then
		gettext "booting zone $zonename ...\n"
		zoneadm -z $zonename boot
	else
		zoneadm -z $zonename boot &
		gnome-terminal \
		    --disable-factory \
		    --title="Zone Console: $zonename $msg_continue" \
		    --command "zlogin -C $zonename"
	fi
}

createDefaultInternal() {
	zoneadm -z $PUBZONE halt

	zonename=snapshot
	newZone	
	zone_cnt+=1 
	zonecfg -z $zonename set autoboot=false

	clone $PUBZONE
	zoneadm -z $PUBZONE boot &

	zonename=$INTZONE
	if [ $DISP -eq 0 ] ; then
		gettext "creating default $zonename zone ...\n"
	fi
	newZone	
	zone_cnt+=1 

	hexlabel=$INTLABEL
	x=$(grep -i :{$hexlabel}: $TNZONECFG)
	if [ $? = 0 ] ; then
		z=$(print $x|cut -d : -f1)
		echo "$msg_inuse $z zone."
	else
		setTNdata
	fi

	clone snapshot
	if [ $DISP -eq 0 ] ; then
		gettext "booting zone $zonename ...\n"
	else
		gnome-terminal \
		    --title="Zone Console: $zonename" \
		    --command "zlogin -C $zonename" &
	fi
	zoneadm -z $zonename boot &
}

selectZone() {
	set -A zonelist "global\nrunning\nADMIN_HIGH"
	integer zone_cnt=1

	for p in $(zoneadm list -cp|grep -v global:) ; do
		zone_cnt+=1
	done
	if [ $zone_cnt == 1 ] ; then
		createDefaultZones
	fi
	if [ $zone_cnt == 1 ] ; then
		zonename=global
		singleZone
		return
	fi

	zone_cnt=1
	for p in $(zoneadm list -cp|grep -v global:) ; do
		zonename=$(echo "$p"|cut -d : -f2)
		state=$(echo "$p"|cut -d : -f3)
		hexlabel=$(grep "^$zonename:" $TNZONECFG|cut -d : -f2)
		if [[ $hexlabel ]] ; then
			curlabel=$(hextoalabel $hexlabel)
		else
			curlabel=...
		fi
		zonelist[zone_cnt]="\n$zonename\n$state\n$curlabel"
		zone_cnt+=1
	done
	zonename=$(print "${zonelist[*]}"|zenity --list \
	    --title="$title" \
	    --text="$msg_getzone" \
	    --height=300 \
	    --width=500 \
	    --column="Zone Name" \
	    --column="Status" \
	    --column="Sensitivity Label" \
	)

	# if the menu choice was a zonename, pop up zone menu
	if [[ -n $zonename ]] ; then
		singleZone
	else
		exit
	fi
}

# Loop for single-zone menu
singleZone() {

	while (( 1 )) do
		# Clear list of commands

		console=
		label=
		start=
		reboot=
		stop=
		clone=
		install=
		ready=
		uninstall=
		autoboot=
		delete=
		deletenet=
		permitrelabel=

		if [ $zone_cnt -gt 1 ] ; then
			killZones="Destroy all zones...\n"
			xit="Select another zone..."
		else
			killZones=
			xit="Exit"
		fi
		if [ $zonename = global ] ; then
			ldapClient="Create LDAP Client...\n"
			nscdOpt="$NSCD_OPT\n"
			createZone="Create a new zone...\n"
			addnet="Configure Network Interfaces...\n"
		else
			ldapClient=
			nscdOpt=
			createZone=
			addnet=
			killZones=
		fi

		zonestate=$(zoneadm -z $zonename list -p | cut -d : -f 3)

		consoleCheck;
		labelCheck;
		delay=0

		if [ $zonename != global ] ; then
			case $zonestate in
				running)
					ready="Ready\n"
					reboot="Reboot\n"
					stop="Halt\n"
					;;
				ready)
					start="Boot\n"
					stop="Halt\n"
					;;
				installed)
					if [[ -z $label ]] ; then
						ready="Ready\n"
						start="Boot\n"
					fi
					uninstall="Uninstall\n"
					relabelCheck
					autobootCheck
					;;
				configured) 
					install="Install...\n"
					cloneCheck
					delete="Delete\n"
					console=
					;;
				incomplete)
					uninstall="Uninstall\n"
					;;
				*)
				;;
			esac
		fi

		command=$(echo ""\
		    $createZone \
		    $console \
		    $label \
		    $start \
		    $reboot \
		    $stop \
		    $clone \
		    $install \
		    $ready \
		    $uninstall \
		    $delete \
		    $addnet \
		    $deletenet \
		    $addremotehost \
		    $addcipsohost \
		    $removeremotehost \
		    $removecipsohost \
		    $setmlps \
		    $permitrelabel \
		    $autoboot \
		    $ldapClient \
		    $nscdOpt \
		    $killZones \
		    $xit \
		    | zenity --list \
		    --title="$title" \
		    --text="$msg_getcmd" \
		    --height=400 \
		    --width=330 \
		    --column "Zone: $zonename   Status: $zonestate" )

		case $command in
		    " Create a new zone...")
			zonename=
			newZone ;;

		    " Zone Console...")
			delay=2
			gnome-terminal \
			    --title="Zone Console: $zonename" \
			    --command "zlogin -C $zonename" & ;;

		    " Select Label...")
			selectLabel;;

		    " Ready")
			zoneadm -z $zonename ready ;;

		    " Boot")
			zoneadm -z $zonename boot ;;

		    " Halt")
			zoneadm -z $zonename halt ;;

		    " Reboot")
			zoneadm -z $zonename reboot ;;

		    " Install...")
			install;;

		    " Clone...")
			clone ;;

		    " Uninstall")
			zoneadm -z $zonename uninstall -F;;

		    " Delete")
			delete
			return ;;

		    " Configure Network Interfaces...")
			if [ $zonename = global ] ; then
				manageNets
			else
				manageZoneNets
			fi;;	

		    " Add Single-level Access to Remote Host...")
			addTnrhdb ;;

		    " Add Multilevel Access to Remote Host...")
			template=cipso
			addTnrhdb ;;

		    " Remove Single-level Access to Remote Host...")
			removeTnrhdb ;;

		    " Remove Multilevel Access to Remote Host...")
			template=cipso
			removeTnrhdb ;;

		    " Configure Multilevel Ports...")
			setMLPs;;

		    " Permit Relabeling")
			zonecfg -z $zonename set limitpriv=default,\
win_mac_read,win_mac_write,win_selection,win_dac_read,win_dac_write,\
file_downgrade_sl,file_upgrade_sl,sys_trans_label ;;

		    " Deny Relabeling")
			zonecfg -z $zonename set limitpriv=default ;;

		    " Set Automatic Booting")
			zonecfg -z $zonename set autoboot=true ;;

		    " Set Manual Booting")
			zonecfg -z $zonename set autoboot=false ;;

		    " Create LDAP Client...")
			createLDAPclient ;;

		    " Configure per-zone name service")
			manageNscd ;;

		    " Unconfigure per-zone name service")
			manageNscd ;;

		    " Destroy all zones...")
			tearDownZones
			return ;;

		    *)
			if [ $zone_cnt == 1 ] ; then
				exit
			else
				return
			fi;;
		esac
		sleep $delay;
	done
}

# Main loop for top-level window
#

/usr/bin/plabel $$ 1>/dev/null 2>&1
if [ $? != 0 ] ; then
	gettext "$0 : Trusted Extensions must be enabled.\n"
	exit 1
fi

myzone=$(/sbin/zonename)
if [ $myzone != "global" ] ; then
	gettext "$0 : must be in global zone to run.\n"
	exit 1
fi


process_options "$@" || exit

mkdir $TXTMP 2>/dev/null
deflabel=$(chk_encodings -a|grep "Default User Sensitivity"|\
   sed 's/= /=/'|sed 's/"/'''/g|cut -d"=" -f2)
DEFAULTLABEL=$(atohexlabel ${deflabel})
intlabel=$(chk_encodings -a|grep "Default User Clearance"|\
   sed 's/= /=/'|sed 's/"/'''/g|cut -d"=" -f2)
INTLABEL=$(atohexlabel -c "${intlabel}")

# are there any zfs pools?
ZDSET=none
zpool iostat 1>/dev/null 2>&1
if [ $? = 0 ] ; then
	# is there a zfs pool named "zone"?
	zpool list -H zone 1>/dev/null 2>&1
	if [ $? = 0 ] ; then
		# yes
		ZDSET=zone
	else
		# no, but is there a root pool?
		rootfs=$(df -n / | awk '{print $3}')
		if [ $rootfs = "zfs" ] ; then
			# yes, use it
			ZDSET=$(zfs list -Ho name / | cut -d/ -f 1)/zones
			zfs list -H $ZDSET 1>/dev/null 2>&1
			if [ $? = 1 ] ; then
				createZDSET "-o mountpoint=/zone" $ZDSET
			fi
		fi
	fi
fi

if [ $DISP -eq 0 ] ; then
	gettext "non-interactive mode ...\n"

	if [ $DESTROYZONES -eq 1 ] ; then
		tearDownZones
	fi

	if [ $CREATEDEF -eq 1 ] ; then
		if [[ $(zoneadm list -c) == global ]] ; then
			createDefaultZones
		else
			gettext "cannot create default zones because there are existing zones.\n"
		fi
	fi

	exit
fi

if [ $NSCD_PER_LABEL -eq 0 ] ; then
	NSCD_OPT="Configure per-zone name service"
else
	NSCD_OPT="Unconfigure per-zone name service"
fi


while (( 1 )) do
	selectZone
done