|
root / base / usr / src / cmd / fs.d / autofs
autofs Plain Text 18602 lines 438.2 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
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
#
# 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) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2015 RackTop Systems.
# Copyright (c) 2018, Joyent, Inc.
#

FSTYPE=		autofs
AUTO=		automount
MOUNT=		mount
VERS=		.2
DFSHARES=	dfshares
SHARE=		share
UNSHARE=	unshare
LIBPROG=	$(AUTO) $(MOUNT) $(DFSHARES) $(SHARE) $(UNSHARE)
TYPEPROG=	automountd

LINKINSTALL=	$(ROOTUSRSBIN)/$(AUTO)
LINKVALUE=	../lib/fs/$(FSTYPE)/$(AUTO)
MAPS=		auto_master auto_home
MAPINSTALL=	$(MAPS:%=$(ROOTETC)/%)
AUTOFS=		autofs
DEFAULTFILES=	autofs.dfl
SMFMANIFEST=	autofs.xml
SMFMETHOD=	svc-autofs
MFSTINSTALL=	$(SMFMANIFEST:%=$(ROOTSVCSYSTEM)/filesystem/%)
METHODINSTALL=	$(SMFMETHOD:%=$(ROOTLIBSVCMETHOD)/%)

OTHERINSTALL=	$(MAPINSTALL) $(LINKINSTALL) $(ROOTETCDEFAULTFILES) \
		$(MFSTINSTALL) $(METHODINSTALL)

UNCHECKED_HDRS=	webnfs.h

MANIFEST=	autofs.xml
SVCMETHOD=	svc-autofs

include		../Makefile.fstype

$(MAPINSTALL)	: FILEMODE= 0644

$(MFSTINSTALL)	: FILEMODE = 0444

# Hammerhead: ns_ldap.o removed (libsldap chain removal, Phase 1).
REAL_COMMON=	debug_alloc.o
COMMON=		ns_generic.o ns_files.o ns_nis.o \
		auto_mnttab.o auto_subr.o $(REAL_COMMON)

AUTOOBJS=	automount.o $(COMMON) $(FSLIB) smfcfg.o

MOUNTOBJS=	mount.o $(FSLIB) $(REAL_COMMON)

LOCAL=		autod_main.o \
		autod_parse.o autod_mount.o autod_nfs.o nfs_cast.o \
		autod_autofs.o autod_xdr.o autod_readdir.o autod_lookup.o \
		smfcfg.o

TYPEOBJS=	$(LOCAL) $(COMMON) replica.o nfs_sec.o nfs_resolve.o nfs_subr.o \
		$(FSLIB) webnfs_xdr.o webnfs_client.o selfcheck.o

SHAREOBJS=	$(SHARE:%=%.o)

UNSHAREOBJS=	$(UNSHARE:%=%.o)

POFILE= autofs.po

$(AUTO) :	LDLIBS += -lnsl -lscf
$(MOUNT):	LDLIBS += -lscf
$(TYPEPROG) :	LDLIBS += -lrpcsvc -lsocket -lnsl -lkstat -lscf

CSTD=		$(CSTD_GNU99)

CFLAGS +=	$(CCVERBOSE) -D_FILE_OFFSET_BITS=64
CPPFLAGS=	-I. -I.. -I../nfs/lib $(CPPFLAGS.master) -D_REENTRANT  \
			$(MALLOC_DEBUG)

CERRWARN +=	-Wno-parentheses
CERRWARN +=	-Wno-unused-variable
CERRWARN +=	-Wno-switch
CERRWARN +=	$(CNOWARN_UNINIT)
CERRWARN +=	-Wno-unused-function

# Hammerhead: Suppress pointer/int cast warnings in legacy autofs code
CERRWARN +=	-Wno-pointer-to-int-cast
CERRWARN +=	-Wno-int-to-pointer-cast

# not linted
SMATCH=off

OBJS=		$(AUTOOBJS) $(MOUNTOBJS) $(TYPEOBJS) \
		$(SHAREOBJS) $(UNSHAREOBJS)

nfs_sec.o :	CPPFLAGS += -DWNFS_SEC_NEGO

$(AUTO):	$(AUTOOBJS)
		$(LINK.c) -o $@ $(AUTOOBJS) $(LDLIBS)
		$(POST_PROCESS)

$(MOUNT):	$(MOUNTOBJS)
		$(LINK.c) -o $@ $(MOUNTOBJS) $(LDLIBS)
		$(POST_PROCESS)

$(TYPEPROG):	webnfs.h $(TYPEOBJS)
		$(LINK.c) -o $@ $(TYPEOBJS) $(LDLIBS)
		$(POST_PROCESS)

$(SHARE):	$(SHAREOBJS)
		$(LINK.c) -o $@ $(SHAREOBJS) $(LDLIBS)
		$(POST_PROCESS)

$(UNSHARE):	$(UNSHAREOBJS)
		$(LINK.c) -o $@ $(UNSHAREOBJS) $(LDLIBS)
		$(POST_PROCESS)

$(ROOTSVCSYSTEM)/filesystem/%: %
		$(INS.file)

DUMP_PROG=malloc_dump
BUILDDIR=tmp
DUMP_PROTO=$(BUILDDIR)/$(DUMP_PROG)_client
XFILE=$(BUILDDIR)/malloc_dump.x
XLINE= "program DUMP { version VERS \
	{ void DUMP_IT(void) = 1000000; } = 2; } = 100099;"

$(XFILE):	$(BUILDDIR)
		$(RM) $(XFILE)
		$(ECHO) $(XLINE) > $(XFILE)

$(BUILDDIR):
		$(RM) -r $(BUILDDIR)
		$(MKDIR) $(BUILDDIR)

$(DUMP_PROTO):	$(BUILDDIR) $(XFILE)
		cd $(BUILDDIR); $(RM) *.[ch] makefile.malloc_dump ; rpcgen -a `basename $(XFILE)
		cd $(BUILDDIR); $(MAKE) -f makefile.malloc_dump `basename $@`

$(DUMP_PROG):	$(DUMP_PROTO)
		$(RM) $@
		$(CP) $(DUMP_PROTO) $@

clean_dump:
		$(RM) -r $(BUILDDIR)
		$(RM) $(DUMP_PROG)
$(ROOTUSRSBIN)/$(AUTO):
		$(RM) $@; $(SYMLINK) $(LINKVALUE) $@

replica.o:	../nfs/lib/replica.c
		$(COMPILE.c) ../nfs/lib/replica.c

nfs_sec.o:	../nfs/lib/nfs_sec.c
		$(COMPILE.c) ../nfs/lib/nfs_sec.c

nfs_subr.o:	../nfs/lib/nfs_subr.c
		$(COMPILE.c) ../nfs/lib/nfs_subr.c

selfcheck.o:	../nfs/lib/selfcheck.c
		$(COMPILE.c) ../nfs/lib/selfcheck.c

smfcfg.o: ../nfs/lib/smfcfg.c
		$(COMPILE.c) ../nfs/lib/smfcfg.c

nfs_resolve.o:	../nfs/lib/nfs_resolve.c
		$(COMPILE.c) ../nfs/lib/nfs_resolve.c

# Hammerhead: pre-generated (rpcgen + GNU cpp truncation bug)
# webnfs.h, webnfs_xdr.c, webnfs_client.c are now committed source files.

webnfs.x:	../nfs/lib/webnfs.x
	$(RM) webnfs.x
	$(CP) ../nfs/lib/webnfs.x .

catalog: $(POFILE)

$(POFILE):
	$(RM) messages.po
	$(SED) -e 's/pr_msg/gettext/' `$(EGREP) -l "pr_msg|gettext" *.[ch]` | \
	$(XGETTEXT) $(XGETFLAGS) -
	$(SED) -e '/^# msg/d' -e '/^domain/d' < messages.po > $@
	$(RM) messages.po

clean:	clean_dump
	$(RM) $(OBJS) webnfs.x
	@# Hammerhead: do not delete pre-generated webnfs_xdr.c webnfs_client.c webnfs.h

check:	$(CHKMANIFEST)
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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
#
# ident	"%Z%%M%	%I%	%E% SMI"
#
# Home directory map for automounter
#
+auto_home
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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
#
# ident	"%Z%%M%	%I%	%E% SMI"
#
# Master map for automounter
#
+auto_master
/net		-hosts		-nosuid,nobrowse
/home		auto_home	-nobrowse
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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
 */
/*
 *	auto_mnttab.c
 *
 *	Copyright (c) 1988-1999 Sun Microsystems Inc
 *	All Rights Reserved.
 */

#include <stdio.h>
#include <sys/mnttab.h>
#include <sys/mkdev.h>
#include "automount.h"

static mutex_t mnttab_lock = DEFAULTMUTEX;

/*
 * XXX - Serialize calls to fsgetmntlist, so that threads can get consistent
 * snapshots of the in-kernel mnttab.  This function should be removed
 * once getextmntent is made MT-safe and callers can invoke fsgetmntlist
 * directly.
 */
struct mntlist *
getmntlist()
{
	struct mntlist *mntl;

	(void) mutex_lock(&mnttab_lock);
	mntl = fsgetmntlist();
	(void) mutex_unlock(&mnttab_lock);
	return (mntl);
}

/*
 * Return device number from extmnttab struct
 */
dev_t
get_devid(mnt)
	struct extmnttab *mnt;
{
	return (makedev(mnt->mnt_major, mnt->mnt_minor));
}
/*
 * 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) 2010, Oracle and/or its affiliates. All rights reserved.
 */


#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <locale.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <dirent.h>
#include <limits.h>
#include <thread.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/vfs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mnttab.h>
#include <sys/mntent.h>
#include <sys/mount.h>
#include <sys/signal.h>
#include <sys/utsname.h>
#include <sys/systeminfo.h>
#include <sys/tiuser.h>
#include <sys/utsname.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>
#include <rpcsvc/daemon_utils.h>
#include <assert.h>
#include "automount.h"
#include <deflt.h>
#include <zone.h>
#include <priv.h>
#include <fcntl.h>
#include <libshare.h>
#include <libscf.h>
#include "smfcfg.h"

static char *check_hier(char *);
static int arch(char *, size_t, bool_t);
static int cpu(char *, size_t);
static int natisa(char *, size_t);
static int platform(char *, size_t);

struct mntlist *current_mounts;

static bool_t nodirect_map = FALSE;

/*
 * If the system is labeled then we need to
 * have a uniquely-named auto_home map for each zone.
 * The maps are made unique by appending the zonename.
 * The home directory is made unique by prepending /zone/<zonename>
 * for each zone that is dominated by the current zone.
 * The current zone's home directory mount point is not changed.
 *
 * For each auto_home_<zonename> a default template map is created
 * only if it doesn't exist yet. The default entry is used to declare
 * local home directories created within each zone. For example:
 *
 *	+auto_home_public
 *      * -fstype=lofs :/zone/public/export/home/&
 */
static void
loadzone_maps(char *mntpnt, char *map, char *opts, char **stack, char ***stkptr)
{
	zoneid_t *zids = NULL;
	zoneid_t my_zoneid;
	uint_t nzents_saved;
	uint_t nzents;
	int i;

	if (!priv_ineffect(PRIV_SYS_MOUNT))
		return;

	if (zone_list(NULL, &nzents) != 0) {
		return;
	}
	my_zoneid = getzoneid();
again:
	if (nzents == 0)
		return;

	zids = malloc(nzents * sizeof (zoneid_t));
	nzents_saved = nzents;

	if (zone_list(zids, &nzents) != 0) {
		free(zids);
		return;
	}
	if (nzents != nzents_saved) {
		/* list changed, try again */
		free(zids);
		goto again;
	}

	for (i = 0; i < nzents; i++) {
		char zonename[ZONENAME_MAX];
		char zoneroot[MAXPATHLEN];

		if (getzonenamebyid(zids[i], zonename, ZONENAME_MAX) != -1) {
			char appended_map[MAXPATHLEN];
			char prepended_mntpnt[MAXPATHLEN];
			char map_path[MAXPATHLEN];
			int fd;

			(void) snprintf(appended_map, sizeof (appended_map),
			    "%s_%s", map, zonename);

			/* for current zone, leave mntpnt alone */
			if (zids[i] != my_zoneid) {
				(void) snprintf(prepended_mntpnt,
				    sizeof (prepended_mntpnt),
				    "/zone/%s%s", zonename, mntpnt);
				if (zone_getattr(zids[i], ZONE_ATTR_ROOT,
				    zoneroot, sizeof (zoneroot)) == -1)
					continue;
			} else {
				(void) strcpy(prepended_mntpnt, mntpnt);
				zoneroot[0] = '\0';
			}

			dirinit(prepended_mntpnt, appended_map, opts, 0, stack,
			    stkptr);
			/*
			 * Next create auto_home_<zone> maps for each zone
			 */

			(void) snprintf(map_path, sizeof (map_path),
			    "/etc/%s", appended_map);
			/*
			 * If the map file doesn't exist create a template
			 */
			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
				int len;
				char map_rec[MAXPATHLEN];

				len = snprintf(map_rec, sizeof (map_rec),
				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
				    appended_map, zoneroot);
				if (len <= sizeof (map_rec))
					(void) write(fd, map_rec, len);
				(void) close(fd);
			}
		}
	}
	free(zids);
}

void
dirinit(char *mntpnt, char *map, char *opts, int direct, char **stack,
    char ***stkptr)
{
	struct autodir *dir;
	char *p;

	if (strcmp(map, "-null") == 0) {
		if (strcmp(mntpnt, "/-") == 0)
			nodirect_map = TRUE;
		goto enter;
	}

	p = mntpnt + (strlen(mntpnt) - 1);
	if (*p == '/')
		*p = '\0';	/* trim trailing / */
	if (*mntpnt != '/') {
		pr_msg("dir %s must start with '/'", mntpnt);
		return;
	}
	if (p = check_hier(mntpnt)) {
		pr_msg("hierarchical mountpoint: %s and %s",
		    p, mntpnt);
		return;
	}

	/*
	 * If it's a direct map then call dirinit
	 * for every map entry.
	 */
	if ((strcmp(mntpnt, "/-") == 0) && !(nodirect_map)) {
		(void) loaddirect_map(map, map, opts, stack, stkptr);
		return;
	}

	/*
	 * Home directories are polyinstantiated on
	 * labeled systems.
	 */
	if (is_system_labeled() &&
	    (strcmp(mntpnt, "/home") == 0) &&
	    (strcmp(map, "auto_home") == 0)) {
		(void) loadzone_maps(mntpnt, map, opts, stack, stkptr);
		return;
	}
enter:
	dir = (struct autodir *)malloc(sizeof (*dir));
	if (dir == NULL)
		goto alloc_failed;
	dir->dir_name = strdup(mntpnt);
	if (dir->dir_name == NULL)
		goto alloc_failed;
	dir->dir_map = strdup(map);
	if (dir->dir_map == NULL)
		goto alloc_failed;
	dir->dir_opts = strdup(opts);
	if (dir->dir_opts == NULL)
		goto alloc_failed;
	dir->dir_direct = direct;
	dir->dir_remount = 0;
	dir->dir_next = NULL;

	/*
	 * Append to dir chain
	 */
	if (dir_head == NULL)
		dir_head = dir;
	else
		dir_tail->dir_next = dir;

	dir->dir_prev = dir_tail;
	dir_tail = dir;

	return;

alloc_failed:
	if (dir != NULL) {
		if (dir->dir_opts)
			free(dir->dir_opts);
		if (dir->dir_map)
			free(dir->dir_map);
		if (dir->dir_name)
			free(dir->dir_name);
		free(dir);
	}
	pr_msg("dirinit: memory allocation failed");
}

/*
 *  Check whether the mount point is a
 *  subdirectory or a parent directory
 *  of any previously mounted automount
 *  mount point.
 */
static char *
check_hier(mntpnt)
	char *mntpnt;
{
	register struct autodir *dir;
	register char *p, *q;

	for (dir = dir_head; dir; dir = dir->dir_next) {
		p = dir->dir_name;
		q = mntpnt;
		for (; *p == *q; p++, q++)
			if (*p == '\0')
				break;
		if (*p == '/' && *q == '\0')
			return (dir->dir_name);
		if (*p == '\0' && *q == '/')
			return (dir->dir_name);
		if (*p == '\0' && *q == '\0')
			return (NULL);
	}
	return (NULL);	/* it's not a subdir or parent */
}

/*
 * Gets the next token from the string "p" and copies it into "w".  The "wq" is
 * a quote vector for "w" and is derived from "pq", which is a quote vector for
 * "p". Delim is the character to be used as a delimiter for the scan.  A space
 * means "whitespace". The call to getword must provide buffers w and wq of size
 * at least wordsz. getword() will pass strings of maximum length (wordsz-1),
 * since it needs to null terminate the string.
 * Returns 0 on ok and -1 on error.
 */
int
getword(char *w, char *wq, char **p, char **pq, char delim, int wordsz)
{
	char *tmp = w;
	char *tmpq = wq;
	int count = wordsz;

	if (wordsz <= 0) {
		if (verbose)
			syslog(LOG_ERR,
			"getword: input word size %d must be > 0", wordsz);
		return (-1);
	}

	while ((delim == ' ' ? isspace(**p) : **p == delim) && **pq == ' ')
		(*p)++, (*pq)++;

	while (**p &&
	    !((delim == ' ' ? isspace(**p) : **p == delim) &&
	    **pq == ' ')) {
		if (--count <= 0) {
			*tmp = '\0';
			*tmpq = '\0';
			syslog(LOG_ERR,
			"maximum word length (%d) exceeded", wordsz);
			return (-1);
		}
		*w++  = *(*p)++;
		*wq++ = *(*pq)++;
	}
	*w  = '\0';
	*wq = '\0';

	return (0);
}

/*
 * get_line attempts to get a line from the map, upto LINESZ. A line in
 * the map is a concatenation of lines if the continuation symbol '\'
 * is used at the end of the line. Returns line on success, a NULL on
 * EOF, and an empty string on lines > linesz.
 */
char *
get_line(FILE *fp, char *map, char *line, int linesz)
{
	register char *p = line;
	register int len;
	int excess = 0;

	*p = '\0';

	for (;;) {
		if (fgets(p, linesz - (p-line), fp) == NULL) {
			return (*line ? line : NULL);	/* EOF */
		}

		len = strlen(line);
		if (len <= 0) {
			p = line;
			continue;
		}
		p = &line[len - 1];

		/*
		 * Is input line too long?
		 */
		if (*p != '\n') {
			excess = 1;
			/*
			 * Perhaps last char read was '\'. Reinsert it
			 * into the stream to ease the parsing when we
			 * read the rest of the line to discard.
			 */
			(void) ungetc(*p, fp);
			break;
		}
trim:
		/* trim trailing white space */
		while (p >= line && isspace(*(uchar_t *)p))
			*p-- = '\0';
		if (p < line) {			/* empty line */
			p = line;
			continue;
		}

		if (*p == '\\') {		/* continuation */
			*p = '\0';
			continue;
		}

		/*
		 * Ignore comments. Comments start with '#'
		 * which must be preceded by a whitespace, unless
		 * if '#' is the first character in the line.
		 */
		p = line;
		while (p = strchr(p, '#')) {
			if (p == line || isspace(*(p-1))) {
				*p-- = '\0';
				goto trim;
			}
			p++;
		}
		break;
	}
	if (excess) {
		int c;

		/*
		 * discard rest of line and return an empty string.
		 * done to set the stream to the correct place when
		 * we are done with this line.
		 */
		while ((c = getc(fp)) != EOF) {
			*p = c;
			if (*p == '\n')		/* end of the long line */
				break;
			else if (*p == '\\') {		/* continuation */
				if (getc(fp) == EOF)	/* ignore next char */
					break;
			}
		}
		syslog(LOG_ERR,
		    "map %s: line too long (max %d chars)",
		    map, linesz-1);
		*line = '\0';
	}

	return (line);
}

/*
 * Gets the retry=n entry from opts.
 * Returns 0 if retry=n is not present in option string,
 * retry=n is invalid, or when option string is NULL.
 */
int
get_retry(char *opts)
{
	int retry = 0;
	char buf[MAXOPTSLEN];
	char *p, *pb, *lasts;

	if (opts == NULL)
		return (retry);

	(void) strcpy(buf, opts);
	pb = buf;
	while (p = (char *)strtok_r(pb, ",", &lasts)) {
		pb = NULL;
		if (strncmp(p, "retry=", 6) == 0)
			retry = atoi(p+6);
	}
	return (retry > 0 ? retry : 0);
}

/*
 * Returns zero if "opt" is found in mnt->mnt_opts, setting
 * *sval to whatever follows the equal sign after "opt".
 * str_opt allocates a string long enough to store the value of
 * "opt" plus a terminating null character and returns it as *sval.
 * It is the responsability of the caller to deallocate *sval.
 * *sval will be equal to NULL upon return if either "opt=" is not found,
 * or "opt=" has no value associated with it.
 *
 * stropt will return -1 on error.
 */
int
str_opt(struct mnttab *mnt, char *opt, char **sval)
{
	char *str, *comma;

	/*
	 * is "opt" in the options field?
	 */
	if (str = hasmntopt(mnt, opt)) {
		str += strlen(opt);
		if (*str++ != '=' ||
		    (*str == ',' || *str == '\0')) {
			syslog(LOG_ERR, "Bad option field");
			return (-1);
		}
		comma = strchr(str, ',');
		if (comma != NULL)
			*comma = '\0';
		*sval = strdup(str);
		if (comma != NULL)
			*comma = ',';
		if (*sval == NULL)
			return (-1);
	} else
		*sval = NULL;

	return (0);
}

/*
 * Performs text expansions in the string "pline".
 * "plineq" is the quote vector for "pline".
 * An identifier prefixed by "$" is replaced by the
 * corresponding environment variable string.  A "&"
 * is replaced by the key string for the map entry.
 *
 * This routine will return an error (non-zero) if *size* would be
 * exceeded after expansion, indicating that the macro_expand failed.
 * This is to prevent writing past the end of pline and plineq.
 * Both pline and plineq are left untouched in such error case.
 */
int
macro_expand(key, pline, plineq, size)
	char *key, *pline, *plineq;
	int size;
{
	register char *p,  *q;
	register char *bp, *bq;
	register char *s;
	char buffp[LINESZ], buffq[LINESZ];
	char namebuf[64], *pn;
	int expand = 0;
	struct utsname name;
	char procbuf[SYS_NMLN];
	char isaname[64];

	p = pline;  q = plineq;
	bp = buffp; bq = buffq;

	while (*p) {
		if (*p == '&' && *q == ' ') {	/* insert key */
			/*
			 * make sure we don't overflow buffer
			 */
			if ((int)((bp - buffp) + strlen(key)) < size) {
				for (s = key; *s; s++) {
					*bp++ = *s;
					*bq++ = ' ';
				}
				expand++;
				p++; q++;
				continue;
			} else {
				/*
				 * line too long...
				 */
				return (1);
			}
		}

		if (*p == '$' && *q == ' ') {	/* insert env var */
			p++; q++;
			pn = namebuf;
			if (*p == '{') {
				p++; q++;
				while (*p && *p != '}') {
					*pn++ = *p++;
					q++;
				}
				if (*p) {
					p++; q++;
				}
			} else {
				while (*p && (*p == '_' || isalnum(*p))) {
					*pn++ = *p++;
					q++;
				}
			}
			*pn = '\0';

			s = getenv(namebuf);
			if (!s) {
				/* not found in env */
				if (strcmp(namebuf, "ARCH") == 0) {
					if (arch(procbuf, sizeof (procbuf),
					    FALSE))
						s = procbuf;
				} else if (strcmp(namebuf, "CPU") == 0) {
					if (cpu(procbuf, sizeof (procbuf)))
						s = procbuf;
				} else if (strcmp(namebuf, "HOST") == 0) {
					(void) uname(&name);
					s = name.nodename;
				} else if (strcmp(namebuf, "KARCH") == 0) {
					if (arch(procbuf, sizeof (procbuf),
					    TRUE))
						s = procbuf;
				} else if (strcmp(namebuf, "OSREL") == 0) {
					(void) uname(&name);
					s = name.release;
				} else if (strcmp(namebuf, "OSNAME") == 0) {
					(void) uname(&name);
					s = name.sysname;
				} else if (strcmp(namebuf, "OSVERS") == 0) {
					(void) uname(&name);
					s = name.version;
				} else if (strcmp(namebuf, "NATISA") == 0) {
					if (natisa(isaname, sizeof (isaname)))
						s = isaname;
				} else if (strcmp(namebuf, "PLATFORM") == 0) {
					if (platform(procbuf, sizeof (procbuf)))
						s = procbuf;
				}
			}

			if (s) {
				if ((int)((bp - buffp) + strlen(s)) < size) {
					while (*s) {
						*bp++ = *s++;
						*bq++ = ' ';
					}
				} else {
					/*
					 * line too long...
					 */
					return (1);
				}
			}
			expand++;
			continue;
		}
		/*
		 * Since buffp needs to be null terminated, we need to
		 * check that there's still room in the buffer to
		 * place at least two more characters, *p and the
		 * terminating null.
		 */
		if (bp - buffp == size - 1) {
			/*
			 * There was not enough room for at least two more
			 * characters, return with an error.
			 */
			return (1);
		}
		/*
		 * The total number of characters so far better be less
		 * than the size of buffer passed in.
		 */
		*bp++ = *p++;
		*bq++ = *q++;

	}
	if (!expand)
		return (0);
	*bp = '\0';
	*bq = '\0';
	/*
	 * We know buffp/buffq will fit in pline/plineq since we
	 * processed at most size characters.
	 */
	(void) strcpy(pline, buffp);
	(void) strcpy(plineq, buffq);

	return (0);
}

/*
 * Removes backslashes, quotes and brackets from the string "str"
 * and returns the quoting information in "qbuf". Character is
 * considered escaped when it is
 *
 *	preceded with '\'	e.g. \a
 *	within quotes		e.g. "string"
 *	a ':' in brackets	e.g. [an:ip:6::ad::d:re:s:s]
 *
 * original str: 'the "brown" f\ox said: [fe80::20a:e4ff:fe35:8b0d]'
 * unquoted str: 'the brown fox said: [fe80::20a:e4ff:fe35:8b0d]'
 * and the qbuf: '    ^^^^^  ^             ^^   ^    ^    ^     '
 */
void
unquote(str, qbuf)
	char *str, *qbuf;
{
	register int escaped, inquote, inbracket, quoted;
	register char *ip, *bp, *qp;
	char buf[LINESZ];

	escaped = inquote = inbracket = quoted = 0;

	for (ip = str, bp = buf, qp = qbuf; *ip; ip++) {
		if (!escaped) {
			if (*ip == '\\') {
				escaped = 1;
				quoted++;
				continue;
			} else
			if (*ip == '"') {
				inquote = !inquote;
				quoted++;
				continue;
			} else
			if (*ip == '[') {
				inbracket++;
				quoted++;
			} else
			if (*ip == ']') {
				if (inbracket > 0) inbracket--;
			}
		}

		*bp++ = *ip;
		*qp++ = (inquote || escaped) ? '^'
				: ((inbracket && (*ip == ':')) ? '^' : ' ');
		escaped = 0;
	}

	*bp = '\0';
	*qp = '\0';

	if (quoted)
		(void) strcpy(str, buf);
}

/*
 * If str is enclosed in [brackets], trim them off.
 */
void
unbracket(s)
	char **s;
{
	char *b = *s + strlen(*s) - 1;

	if (*b == ']')
		*b = '\0';
	if (**s == '[')
		(*s)++;
}

/*
 * Removes trailing spaces from string "s".
 */
void
trim(s)
	char *s;
{
	char *p = &s[strlen(s) - 1];

	while (p >= s && isspace(*(uchar_t *)p))
		*p-- = '\0';
}

/*
 * try to allocate memory using malloc, if malloc fails, then flush the
 * rddir caches, and retry. If the second allocation after the readdir
 * caches have been flushed fails too, then return NULL to indicate
 * memory could not be allocated.
 */
char *
auto_rddir_malloc(unsigned nbytes)
{
	char *p;
	int again = 0;

	if ((p = malloc(nbytes)) == NULL) {
		/*
		 * No memory, free rddir caches and try again
		 */
		mutex_lock(&cleanup_lock);
		cond_signal(&cleanup_start_cv);
		if (cond_wait(&cleanup_done_cv, &cleanup_lock)) {
			mutex_unlock(&cleanup_lock);
			syslog(LOG_ERR, "auto_rddir_malloc interrupted\n");
		} else {
			mutex_unlock(&cleanup_lock);
			again = 1;
		}
	}

	if (again)
		p = malloc(nbytes);

	return (p);
}

/*
 * try to strdup a string, if it fails, then flush the rddir caches,
 * and retry. If the second strdup fails, return NULL to indicate failure.
 */
char *
auto_rddir_strdup(const char *s1)
{
	char *s2;
	int again = 0;

	if ((s2 = strdup(s1)) == NULL) {
		/*
		 * No memory, free rddir caches and try again
		 */
		mutex_lock(&cleanup_lock);
		cond_signal(&cleanup_start_cv);
		if (cond_wait(&cleanup_done_cv, &cleanup_lock)) {
			mutex_unlock(&cleanup_lock);
			syslog(LOG_ERR, "auto_rddir_strdup interrupted\n");
		} else {
			mutex_unlock(&cleanup_lock);
			again = 1;
		}
	}

	if (again)
		s2 = strdup(s1);

	return (s2);
}

/*
 * Returns a pointer to the entry corresponding to 'name' if found,
 * otherwise it returns NULL.
 */
struct dir_entry *
btree_lookup(struct dir_entry *head, char *name)
{
	register struct dir_entry *p;
	register int direction;

	for (p = head; p != NULL; ) {
		direction = strcmp(name, p->name);
		if (direction == 0)
			return (p);
		if (direction > 0)
			p = p->right;
		else p = p->left;
	}
	return (NULL);
}

/*
 * Add entry to binary tree
 * Duplicate entries are not added
 */
void
btree_enter(struct dir_entry **head, struct dir_entry *ent)
{
	register struct dir_entry *p, *prev = NULL;
	register int direction;

	ent->right = ent->left = NULL;
	if (*head == NULL) {
		*head = ent;
		return;
	}

	for (p = *head; p != NULL; ) {
		prev = p;
		direction = strcmp(ent->name, p->name);
		if (direction == 0) {
			/*
			 * entry already in btree
			 */
			return;
		}
		if (direction > 0)
			p = p->right;
		else p = p->left;
	}
	assert(prev != NULL);
	if (direction > 0)
		prev->right = ent;
	else prev->left = ent;
}

/*
 * If entry doesn't exist already, add it to the linear list
 * after '*last' and to the binary tree list.
 * If '*last == NULL' then the list is walked till the end.
 * *last is always set to the new element after successful completion.
 * if entry already exists '*last' is only updated if not previously
 * provided.
 */
int
add_dir_entry(char *name, struct dir_entry **list, struct dir_entry **last)
{
	struct dir_entry *e, *l;

	if ((*list != NULL) && (*last == NULL)) {
		/*
		 * walk the list to find last element
		 */
		for (l = *list; l != NULL; l = l->next)
			*last = l;
	}

	if (btree_lookup(*list, name) == NULL) {
		/*
		 * not a duplicate, add it to list
		 */
		/* LINTED pointer alignment */
		e = (struct dir_entry *)
		    auto_rddir_malloc(sizeof (struct dir_entry));
		if (e == NULL)
			return (ENOMEM);
		(void) memset((char *)e, 0, sizeof (*e));
		e->name = auto_rddir_strdup(name);
		if (e->name == NULL) {
			free(e);
			return (ENOMEM);
		}
		e->next = NULL;
		if (*list == NULL) {
			/*
			 * list is empty
			 */
			*list = *last = e;
		} else {
			/*
			 * append to end of list
			 */
			assert(*last != NULL);
			(*last)->next = e;
			*last = e;
		}
		/*
		 * add to binary tree
		 */
		btree_enter(list, e);
	}
	return (0);
}

/*
 * Print trace output.
 * Like fprintf(stderr, fmt, ...) except that if "id" is nonzero, the output
 * is preceeded by the ID of the calling thread.
 */
#define	FMT_BUFSIZ 1024

void
trace_prt(int id, char *fmt, ...)
{
	va_list args;

	char buf[FMT_BUFSIZ];

	if (id) {
		(void) sprintf(buf, "t%u\t%s", thr_self(), fmt);
		fmt = buf;
	}
	va_start(args, fmt);
	(void) vfprintf(stderr, fmt, args);
	va_end(args);
}

/*
 * Extract the isalist(7) for userland from the kernel.
 */
static char *
isalist(void)
{
	char *buf;
	size_t bufsize = BUFSIZ;	/* wild guess */
	long ret;

	buf = malloc(bufsize);
	do {
		ret = sysinfo(SI_ISALIST, buf, bufsize);
		if (ret == -1l)
			return (NULL);
		if (ret > bufsize) {
			bufsize = ret;
			buf = realloc(buf, bufsize);
		} else
			break;
	} while (buf != NULL);

	return (buf);
}

/*
 * Classify isa's as to bitness of the corresponding ABIs.
 * isa's which have no "official" system ABI are returned
 * unrecognised i.e. zero bits.
 */
static int
bitness(char *isaname)
{
	if (strcmp(isaname, "sparc") == 0 ||
	    strcmp(isaname, "i386") == 0)
		return (32);

	if (strcmp(isaname, "sparcv9") == 0 ||
	    strcmp(isaname, "amd64") == 0)
		return (64);

	return (0);
}

/*
 * Determine the application architecture (derived from uname -m) to expand
 * the $ARCH and $KARCH macros.
 *
 * Like arch(1), we need to substitute "sun4" for "sun4u", "sun4v", ... for
 * backward compatibility. When kflag is set (like arch -k), the unmodifed
 * value is returned instead.
 */
static int
arch(char *buf, size_t bufsize, bool_t karch)
{
	long ret;

	ret = sysinfo(SI_MACHINE, buf, bufsize);
	if (ret == -1L)
		return (0);
	if (!karch && strncmp(buf, "sun4", 4) == 0)
		(void) strlcpy(buf, "sun4", bufsize);
	return (1);
}

/*
 * Determine the basic ISA (uname -p) to expand the $CPU macro.
 */
static int
cpu(char *buf, size_t bufsize)
{
	long ret;

	ret = sysinfo(SI_ARCHITECTURE, buf, bufsize);
	if (ret == -1L)
		return (0);
	else
		return (1);
}

/*
 * Find the left-most element in the isalist that matches our idea of a
 * system ABI.
 *
 * On machines with only one ABI, this is usually the same as uname -p.
 */
static int
natisa(char *buf, size_t bufsize)
{
	int bits;
	char *isa, *list;
	char *lasts;

	if ((list = isalist()) == NULL)
		return (0);

	for (isa = strtok_r(list, " ", &lasts);
	    isa; isa = strtok_r(0, " ", &lasts))
		if ((bits = bitness(isa)) != 0)
			break;	/* ignore "extension" architectures */

	if (isa == 0 || bits == 0) {
		free(list);
		return (0);	/* can't figure it out :( */
	}

	(void) strncpy(buf, isa, bufsize);
	free(list);

	return (1);
}

/*
 * Determine the platform (uname -i) to expand the $PLATFORM macro.
 */
static int
platform(char *buf, size_t bufsize)
{
	long ret;

	ret = sysinfo(SI_PLATFORM, buf, bufsize);
	if (ret == -1L)
		return (0);
	else
		return (1);
}

/*
 * Set environment variables
 */
void
put_automountd_env(void)
{
	char defval[PATH_MAX], *p, *a, *c;
	int ret = 0, bufsz = PATH_MAX;

	ret = autofs_smf_get_prop("environment", defval, DEFAULT_INSTANCE,
	    SCF_TYPE_ASTRING, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK) {
		a = c = defval;
		if (*a == '\0')
			return;
		/*
		 * Environment variables can have more than one value
		 * seperated by a comma and there can be multiple
		 * environment variables. * a=b\,c,d=e. For multiple
		 * valued environment variable, values are seperated
		 * with an escape character.
		 */
		while ((p = strchr(c, ',')) != NULL) {
			if (*(p - 1) == '\\') {
				c = p + 1;
				continue;
			}
			*p = '\0';
			if ((c = strchr(a, '=')) != NULL)
				putenv(strdup(a));
			a = c = p + 1;
		}
		if (*a != '\0') {
			if ((c = strchr(a, '=')) != NULL)
				putenv(strdup(a));
		}
	}
}
/*
 * 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
 */
/*
 *	autod_autofs.c
 *
 *	Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 *	Use is subject to license terms.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/tiuser.h>
#include <syslog.h>
#include <string.h>
#include <errno.h>
#include <fslib.h>
#include <sys/vfs.h>
#include <assert.h>
#include "automount.h"

static int process_opts(char *options, int *directp, int *sawnestp);
void netbuf_free(struct netbuf *);

int
mount_autofs(
	struct mapent *me,
	char *mntpnt,
	action_list *alp,
	char *rootp,
	char *subdir,
	char *key
)
{
	int mntflags = 0;
	struct utsname utsname;
	autofs_args *fnip = NULL;
	int mount_timeout = AUTOFS_MOUNT_TIMEOUT;
	int sawnest, len, error = 0;
	char *buf, rel_mntpnt[MAXPATHLEN];

	if (trace > 1)
		trace_prt(1, "  mount_autofs %s on %s\n",
		me->map_fs->mfs_dir, mntpnt);

	if (strcmp(mntpnt, "/-") == 0) {
		syslog(LOG_ERR, "invalid mountpoint: /-");
		return (ENOENT);
	}

	/*
	 * get relative mountpoint
	 */
	sprintf(rel_mntpnt, ".%s", mntpnt+strlen(rootp));

	if (trace > 2)
		trace_prt(1, "rel_mntpnt = %s\n", rel_mntpnt);

	if (uname(&utsname) < 0) {
		error = errno;
		syslog(LOG_ERR, "uname %s", strerror(error));
		return (error);
	}

	if ((fnip = (autofs_args *)
	    malloc(sizeof (autofs_args))) == NULL) {
		goto free_mem;
	}
	(void) memset((void *) fnip, 0, sizeof (*fnip));

	if ((fnip->addr.buf = (char *)malloc(MAXADDRLEN)) == NULL)
		goto free_mem;

	(void) strcpy(fnip->addr.buf, utsname.nodename);
	(void) strcat(fnip->addr.buf, ".autofs");

	if ((fnip->opts = malloc(MAX_MNTOPT_STR)) == NULL)
		goto free_mem;
	strcpy(fnip->opts, me->map_mntopts);

	if (process_opts(fnip->opts, &fnip->direct, &sawnest) != 0)
		goto free_mem;

	fnip->addr.len = strlen(fnip->addr.buf);
	fnip->addr.maxlen = fnip->addr.len;

	/*
	 * get absolute mountpoint
	 */
	if ((fnip->path = strdup(mntpnt)) == NULL)
		goto free_mem;
	if ((fnip->map = strdup(me->map_fs->mfs_dir)) == NULL)
		goto free_mem;
	if ((fnip->subdir = strdup(subdir)) == NULL)
		goto free_mem;

	/*
	 * This timeout is really ignored by autofs, it uses the
	 * parent directory's timeout since it's really the one
	 * specified/inherited from the original mount by 'automount'
	 */
	fnip->mount_to = mount_timeout;	/* IGNORED */
	fnip->rpc_to = AUTOFS_RPC_TIMEOUT;

	if (fnip->direct) {
		if (me->map_modified == TRUE || me->map_faked == TRUE) {
			if ((fnip->key = strdup(key)) == NULL)
				goto free_mem;
		} else {
			/* wierd case of a direct map pointer in another map */
			if ((fnip->key = strdup(fnip->path)) == NULL)
				goto free_mem;
		}
	} else {
		fnip->key = NULL;
	}

	/*
	 * Fill out action list.
	 */
	alp->action.action = AUTOFS_MOUNT_RQ;
	if ((alp->action.action_list_entry_u.mounta.spec =
	    strdup(me->map_fs->mfs_dir)) == NULL)
		goto free_mem;
	if ((alp->action.action_list_entry_u.mounta.dir =
	    strdup(rel_mntpnt)) == NULL)
		goto free_mem;

	len = strlen(fnip->opts);
	/*
	 * Get a buffer for the option string, it holds the map options plus
	 * space for "nest" if it isn't already in the option string
	 */
	if ((buf = (char *)malloc(MAX_MNTOPT_STR)) == NULL)
		goto free_mem;
	strcpy(buf, fnip->opts);
	if (!sawnest) {
		if (len + strlen(",nest") + 1 > MAX_MNTOPT_STR)
			goto free_mem;
		if (len)
			(void) strcat(buf, ",");
		(void) strcat(buf, "nest");
	}
	alp->action.action_list_entry_u.mounta.optptr = buf;
	alp->action.action_list_entry_u.mounta.optlen = strlen(buf) + 1;
	alp->action.action_list_entry_u.mounta.flags =
		mntflags | MS_DATA | MS_OPTIONSTR;
	if ((alp->action.action_list_entry_u.mounta.fstype =
	    strdup(MNTTYPE_AUTOFS)) == NULL)
		goto free_mem;
	alp->action.action_list_entry_u.mounta.dataptr = (char *)fnip;
	alp->action.action_list_entry_u.mounta.datalen = sizeof (*fnip);

	return (0);

free_mem:
	/*
	 * We got an error, free the memory we allocated.
	 */
	syslog(LOG_ERR, "mount_autofs: memory allocation failure");
	free_autofs_args(fnip);
	alp->action.action_list_entry_u.mounta.dataptr = NULL;
	alp->action.action_list_entry_u.mounta.datalen = 0;
	free_mounta(&alp->action.action_list_entry_u.mounta);

	return (error ? error : ENOMEM);
}

/*
 * Set *directp to 1 if "direct" is found, and 0 otherwise
 * (mounts are indirect by default).  If both "direct" and "indirect" are
 * found, the last one wins.
 */
static int
process_opts(char *options, int *directp, int *sawnestp)
{
	char *opt, *opts, *lasts;
	char buf[AUTOFS_MAXOPTSLEN];

	assert(strlen(options)+1 < AUTOFS_MAXOPTSLEN);

	*sawnestp = 0;
	strcpy(buf, options);
	opts = buf;
	options[0] = '\0';
	*directp = 0;

	while ((opt = strtok_r(opts, ",", &lasts)) != NULL) {
		opts = NULL;
		while (isspace(*opt)) {
			opt++;
		}
		if (strcmp(opt, "direct") == 0) {
			*directp = 1;
		} else if (strcmp(opt, "indirect") == 0) {
			*directp = 0;
		} else if (strcmp(opt, "ignore") != 0) {
			if (strcmp(opt, "nest") == 0) {
				*sawnestp = 1;
			}
			if (options[0] != '\0') {
				(void) strcat(options, ",");
			}
			(void) strcat(options, opt);
		}
	};
	return (0);
}

/*
 * Free autofs_args structure
 */
void
free_autofs_args(autofs_args *p)
{
	if (p == NULL)
		return;
	if (p->addr.buf)
		free(p->addr.buf);
	if (p->path)
		free(p->path);
	if (p->opts)
		free(p->opts);
	if (p->map)
		free(p->map);
	if (p->subdir)
		free(p->subdir);
	if (p->key)
		free(p->key);
	free(p);
}

/*
 * free mounta structure. Assumes that m->dataptr has
 * been freed already
 */
void
free_mounta(struct mounta *m)
{
	if (m == NULL)
		return;
	if (m->spec)
		free(m->spec);
	if (m->dir)
		free(m->dir);
	if (m->fstype)
		free(m->fstype);
	if (m->optptr)
		free(m->optptr);
	assert(m->dataptr == NULL);
	assert(m->datalen == 0);
	/*
	 * no need to free 'm' since it is part of the
	 * action_list_entry structure.
	 */
}
/*
 * 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
 */
/*
 *	autod_lookup.c
 *
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <syslog.h>
#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include "automount.h"

int
do_lookup1(
	char *mapname,
	char *key,
	char *subdir,
	char *mapopts,
	char *path,
	uint_t isdirect,
	uid_t uid,
	autofs_action_t *action,
	struct linka *linkp)
{
	struct mapline ml;
	struct mapent *mapents = NULL;
	int err;
	struct autofs_rddir_cache *rdcp;
	int found = 0;
	bool_t iswildcard = FALSE;
	bool_t isrestricted = hasrestrictopt(mapopts);
	char *stack[STACKSIZ];
	char **stkptr = stack;

	/*
	 * Default action is for no work to be done by kernel AUTOFS.
	 */
	*action = AUTOFS_NONE;

	/*
	 * Is there a cache for this map?
	 */
	rw_rdlock(&autofs_rddir_cache_lock);
	err = autofs_rddir_cache_lookup(mapname, &rdcp);
	if (!err && rdcp->full) {
		rw_unlock(&autofs_rddir_cache_lock);
		/*
		 * Try to lock readdir cache entry for reading, if
		 * the entry can not be locked, then avoid blocking
		 * and go to the name service. I'm assuming it is
		 * faster to go to the name service than to wait for
		 * the cache to be populated.
		 */
		if (rw_tryrdlock(&rdcp->rwlock) == 0) {
			found = (rddir_entry_lookup(key, rdcp->entp) != NULL);
			rw_unlock(&rdcp->rwlock);
		}
	} else
		rw_unlock(&autofs_rddir_cache_lock);

	if (!err) {
		/*
		 * release reference on cache entry
		 */
		mutex_lock(&rdcp->lock);
		rdcp->in_use--;
		assert(rdcp->in_use >= 0);
		mutex_unlock(&rdcp->lock);
	}

	if (found)
		return (0);

	/*
	 * entry not found in cache, try the name service now
	 */
	err = 0;

	/* initialize the stack of open files for this thread */
	stack_op(INIT, NULL, stack, &stkptr);

	err = getmapent(key, mapname, &ml, stack, &stkptr, &iswildcard,
		isrestricted);
	if (err == 0) /* call parser w default mount_access = TRUE */
		mapents = parse_entry(key, mapname, mapopts, &ml,
				    subdir, isdirect, TRUE);

	/*
	 * Now we indulge in a bit of hanky-panky.
	 * If the entry isn't found in the map and the
	 * name begins with an "=" then we assume that
	 * the name is an undocumented control message
	 * for the daemon.  This is accessible only
	 * to superusers.
	 */
	if (mapents == NULL && *action == AUTOFS_NONE) {
		if (*key == '=' && uid == 0) {
			if (isdigit(*(key+1))) {
				/*
				 * If next character is a digit
				 * then set the trace level.
				 */
				trace = atoi(key+1);
				trace_prt(1, "Automountd: trace level = %d\n",
					trace);
			} else if (*(key+1) == 'v') {
				/*
				 * If it's a "v" then
				 * toggle verbose mode.
				 */
				verbose = !verbose;
				trace_prt(1, "Automountd: verbose %s\n",
						verbose ? "on" : "off");
			}
		}

		err = ENOENT;
		goto done;
	}

	/*
	 * Each mapent in the list describes a mount to be done.
	 * Since I'm only doing a lookup, I only care whether a mapentry
	 * was found or not. The mount will be done on a later RPC to
	 * do_mount1.
	 */
	if (mapents == NULL && *action == AUTOFS_NONE)
		err = ENOENT;

done:	if (mapents)
		free_mapent(mapents);

	if (*action == AUTOFS_NONE && (iswildcard == TRUE)) {
		*action = AUTOFS_MOUNT_RQ;
	}
	if (trace > 1) {
		trace_prt(1, "  do_lookup1: action=%d wildcard=%s error=%d\n",
			*action, iswildcard ? "TRUE" : "FALSE", err);
	}
	return (err);
}
/*
 * 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) 2010, Oracle and/or its affiliates. All rights reserved.
 */


#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <memory.h>
#include <stropts.h>
#include <netconfig.h>
#include <stdarg.h>
#include <sys/resource.h>
#include <sys/systeminfo.h>
#include <syslog.h>
#include <errno.h>
#include <sys/sockio.h>
#include <rpc/xdr.h>
#include <net/if.h>
#include <netdir.h>
#include <string.h>
#include <thread.h>
#include <locale.h>
#include <door.h>
#include <limits.h>
#include "automount.h"
#include <sys/vfs.h>
#include <sys/mnttab.h>
#include <arpa/inet.h>
#include <rpcsvc/daemon_utils.h>
#include <deflt.h>
#include <strings.h>
#include <priv.h>
#include <tsol/label.h>
#include <sys/utsname.h>
#include <sys/thread.h>
#include <nfs/rnode.h>
#include <nfs/nfs.h>
#include <wait.h>
#include <libshare.h>
#include <libscf.h>
#include "smfcfg.h"

static void autofs_doorfunc(void *, char *, size_t, door_desc_t *, uint_t);
static void autofs_setdoor(int);
static void autofs_mntinfo_1_r(autofs_lookupargs *, autofs_mountres *);
static void autofs_mount_1_free_r(struct autofs_mountres *);
static void autofs_lookup_1_r(autofs_lookupargs *, autofs_lookupres *);
static void autofs_lookup_1_free_args(autofs_lookupargs *);
static void autofs_unmount_1_r(umntrequest *, umntres *);
static void autofs_unmount_1_free_args(umntrequest *);
static void autofs_readdir_1_r(autofs_rddirargs *, autofs_rddirres *);
static void autofs_readdir_1_free_r(struct autofs_rddirres *);
static int decode_args(xdrproc_t, autofs_door_args_t *, caddr_t *, int);
static bool_t encode_res(xdrproc_t, autofs_door_res_t **, caddr_t, int *);
static void usage();
static void warn_hup(int);
static void free_action_list();
static int start_autofs_svcs();
static void automountd_wait_for_cleanup(pid_t);

/*
 * Private autofs system call
 */
extern int _autofssys(int, void *);

#define	CTIME_BUF_LEN 26

#define	RESOURCE_FACTOR 8
#ifdef DEBUG
#define	AUTOFS_DOOR	"/var/run/autofs_door"
#endif /* DEBUG */

static thread_key_t	s_thr_key;

struct autodir *dir_head;
struct autodir *dir_tail;
char self[64];

time_t timenow;
int verbose = 0;
int trace = 0;
int automountd_nobrowse = 0;
int did_fork_exec;

int
main(argc, argv)
	int argc;
	char *argv[];

{
	pid_t pid;
	int c, error;
	struct rlimit rlset;
	char defval[6];
	int ret = 0, bufsz;

	if (geteuid() != 0) {
		(void) fprintf(stderr, "%s must be run as root\n", argv[0]);
		exit(1);
	}

	/*
	 * Read in the values from SMF first before we check
	 * commandline options so the options override the file.
	 */
	bufsz = 6;
	ret = autofs_smf_get_prop("automountd_verbose", defval,
	    DEFAULT_INSTANCE, SCF_TYPE_BOOLEAN, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK) {
		if (strncasecmp("true", defval, 4) == 0)
			verbose = TRUE;
		else
			verbose = FALSE;
	}
	bufsz = 6;
	ret = autofs_smf_get_prop("nobrowse", defval, DEFAULT_INSTANCE,
	    SCF_TYPE_BOOLEAN, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK) {
		if (strncasecmp("true", defval, 4) == 0)
			automountd_nobrowse = TRUE;
		else
			automountd_nobrowse = FALSE;
	}
	bufsz = 6;
	ret = autofs_smf_get_prop("trace", defval, DEFAULT_INSTANCE,
	    SCF_TYPE_INTEGER, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK) {
		errno = 0;
		trace = strtol(defval, (char **)NULL, 10);
		if (errno != 0)
			trace = 0;
	}
	put_automountd_env();

	while ((c = getopt(argc, argv, "vnTD:")) != EOF) {
		switch (c) {
		case 'v':
			verbose++;
			break;
		case 'n':
			automountd_nobrowse++;
			break;
		case 'T':
			trace++;
			break;
		case 'D':
			(void) putenv(optarg);
			break;
		default:
			usage();
		}
	}

	if (sysinfo(SI_HOSTNAME, self, sizeof (self)) == -1) {
		error = errno;
		(void) fprintf(stderr,
			"automountd: can't determine hostname, error: %d\n",
			error);
		exit(1);
	}

#ifndef DEBUG
	pid = fork();
	if (pid < 0) {
		perror("cannot fork");
		exit(1);
	}
	if (pid)
		exit(0);
#endif

	(void) setsid();
	openlog("automountd", LOG_PID, LOG_DAEMON);
	(void) setlocale(LC_ALL, "");

	/*
	 * Create the door_servers to manage fork/exec requests for
	 * mounts and executable automount maps
	 */
	if ((did_fork_exec = door_create(automountd_do_fork_exec,
	    NULL, 0)) == -1) {
		syslog(LOG_ERR, "door_create failed: %m, Exiting.");
		exit(errno);
	}
	if ((did_exec_map = door_create(automountd_do_exec_map,
	    NULL, 0)) == -1) {
		syslog(LOG_ERR, "door_create failed: %m, Exiting.");
		if (door_revoke(did_fork_exec) == -1) {
			syslog(LOG_ERR, "failed to door_revoke(%d) %m",
			    did_fork_exec);
		}
		exit(errno);
	}
	/*
	 * Before we become multithreaded we fork allowing the parent
	 * to become a door server to handle all mount and unmount
	 * requests. This works around a potential hang in using
	 * fork1() within a multithreaded environment
	 */

	pid = fork1();
	if (pid < 0) {
		syslog(LOG_ERR,
			"can't fork the automountd mount process %m");
		if (door_revoke(did_fork_exec) == -1) {
			syslog(LOG_ERR, "failed to door_revoke(%d) %m",
				did_fork_exec);
		}
		if (door_revoke(did_exec_map) == -1) {
			syslog(LOG_ERR, "failed to door_revoke(%d) %m",
				did_exec_map);
		}
		exit(1);
	} else if (pid > 0) {
		/* this is the door server process */
		automountd_wait_for_cleanup(pid);
	}


	(void) rwlock_init(&cache_lock, USYNC_THREAD, NULL);
	(void) rwlock_init(&autofs_rddir_cache_lock, USYNC_THREAD, NULL);

	/*
	 * initialize the name services, use NULL arguments to ensure
	 * we don't initialize the stack of files used in file service
	 */
	(void) ns_setup(NULL, NULL);

	/*
	 * we're using doors and its thread management now so we need to
	 * make sure we have more than the default of 256 file descriptors
	 * available.
	 */
	rlset.rlim_cur = RLIM_INFINITY;
	rlset.rlim_max = RLIM_INFINITY;
	if (setrlimit(RLIMIT_NOFILE, &rlset) == -1)
		syslog(LOG_ERR, "setrlimit failed for %s: %s", AUTOMOUNTD,
		    strerror(errno));

	(void) enable_extended_FILE_stdio(-1, -1);

	/*
	 * establish our lock on the lock file and write our pid to it.
	 * exit if some other process holds the lock, or if there's any
	 * error in writing/locking the file.
	 */
	pid = _enter_daemon_lock(AUTOMOUNTD);
	switch (pid) {
	case 0:
		break;
	case -1:
		syslog(LOG_ERR, "error locking for %s: %m", AUTOMOUNTD);
		exit(2);
	default:
		/* daemon was already running */
		exit(0);
	}

	/*
	 * If we coredump it'll be /core.
	 */
	if (chdir("/") < 0)
		syslog(LOG_ERR, "chdir /: %m");

	/*
	 * Create cache_cleanup thread
	 */
	if (thr_create(NULL, 0, (void *(*)(void *))cache_cleanup, NULL,
			THR_DETACHED | THR_DAEMON | THR_NEW_LWP, NULL)) {
		syslog(LOG_ERR, "unable to create cache_cleanup thread");
		exit(1);
	}

	/* other initializations */
	(void) rwlock_init(&portmap_cache_lock, USYNC_THREAD, NULL);

	/*
	 * On a labeled system, allow read-down nfs mounts if privileged
	 * (PRIV_NET_MAC_AWARE) to do so.  Otherwise, ignore the error
	 * and "mount equal label only" behavior will result.
	 */
	if (is_system_labeled()) {
		(void) setpflags(NET_MAC_AWARE, 1);
		(void) setpflags(NET_MAC_AWARE_INHERIT, 1);
	}

	(void) signal(SIGHUP, warn_hup);

	/* start services */
	return (start_autofs_svcs());

}

/*
 * The old automounter supported a SIGHUP
 * to allow it to resynchronize internal
 * state with the /etc/mnttab.
 * This is no longer relevant, but we
 * need to catch the signal and warn
 * the user.
 */
/* ARGSUSED */
static void
warn_hup(i)
	int i;
{
	syslog(LOG_ERR, "SIGHUP received: ignored");
	(void) signal(SIGHUP, warn_hup);
}

static void
usage()
{
	(void) fprintf(stderr, "Usage: automountd\n"
	    "\t[-T]\t\t(trace requests)\n"
	    "\t[-v]\t\t(verbose error msgs)\n"
	    "\t[-D n=s]\t(define env variable)\n");
	exit(1);
	/* NOTREACHED */
}

static void
autofs_readdir_1_r(
	autofs_rddirargs *req,
	autofs_rddirres *res)
{
	if (trace > 0)
		trace_prt(1, "READDIR REQUEST	: %s @ %ld\n",
		    req->rda_map, req->rda_offset);

	do_readdir(req, res);
	if (trace > 0)
		trace_prt(1, "READDIR REPLY	: status=%d\n", res->rd_status);
}

static void
autofs_readdir_1_free_r(struct autofs_rddirres *res)
{
	if (res->rd_status == AUTOFS_OK) {
		if (res->rd_rddir.rddir_entries)
			free(res->rd_rddir.rddir_entries);
	}
}


/* ARGSUSED */
static void
autofs_unmount_1_r(
	umntrequest *m,
	umntres *res)
{
	struct umntrequest *ul;

	if (trace > 0) {
		char ctime_buf[CTIME_BUF_LEN];
		if (ctime_r(&timenow, ctime_buf, CTIME_BUF_LEN) == NULL)
			ctime_buf[0] = '\0';

		trace_prt(1, "UNMOUNT REQUEST: %s", ctime_buf);
		for (ul = m; ul; ul = ul->next)
			trace_prt(1, " resource=%s fstype=%s mntpnt=%s"
			    " mntopts=%s %s\n",
			    ul->mntresource,
			    ul->fstype,
			    ul->mntpnt,
			    ul->mntopts,
			    ul->isdirect ? "direct" : "indirect");
	}


	res->status = do_unmount1(m);

	if (trace > 0)
		trace_prt(1, "UNMOUNT REPLY: status=%d\n", res->status);
}

static void
autofs_lookup_1_r(
	autofs_lookupargs *m,
	autofs_lookupres *res)
{
	autofs_action_t action;
	struct	linka link;
	int status;

	if (trace > 0) {
		char ctime_buf[CTIME_BUF_LEN];
		if (ctime_r(&timenow, ctime_buf, CTIME_BUF_LEN) == NULL)
			ctime_buf[0] = '\0';

		trace_prt(1, "LOOKUP REQUEST: %s", ctime_buf);
		trace_prt(1, "  name=%s[%s] map=%s opts=%s path=%s direct=%d\n",
		    m->name, m->subdir, m->map, m->opts, m->path, m->isdirect);
	}

	bzero(&link, sizeof (struct linka));

	status = do_lookup1(m->map, m->name, m->subdir, m->opts, m->path,
	    (uint_t)m->isdirect, m->uid, &action, &link);
	if (status == 0) {
		/*
		 * Return action list to kernel.
		 */
		res->lu_res = AUTOFS_OK;
		if ((res->lu_type.action = action) == AUTOFS_LINK_RQ) {
			res->lu_type.lookup_result_type_u.lt_linka = link;
		}
	} else {
		/*
		 * Entry not found
		 */
		res->lu_res = AUTOFS_NOENT;
	}
	res->lu_verbose = verbose;

	if (trace > 0)
		trace_prt(1, "LOOKUP REPLY    : status=%d\n", res->lu_res);
}

static void
autofs_mntinfo_1_r(
	autofs_lookupargs *m,
	autofs_mountres *res)
{
	int status;
	action_list		*alp = NULL;

	if (trace > 0) {
		char ctime_buf[CTIME_BUF_LEN];
		if (ctime_r(&timenow, ctime_buf, CTIME_BUF_LEN) == NULL)
			ctime_buf[0] = '\0';

		trace_prt(1, "MOUNT REQUEST:   %s", ctime_buf);
		trace_prt(1, "  name=%s[%s] map=%s opts=%s path=%s direct=%d\n",
		    m->name, m->subdir, m->map, m->opts, m->path, m->isdirect);
	}

	status = do_mount1(m->map, m->name, m->subdir, m->opts, m->path,
	    (uint_t)m->isdirect, m->uid, &alp, DOMOUNT_USER);
	if (status != 0) {
		/*
		 * An error occurred, free action list if allocated.
		 */
		if (alp != NULL) {
			free_action_list(alp);
			alp = NULL;
		}
	}
	if (alp != NULL) {
		/*
		 * Return action list to kernel.
		 */
		res->mr_type.status = AUTOFS_ACTION;
		res->mr_type.mount_result_type_u.list = alp;
	} else {
		/*
		 * No work to do left for the kernel
		 */
		res->mr_type.status = AUTOFS_DONE;
		res->mr_type.mount_result_type_u.error = status;
	}

	if (trace > 0) {
		switch (res->mr_type.status) {
		case AUTOFS_ACTION:
			trace_prt(1,
			    "MOUNT REPLY    : status=%d, AUTOFS_ACTION\n",
			    status);
			break;
		case AUTOFS_DONE:
			trace_prt(1,
			    "MOUNT REPLY    : status=%d, AUTOFS_DONE\n",
			    status);
			break;
		default:
			trace_prt(1, "MOUNT REPLY    : status=%d, UNKNOWN\n",
			    status);
		}
	}

	if (status && verbose) {
		if (m->isdirect) {
			/* direct mount */
			syslog(LOG_ERR, "mount of %s failed", m->path);
		} else {
			/* indirect mount */
			syslog(LOG_ERR,
			    "mount of %s/%s failed", m->path, m->name);
		}
	}
}

static void
autofs_mount_1_free_r(struct autofs_mountres *res)
{
	if (res->mr_type.status == AUTOFS_ACTION) {
		if (trace > 2)
			trace_prt(1, "freeing action list\n");
		free_action_list(res->mr_type.mount_result_type_u.list);
	}
}

/*
 * Used for reporting messages from code shared with automount command.
 * Formats message into a buffer and calls syslog.
 *
 * Print an error.  Works like printf (fmt string and variable args)
 * except that it will subsititute an error message for a "%m" string
 * (like syslog).
 */
void
pr_msg(const char *fmt, ...)
{
	va_list ap;
	char fmtbuff[BUFSIZ], buff[BUFSIZ];
	const char *p1;
	char *p2;

	p2 = fmtbuff;
	fmt = gettext(fmt);

	for (p1 = fmt; *p1; p1++) {
		if (*p1 == '%' && *(p1 + 1) == 'm') {
			(void) strcpy(p2, strerror(errno));
			p2 += strlen(p2);
			p1++;
		} else {
			*p2++ = *p1;
		}
	}
	if (p2 > fmtbuff && *(p2-1) != '\n')
		*p2++ = '\n';
	*p2 = '\0';

	va_start(ap, fmt);
	(void) vsprintf(buff, fmtbuff, ap);
	va_end(ap);
	syslog(LOG_ERR, buff);
}

static void
free_action_list(action_list *alp)
{
	action_list *p, *next = NULL;
	struct mounta *mp;

	for (p = alp; p != NULL; p = next) {
		switch (p->action.action) {
		case AUTOFS_MOUNT_RQ:
			mp = &(p->action.action_list_entry_u.mounta);
			/* LINTED pointer alignment */
			if (mp->fstype) {
				if (strcmp(mp->fstype, "autofs") == 0) {
					free_autofs_args((autofs_args *)
					    mp->dataptr);
				} else if (strncmp(mp->fstype, "nfs", 3) == 0) {
					free_nfs_args((struct nfs_args *)
					    mp->dataptr);
				}
			}
			mp->dataptr = NULL;
			mp->datalen = 0;
			free_mounta(mp);
			break;
		case AUTOFS_LINK_RQ:
			syslog(LOG_ERR,
			    "non AUTOFS_MOUNT_RQ requests not implemented\n");
			break;
		default:
			syslog(LOG_ERR,
			    "non AUTOFS_MOUNT_RQ requests not implemented\n");
			break;
		}
		next = p->next;
		free(p);
	}
}

static void
autofs_lookup_1_free_args(autofs_lookupargs *args)
{
	if (args->map)
		free(args->map);
	if (args->path)
		free(args->path);
	if (args->name)
		free(args->name);
	if (args->subdir)
		free(args->subdir);
	if (args->opts)
		free(args->opts);
}

static void
autofs_unmount_1_free_args(umntrequest *args)
{
	if (args->mntresource)
		free(args->mntresource);
	if (args->mntpnt)
		free(args->mntpnt);
	if (args->fstype)
		free(args->fstype);
	if (args->mntopts)
		free(args->mntopts);
	if (args->next)
		autofs_unmount_1_free_args(args->next);
}

static void
autofs_setdoor(int did)
{

	if (did < 0) {
		did = 0;
	}

	(void) _autofssys(AUTOFS_SETDOOR, &did);
}

void *
autofs_get_buffer(size_t size)
{
	autofs_tsd_t *tsd = NULL;

	/*
	 * Make sure the buffer size is aligned
	 */
	(void) thr_getspecific(s_thr_key, (void **)&tsd);
	if (tsd == NULL) {
		tsd = (autofs_tsd_t *)malloc(sizeof (autofs_tsd_t));
		if (tsd == NULL) {
			return (NULL);
		}
		tsd->atsd_buf = malloc(size);
		if (tsd->atsd_buf != NULL)
			tsd->atsd_len = size;
		else
			tsd->atsd_len = 0;
		(void) thr_setspecific(s_thr_key, tsd);
	} else {
		if (tsd->atsd_buf && (tsd->atsd_len < size)) {
			free(tsd->atsd_buf);
			tsd->atsd_buf = malloc(size);
			if (tsd->atsd_buf != NULL)
				tsd->atsd_len = size;
			else {
				tsd->atsd_len = 0;
			}
		}
	}
	if (tsd->atsd_buf) {
		bzero(tsd->atsd_buf, size);
		return (tsd->atsd_buf);
	} else {
		syslog(LOG_ERR,
		    gettext("Can't Allocate tsd buffer, size %d"), size);
		return (NULL);
	}
}

/*
 * Each request will automatically spawn a new thread with this
 * as its entry point.
 */
/* ARGUSED */
static void
autofs_doorfunc(
	void *cookie,
	char *argp,
	size_t arg_size,
	door_desc_t *dp,
	uint_t n_desc)
{
	char			*res;
	int			 res_size;
	int			 which;
	int			 error = 0;
	int			 srsz = 0;
	autofs_lookupargs	*xdrargs;
	autofs_lookupres	 lookup_res;
	autofs_rddirargs	*rddir_args;
	autofs_rddirres		 rddir_res;
	autofs_mountres		 mount_res;
	umntrequest		*umnt_args;
	umntres			 umount_res;
	autofs_door_res_t	*door_res;
	autofs_door_res_t	 failed_res;

	if (arg_size < sizeof (autofs_door_args_t)) {
		failed_res.res_status = EINVAL;
		error = door_return((char *)&failed_res,
		    sizeof (autofs_door_res_t), NULL, 0);
		/*
		 * If we got here the door_return() failed.
		 */
		syslog(LOG_ERR, "Bad argument, door_return failure %d", error);
		return;
	}

	timenow = time((time_t *)NULL);

	which = ((autofs_door_args_t *)argp)->cmd;
	switch (which) {
	case AUTOFS_LOOKUP:
		if (error = decode_args(xdr_autofs_lookupargs,
		    (autofs_door_args_t *)argp, (caddr_t *)&xdrargs,
		    sizeof (autofs_lookupargs))) {
			syslog(LOG_ERR,
			    "error allocating lookup arguments buffer");
			failed_res.res_status = error;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = 0;
			break;
		}
		bzero(&lookup_res, sizeof (autofs_lookupres));

		autofs_lookup_1_r(xdrargs, &lookup_res);

		autofs_lookup_1_free_args(xdrargs);
		free(xdrargs);

		if (!encode_res(xdr_autofs_lookupres, &door_res,
		    (caddr_t)&lookup_res, &res_size)) {
			syslog(LOG_ERR,
			    "error allocating lookup results buffer");
			failed_res.res_status = EINVAL;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
		} else {
			door_res->res_status = 0;
			res = (caddr_t)door_res;
		}
		break;

	case AUTOFS_MNTINFO:
		if (error = decode_args(xdr_autofs_lookupargs,
		    (autofs_door_args_t *)argp, (caddr_t *)&xdrargs,
		    sizeof (autofs_lookupargs))) {
			syslog(LOG_ERR,
			    "error allocating lookup arguments buffer");
			failed_res.res_status = error;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = 0;
			break;
		}

		autofs_mntinfo_1_r((autofs_lookupargs *)xdrargs, &mount_res);

		autofs_lookup_1_free_args(xdrargs);
		free(xdrargs);

		/*
		 * Only reason we would get a NULL res is because
		 * we could not allocate a results buffer.  Use
		 * a local one to return the error EAGAIN as has
		 * always been done when memory allocations fail.
		 */
		if (!encode_res(xdr_autofs_mountres, &door_res,
		    (caddr_t)&mount_res, &res_size)) {
			syslog(LOG_ERR,
			    "error allocating mount results buffer");
			failed_res.res_status = EAGAIN;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
		} else {
			door_res->res_status = 0;
			res = (caddr_t)door_res;
		}
		autofs_mount_1_free_r(&mount_res);
		break;

	case AUTOFS_UNMOUNT:
		if (error = decode_args(xdr_umntrequest,
		    (autofs_door_args_t *)argp,
		    (caddr_t *)&umnt_args, sizeof (umntrequest))) {
			syslog(LOG_ERR,
			    "error allocating unmount argument buffer");
			failed_res.res_status = error;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = sizeof (autofs_door_res_t);
			break;
		}

		autofs_unmount_1_r(umnt_args, &umount_res);

		error = umount_res.status;

		autofs_unmount_1_free_args(umnt_args);
		free(umnt_args);

		if (!encode_res(xdr_umntres, &door_res, (caddr_t)&umount_res,
		    &res_size)) {
			syslog(LOG_ERR,
			    "error allocating unmount results buffer");
			failed_res.res_status = EINVAL;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = sizeof (autofs_door_res_t);
		} else {
			door_res->res_status = 0;
			res = (caddr_t)door_res;
		}
		break;

	case AUTOFS_READDIR:
		if (error = decode_args(xdr_autofs_rddirargs,
		    (autofs_door_args_t *)argp,
		    (caddr_t *)&rddir_args,
		    sizeof (autofs_rddirargs))) {
			syslog(LOG_ERR,
			    "error allocating readdir argument buffer");
			failed_res.res_status = error;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = sizeof (autofs_door_res_t);
			break;
		}

		autofs_readdir_1_r(rddir_args, &rddir_res);

		free(rddir_args->rda_map);
		free(rddir_args);

		if (!encode_res(xdr_autofs_rddirres, &door_res,
		    (caddr_t)&rddir_res, &res_size)) {
			syslog(LOG_ERR,
			    "error allocating readdir results buffer");
			failed_res.res_status = ENOMEM;
			failed_res.xdr_len = 0;
			res = (caddr_t)&failed_res;
			res_size = sizeof (autofs_door_res_t);
		} else {
			door_res->res_status = 0;
			res = (caddr_t)door_res;
		}
		autofs_readdir_1_free_r(&rddir_res);
		break;
#ifdef MALLOC_DEBUG
	case AUTOFS_DUMP_DEBUG:
			check_leaks("/var/tmp/automountd.leak");
			error = door_return(NULL, 0, NULL, 0);
			/*
			 * If we got here, door_return() failed
			 */
			syslog(LOG_ERR, "dump debug door_return failure %d",
			    error);
			return;
#endif
	case NULLPROC:
			res = NULL;
			res_size = 0;
			break;
	default:
			failed_res.res_status = EINVAL;
			res = (char *)&failed_res;
			res_size = sizeof (autofs_door_res_t);
			break;
	}

	srsz = res_size;
	errno = 0;
	error = door_return(res, res_size, NULL, 0);

	if (errno == E2BIG) {
		/*
		 * Failed due to encoded results being bigger than the
		 * kernel expected bufsize. Passing actual results size
		 * back down to kernel.
		 */
		failed_res.res_status = EOVERFLOW;
		failed_res.xdr_len = srsz;
		res = (caddr_t)&failed_res;
		res_size = sizeof (autofs_door_res_t);
	} else {
		syslog(LOG_ERR, "door_return failed %d, buffer %p, "
		    "buffer size %d", error, (void *)res, res_size);
		res = NULL;
		res_size = 0;
	}
	(void) door_return(res, res_size, NULL, 0);
	/* NOTREACHED */
}

static int
start_autofs_svcs(void)
{
	int doorfd;
#ifdef DEBUG
	int dfd;
#endif

	if ((doorfd = door_create(autofs_doorfunc, NULL,
	    DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) == -1) {
		syslog(LOG_ERR, gettext("Unable to create door\n"));
		return (1);
	}

#ifdef DEBUG
	/*
	 * Create a file system path for the door
	 */
	if ((dfd = open(AUTOFS_DOOR, O_RDWR|O_CREAT|O_TRUNC,
	    S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1) {
		syslog(LOG_ERR, "Unable to open %s: %m\n", AUTOFS_DOOR);
		(void) close(doorfd);
		return (1);
	}

	/*
	 * stale associations clean up
	 */
	(void) fdetach(AUTOFS_DOOR);

	/*
	 * Register in the namespace to the kernel to door_ki_open.
	 */
	if (fattach(doorfd, AUTOFS_DOOR) == -1) {
		syslog(LOG_ERR, "Unable to fattach door %m\n", AUTOFS_DOOR);
		(void) close(dfd);
		(void) close(doorfd);
		return (1);
	}
#endif /* DEBUG */

	/*
	 * Pass door name to kernel for door_ki_open
	 */
	autofs_setdoor(doorfd);

	(void) thr_keycreate(&s_thr_key, NULL);

	/*
	 * Wait for incoming calls
	 */
	/*CONSTCOND*/
	while (1)
		(void) pause();

	/* NOTREACHED */
	syslog(LOG_ERR, gettext("Door server exited"));
	return (10);
}

static int
decode_args(
	xdrproc_t xdrfunc,
	autofs_door_args_t *argp,
	caddr_t *xdrargs,
	int size)
{
	XDR xdrs;

	caddr_t tmpargs = (caddr_t)&((autofs_door_args_t *)argp)->xdr_arg;
	size_t arg_size = ((autofs_door_args_t *)argp)->xdr_len;

	xdrmem_create(&xdrs, tmpargs, arg_size, XDR_DECODE);

	*xdrargs = malloc(size);
	if (*xdrargs == NULL) {
		syslog(LOG_ERR, "error allocating arguments buffer");
		return (ENOMEM);
	}

	bzero(*xdrargs, size);

	if (!(*xdrfunc)(&xdrs, *xdrargs)) {
		free(*xdrargs);
		*xdrargs = NULL;
		syslog(LOG_ERR, "error decoding arguments");
		return (EINVAL);
	}

	return (0);
}


static bool_t
encode_res(
	xdrproc_t xdrfunc,
	autofs_door_res_t **results,
	caddr_t resp,
	int *size)
{
	XDR xdrs;

	*size = xdr_sizeof((*xdrfunc), resp);
	*results = autofs_get_buffer(
	    sizeof (autofs_door_res_t) + *size);
	if (*results == NULL) {
		(*results)->res_status = ENOMEM;
		return (FALSE);
	}
	(*results)->xdr_len = *size;
	*size = sizeof (autofs_door_res_t) + (*results)->xdr_len;
	xdrmem_create(&xdrs, (caddr_t)((*results)->xdr_res),
	    (*results)->xdr_len, XDR_ENCODE);
	if (!(*xdrfunc)(&xdrs, resp)) {
		(*results)->res_status = EINVAL;
		syslog(LOG_ERR, "error encoding results");
		return (FALSE);
	}
	(*results)->res_status = 0;
	return (TRUE);
}

static void
automountd_wait_for_cleanup(pid_t pid)
{
	int status;
	int child_exitval;

	/*
	 * Wait for the main automountd process to exit so we cleanup
	 */
	(void) waitpid(pid, &status, 0);

	child_exitval = WEXITSTATUS(status);

	/*
	 * Shutdown the door server for mounting and unmounting
	 * filesystems
	 */
	if (door_revoke(did_fork_exec) == -1) {
		syslog(LOG_ERR, "failed to door_revoke(%d) %m", did_fork_exec);
	}
	if (door_revoke(did_exec_map) == -1) {
		syslog(LOG_ERR, "failed to door_revoke(%d) %m", did_exec_map);
	}
	exit(child_exitval);
}
/*
 * 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
 */
/*
 *	autod_mount.c
 *
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <errno.h>
#include <pwd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/tiuser.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sys/fs/autofs.h>
#include <nfs/nfs.h>
#include <thread.h>
#include <limits.h>
#include <assert.h>
#include <fcntl.h>
#include <strings.h>

#include "automount.h"
#include "replica.h"

static int unmount_mntpnt(struct mnttab *);
static int call_fork_exec(char *, char *, char **, int);
static void remove_browse_options(char *);
static int inherit_options(char *, char **);

int
do_mount1(
	char *mapname,
	char *key,
	char *subdir,
	char *mapopts,
	char *path,
	uint_t isdirect,
	uid_t uid,
	action_list **alpp,
	int flags)
{
	struct mapline ml;
	struct mapent *me, *mapents = NULL;
	char mntpnt[MAXPATHLEN];
	char spec_mntpnt[MAXPATHLEN];
	int err = 0;
	char *private;	/* fs specific data. eg prevhost in case of nfs */
	int mount_ok = 0;
	ssize_t len;
	action_list *alp, *prev, *tmp;
	char root[MAXPATHLEN];
	int overlay = 1;
	char next_subdir[MAXPATHLEN];
	bool_t mount_access = TRUE;
	bool_t iswildcard;
	bool_t isrestricted = hasrestrictopt(mapopts);
	char *stack[STACKSIZ];
	char **stkptr = stack;

retry:
	iswildcard = FALSE;

	/* initialize the stack of open files for this thread */
	stack_op(INIT, NULL, stack, &stkptr);

	err = getmapent(key, mapname, &ml, stack, &stkptr, &iswildcard,
		isrestricted);
	if (err == 0) {
		mapents = parse_entry(key, mapname, mapopts, &ml,
				    subdir, isdirect, mount_access);
	}

	if (trace) {
		struct mapfs *mfs;
		trace_prt(1, "  do_mount1:\n");
		for (me = mapents; me; me = me->map_next) {
			trace_prt(1, "  (%s,%s)\t%s%s%s\n",
			me->map_fstype ? me->map_fstype : "",
			me->map_mounter ? me->map_mounter : "",
			path ? path : "",
			me->map_root  ? me->map_root : "",
			me->map_mntpnt ? me->map_mntpnt : "");
			trace_prt(0, "\t\t-%s\n",
			me->map_mntopts ? me->map_mntopts : "");

			for (mfs = me->map_fs; mfs; mfs = mfs->mfs_next)
				trace_prt(0, "\t\t%s:%s\tpenalty=%d\n",
					mfs->mfs_host ? mfs->mfs_host: "",
					mfs->mfs_dir ? mfs->mfs_dir : "",
					mfs->mfs_penalty);
		}
	}

	*alpp = NULL;

	/*
	 * Each mapent in the list describes a mount to be done.
	 * Normally there's just a single entry, though in the
	 * case of /net mounts there may be many entries, that
	 * must be mounted as a hierarchy.  For each mount the
	 * automountd must make sure the required mountpoint
	 * exists and invoke the appropriate mount command for
	 * the fstype.
	 */
	private = "";
	for (me = mapents; me && !err; me = me->map_next) {
		len = snprintf(mntpnt, sizeof (mntpnt), "%s%s%s", path,
		    mapents->map_root, me->map_mntpnt);

		if (len >= sizeof (mntpnt)) {
			free_mapent(mapents);
			return (ENAMETOOLONG);
		}
		/*
		 * remove trailing /'s from mountpoint to avoid problems
		 * stating a directory with two or more trailing slashes.
		 * This will let us mount directories from machines
		 * which export with two or more slashes (apollo for instance).
		 */
		len -= 1;
		while (mntpnt[len] == '/')
			mntpnt[len--] = '\0';

		(void) strcpy(spec_mntpnt, mntpnt);

		if (isrestricted &&
		    inherit_options(mapopts, &me->map_mntopts) != 0) {
			syslog(LOG_ERR, "malloc of options failed");
			free_mapent(mapents);
			return (EAGAIN);
		}

		if (strcmp(me->map_fstype, MNTTYPE_NFS) == 0) {
			remove_browse_options(me->map_mntopts);
			if (flags == DOMOUNT_KERNEL) {
				alp = (action_list *)malloc(
					sizeof (action_list));
				if (alp == NULL) {
					syslog(LOG_ERR,
						"malloc of alp failed");
					continue;
				}
				memset(alp, 0, sizeof (action_list));
			} else
				alp = NULL;
			err =
			    mount_nfs(me, spec_mntpnt, private, overlay, uid,
				    &alp);
			/*
			 * We must retry if we don't have access to the
			 * root file system and there are other
			 * following mapents. The reason we can't
			 * continue because the rest of the mapent list
			 * depends on whether mount_access is TRUE or FALSE.
			 */
			if (err == NFSERR_ACCES && me->map_next != NULL) {
				/*
				 * don't expect mount_access to be
				 * FALSE here, but we do a check
				 * anyway.
				 */
				if (mount_access == TRUE) {
					mount_access = FALSE;
					err = 0;
					free_mapent(mapents);
					if (alp) {
						free(alp);
						alp = NULL;
					}
					goto retry;
				}
			}
			if (alp) {
				if (*alpp == NULL)
					*alpp = alp;
				else {
					for (tmp = *alpp; tmp != NULL;
						tmp = tmp->next)
						prev = tmp;
					prev->next = alp;
				}
			}
			mount_ok = !err;
		} else if (strcmp(me->map_fstype, MNTTYPE_AUTOFS) == 0) {
			if (isdirect) {
				len = strlcpy(root, path, sizeof (root));
			} else {
				len = snprintf(root, sizeof (root), "%s/%s",
				    path, key);
			}
			if (len >= sizeof (root)) {
				free_mapent(mapents);
				return (ENAMETOOLONG);
			}

			alp = (action_list *)malloc(sizeof (action_list));
			if (alp == NULL) {
				syslog(LOG_ERR, "malloc of alp failed");
				continue;
			}
			memset(alp, 0, sizeof (action_list));

			/*
			 * get the next subidr, but only if its a modified
			 * or faked autofs mount
			 */
			if (me->map_modified || me->map_faked) {
				len = snprintf(next_subdir,
					sizeof (next_subdir), "%s%s", subdir,
					me->map_mntpnt);
			} else {
				next_subdir[0] = '\0';
				len = 0;
			}

			if (trace > 2)
				trace_prt(1, "  root=%s\t next_subdir=%s\n",
						root, next_subdir);
			if (len < sizeof (next_subdir)) {
				err = mount_autofs(me, spec_mntpnt, alp,
					root, next_subdir, key);
			} else {
				err = ENAMETOOLONG;
			}
			if (err == 0) {
				/*
				 * append to action list
				 */
				mount_ok++;
				if (*alpp == NULL)
					*alpp = alp;
				else {
					for (tmp = *alpp; tmp != NULL;
					    tmp = tmp->next)
						prev = tmp;
					prev->next = alp;
				}
			} else {
				free(alp);
				mount_ok = 0;
			}
		} else if (strcmp(me->map_fstype, MNTTYPE_LOFS) == 0) {
			remove_browse_options(me->map_mntopts);
			err = loopbackmount(me->map_fs->mfs_dir, spec_mntpnt,
					    me->map_mntopts, overlay);
			mount_ok = !err;
		} else {
			remove_browse_options(me->map_mntopts);
			err = mount_generic(me->map_fs->mfs_dir,
					    me->map_fstype, me->map_mntopts,
					    spec_mntpnt, overlay);
			mount_ok = !err;
		}
	}
	if (mapents)
		free_mapent(mapents);

	/*
	 * If an error occurred,
	 * the filesystem doesn't exist, or could not be
	 * mounted.  Return EACCES to autofs indicating that
	 * the mountpoint can not be accessed if this is not
	 * a wildcard access.  If it is a wildcard access we
	 * return ENOENT since the lookup that triggered
	 * this mount request will fail and the entry will not
	 * be available.
	 */
	if (mount_ok) {
		/*
		 * No error occurred, return 0 to indicate success.
		 */
		err = 0;
	} else {
		/*
		 * The filesystem does not exist or could not be mounted.
		 * Return ENOENT if the lookup was triggered by a wildcard
		 * access.  Wildcard entries only exist if they can be
		 * mounted.  They can not be listed otherwise (through
		 * a readdir(3C)).
		 * Return EACCES if the lookup was not triggered by a
		 * wildcard access.  Map entries that are explicitly defined
		 * in maps are visible via readdir(3C), therefore we return
		 * EACCES to indicate that the entry exists, but the directory
		 * can not be opened.  This is the same behavior of a Unix
		 * directory that exists, but has its execute bit turned off.
		 * The directory is there, but the user does not have access
		 * to it.
		 */
		if (iswildcard)
			err = ENOENT;
		else
			err = EACCES;
	}
	return (err);
}

#define	ARGV_MAX	16
#define	VFS_PATH	"/usr/lib/fs"

int
mount_generic(special, fstype, opts, mntpnt, overlay)
	char *special, *fstype, *opts, *mntpnt;
	int overlay;
{
	struct mnttab m;
	struct stat stbuf;
	int i, res;
	char *newargv[ARGV_MAX];

	if (trace > 1) {
		trace_prt(1, "  mount: %s %s %s %s\n",
			special, mntpnt, fstype, opts);
	}

	if (stat(mntpnt, &stbuf) < 0) {
		syslog(LOG_ERR, "Couldn't stat %s: %m", mntpnt);
		return (ENOENT);
	}

	i = 2;

	if (overlay)
		newargv[i++] = "-O";

	/*
	 *  Use "quiet" option to suppress warnings about unsupported
	 *  mount options.
	 */
	newargv[i++] = "-q";

	if (opts && *opts) {
		m.mnt_mntopts = opts;
		if (hasmntopt(&m, MNTOPT_RO) != NULL)
			newargv[i++] = "-r";
		newargv[i++] = "-o";
		newargv[i++] = opts;
	}
	newargv[i++] = "--";
	newargv[i++] = special;
	newargv[i++] = mntpnt;
	newargv[i] = NULL;
	res = call_fork_exec(fstype, "mount", newargv, verbose);
	if (res == 0 && trace > 1) {
		if (stat(mntpnt, &stbuf) == 0) {
			trace_prt(1, "  mount of %s dev=%x rdev=%x OK\n",
				mntpnt, stbuf.st_dev, stbuf.st_rdev);
		} else {
			trace_prt(1, "  failed to stat %s\n", mntpnt);
		}
	}
	return (res);
}

void
automountd_do_fork_exec(void *cookie, char *argp, size_t arg_size,
		door_desc_t *dfd, uint_t n_desc)
{
	int stat_loc;
	int fd = 0;
	struct stat stbuf;
	int res;
	int child_pid;
	command_t *command;
	char *newargv[ARGV_MAX];
	int i;


	command = (command_t *)argp;
	if (sizeof (*command) != arg_size) {
		res = EINVAL;
		door_return((char *)&res, sizeof (res), NULL, 0);
	}

	switch ((child_pid = fork1())) {
	case -1:
		syslog(LOG_ERR, "Cannot fork: %m");
		res = errno;
		break;
	case 0:
		/*
		 * Child
		 */
		(void) setsid();
		fd = open(command->console ? "/dev/console" : "/dev/null",
			    O_WRONLY);
		if (fd != -1) {
			(void) dup2(fd, 1);
			(void) dup2(fd, 2);
			(void) close(fd);
		}

		for (i = 0; *command->argv[i]; i++) {
			newargv[i] = strdup(command->argv[i]);
			if (newargv[i] == (char *)NULL) {
				syslog(LOG_ERR, "failed to copy argument '%s'"
				    " of %s: %m", command->argv[i],
				    command->file);
				_exit(errno);
			}
		}
		newargv[i] = NULL;

		(void) execv(command->file, newargv);
		if (errno == EACCES)
			syslog(LOG_ERR, "exec %s: %m", command->file);

		_exit(errno);
	default:
		/*
		 * Parent
		 */
		(void) waitpid(child_pid, &stat_loc, WUNTRACED);

		if (WIFEXITED(stat_loc)) {
			if (trace > 1) {
				trace_prt(1,
				    "  fork_exec: returns exit status %d\n",
				    WEXITSTATUS(stat_loc));
			}

			res = WEXITSTATUS(stat_loc);
		} else if (WIFSIGNALED(stat_loc)) {
			if (trace > 1)
				trace_prt(1,
				    "  fork_exec: returns signal status %d\n",
				    WTERMSIG(stat_loc));
			res = 1;
		} else {
			if (trace > 1)
				trace_prt(1,
				    "  fork_exec: returns unknown status\n");
			res = 1;
		}

	}
	door_return((char *)&res, sizeof (res), NULL, 0);
	trace_prt(1, "automountd_do_fork_exec, door return failed %s, %s\n",
	    command->file, strerror(errno));
	door_return(NULL, 0, NULL, 0);
}

int
do_unmount1(ur)
	umntrequest *ur;
{

	struct mnttab m;
	int res = 0;

	m.mnt_special = ur->mntresource;
	m.mnt_mountp = ur->mntpnt;
	m.mnt_fstype = ur->fstype;
	m.mnt_mntopts = ur->mntopts;
	/*
	 * Special case for NFS mounts.
	 * Don't want to attempt unmounts from
	 * a dead server.  If any member of a
	 * hierarchy belongs to a dead server
	 * give up (try later).
	 */
	if (strcmp(ur->fstype, MNTTYPE_NFS) == 0) {
		struct replica *list;
		int i, n;
		bool_t pubopt = FALSE;
		int nfs_port;
		int got_port;

		/*
		 * See if a port number was specified.  If one was
		 * specified that is too large to fit in 16 bits, truncate
		 * the high-order bits (for historical compatibility).  Use
		 * zero to indicate "no port specified".
		 */
		got_port = nopt(&m, MNTOPT_PORT, &nfs_port);
		if (!got_port)
			nfs_port = 0;
		nfs_port &= USHRT_MAX;

		if (hasmntopt(&m, MNTOPT_PUBLIC))
			pubopt = TRUE;

		list = parse_replica(ur->mntresource, &n);
		if (list == NULL) {
			if (n >= 0)
				syslog(LOG_ERR, "Memory allocation failed: %m");
			res = 1;
			goto done;
		}

		for (i = 0; i < n; i++) {
			if (pingnfs(list[i].host, 1, NULL, 0, nfs_port,
			    pubopt, list[i].path, NULL) != RPC_SUCCESS) {
				res = 1;
				free_replica(list, n);
				goto done;
			}
		}
		free_replica(list, n);
	}

	res = unmount_mntpnt(&m);

done:	return (res);
}

static int
unmount_mntpnt(mnt)
	struct mnttab *mnt;
{
	char *fstype = mnt->mnt_fstype;
	char *mountp = mnt->mnt_mountp;
	char *newargv[ARGV_MAX];
	int res;

	if (strcmp(fstype, MNTTYPE_NFS) == 0) {
		res = nfsunmount(mnt);
	} else if (strcmp(fstype, MNTTYPE_LOFS) == 0) {
		if ((res = umount(mountp)) < 0)
			res = errno;
	} else {
		newargv[2] = mountp;
		newargv[3] = NULL;

		res = call_fork_exec(fstype, "umount", newargv, verbose);
		if (res == ENOENT) {
			/*
			 * filesystem specific unmount command not found
			 */
			if ((res = umount(mountp)) < 0)
				res = errno;
		}
	}

	if (trace > 1)
		trace_prt(1, "  unmount %s %s\n",
			mountp, res ? "failed" : "OK");
	return (res);
}

/*
 * Remove the autofs specific options 'browse', 'nobrowse' and
 * 'restrict' from 'opts'.
 */
static void
remove_browse_options(char *opts)
{
	char *p, *pb;
	char buf[MAXOPTSLEN], new[MAXOPTSLEN];
	char *placeholder;

	new[0] = '\0';
	(void) strcpy(buf, opts);
	pb = buf;
	while (p = (char *)strtok_r(pb, ",", &placeholder)) {
		pb = NULL;
		if (strcmp(p, MNTOPT_NOBROWSE) != 0 &&
		    strcmp(p, MNTOPT_BROWSE) != 0 &&
		    strcmp(p, MNTOPT_RESTRICT) != 0) {
			if (new[0] != '\0')
				(void) strcat(new, ",");
			(void) strcat(new, p);
		}
	}
	(void) strcpy(opts, new);
}

static const char *restropts[] = {
	RESTRICTED_MNTOPTS
};
#define	NROPTS	(sizeof (restropts)/sizeof (restropts[0]))

static int
inherit_options(char *opts, char **mapentopts)
{
	int i;
	char *new;
	struct mnttab mtmap;
	struct mnttab mtopt;

	size_t len = strlen(*mapentopts);

	for (i = 0; i < NROPTS; i++)
		len += strlen(restropts[i]);

	/* "," for each new option plus the trailing NUL */
	len += NROPTS + 1;

	new = malloc(len);
	if (new == 0)
		return (-1);

	(void) strcpy(new, *mapentopts);

	mtmap.mnt_mntopts = *mapentopts;
	mtopt.mnt_mntopts = opts;

	for (i = 0; i < NROPTS; i++) {
		if (hasmntopt(&mtopt, (char *)restropts[i]) != NULL &&
		    hasmntopt(&mtmap, (char *)restropts[i]) == NULL) {
			if (*new != '\0')
				(void) strcat(new, ",");
			(void) strcat(new, restropts[i]);
		}
	}
	free(*mapentopts);
	*mapentopts = new;
	return (0);
}

bool_t
hasrestrictopt(char *opts)
{
	struct mnttab mt;

	mt.mnt_mntopts = opts;

	return (hasmntopt(&mt, MNTOPT_RESTRICT) != NULL);
}

static int
call_fork_exec(fstype, cmd, newargv, console)
	char *fstype;
	char *cmd;
	char **newargv;
	int console;
{
	command_t command;
	door_arg_t darg;
	char path[MAXPATHLEN];
	struct stat stbuf;
	int ret;
	int sz;
	int status;
	int i;

	bzero(&command, sizeof (command));
	/* build the full path name of the fstype dependent command */
	(void) snprintf(path, MAXPATHLEN, "%s/%s/%s", VFS_PATH, fstype, cmd);

	if (stat(path, &stbuf) != 0) {
		ret = errno;
		return (ret);
	}

	strlcpy(command.file, path, MAXPATHLEN);
	strlcpy(command.argv[0], path, MAXOPTSLEN);
	for (i = 2; newargv[i]; i++) {
		strlcpy(command.argv[i-1], newargv[i], MAXOPTSLEN);
	}
	if (trace > 1) {
		trace_prt(1, "  call_fork_exec: %s ", command.file);
		for (i = 0; *command.argv[i]; i++)
			trace_prt(0, "%s ", command.argv[i]);
		trace_prt(0, "\n");
	}

	command.console = console;

	darg.data_ptr = (char *)&command;
	darg.data_size = sizeof (command);
	darg.desc_ptr = NULL;
	darg.desc_num = 0;
	darg.rbuf = (char *)&status;
	darg.rsize = sizeof (status);

	ret = door_call(did_fork_exec, &darg);
	if (trace > 1) {
		trace_prt(1, "  call_fork_exec: door_call failed %d\n", ret);
	}

	return (status);
}
/*
 * 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 2015 Nexenta Systems, Inc.  All rights reserved.
 * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <syslog.h>
#include <string.h>
#include <deflt.h>
#include <kstat.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/signal.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include <sys/mount.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <sys/fstyp.h>
#include <sys/fsid.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netconfig.h>
#include <netdir.h>
#include <errno.h>
#define	NFSCLIENT
#include <nfs/nfs.h>
#include <nfs/mount.h>
#include <rpcsvc/mount.h>
#include <rpc/nettype.h>
#include <locale.h>
#include <setjmp.h>
#include <sys/socket.h>
#include <thread.h>
#include <limits.h>
#include <nss_dbdefs.h>			/* for NSS_BUFLEN_HOSTS */
#include <nfs/nfs_sec.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <assert.h>
#include <nfs/nfs_clnt.h>
#include <rpcsvc/nfs4_prot.h>
#include <nfs/nfs4.h>
#define	NO_RDDIR_CACHE
#include "automount.h"
#include "replica.h"
#include "nfs_subr.h"
#include "webnfs.h"
#include "nfs_resolve.h"
#include <sys/sockio.h>
#include <net/if.h>
#include <rpcsvc/daemon_utils.h>
#include <pwd.h>
#include <strings.h>
#include <tsol/label.h>
#include <zone.h>
#include <limits.h>
#include <libscf.h>
#include <libshare.h>
#include "smfcfg.h"

extern void set_nfsv4_ephemeral_mount_to(void);

extern char *nfs_get_qop_name();
extern AUTH *nfs_create_ah();
extern enum snego_stat nfs_sec_nego();

#define	MAXHOSTS	512

/*
 * host cache states
 */
#define	NOHOST		0
#define	GOODHOST	1
#define	DEADHOST	2

#define	NFS_ARGS_EXTB_secdata(args, secdata) \
	{ (args).nfs_args_ext = NFS_ARGS_EXTB, \
	(args).nfs_ext_u.nfs_extB.secdata = secdata; }

struct cache_entry {
	struct	cache_entry *cache_next;
	char	*cache_host;
	time_t	cache_time;
	int	cache_state;
	rpcvers_t cache_reqvers;
	rpcvers_t cache_outvers;
	char	*cache_proto;
};

struct mfs_snego_t {
	int sec_opt;
	bool_t snego_done;
	char *nfs_flavor;
	seconfig_t nfs_sec;
};
typedef struct mfs_snego_t mfs_snego_t;

static struct cache_entry *cache_head = NULL;
rwlock_t cache_lock;	/* protect the cache chain */

static enum nfsstat nfsmount(struct mapfs *, char *, char *, int, uid_t,
	action_list *);
static int is_nfs_port(char *);

static void netbuf_free(struct netbuf *);
static int get_pathconf(CLIENT *, char *, char *, struct pathcnf **, int);
static struct mapfs *enum_servers(struct mapent *, char *);
static struct mapfs *get_mysubnet_servers(struct mapfs *);
static int subnet_test(int af, struct sioc_addrreq *);
static	struct	netbuf *get_addr(char *, rpcprog_t, rpcvers_t,
	struct netconfig **, char *, ushort_t, struct t_info *);

static	struct	netbuf *get_pubfh(char *, rpcvers_t, mfs_snego_t *,
	struct netconfig **, char *, ushort_t, struct t_info *, caddr_t *,
	bool_t, char *);

static int create_homedir(const char *, const char *);

enum type_of_stuff {
	SERVER_ADDR = 0,
	SERVER_PING = 1,
	SERVER_FH = 2
};

static void *get_server_netinfo(enum type_of_stuff, char *, rpcprog_t,
	rpcvers_t, mfs_snego_t *, struct netconfig **, char *, ushort_t,
	struct t_info *, caddr_t *, bool_t, char *, enum clnt_stat *);
static void *get_netconfig_info(enum type_of_stuff, char *, rpcprog_t,
	rpcvers_t, struct netconfig *, ushort_t, struct t_info *,
	struct t_bind *, caddr_t *, bool_t, char *, enum clnt_stat *,
	mfs_snego_t *);
static void *get_server_addrorping(char *, rpcprog_t, rpcvers_t,
	struct netconfig *, ushort_t, struct t_info *, struct t_bind *,
	caddr_t *, bool_t, char *, enum clnt_stat *, int);
static void *get_server_fh(char *, rpcprog_t, rpcvers_t, mfs_snego_t *,
	struct netconfig *, ushort_t, struct t_info *, struct t_bind *,
	caddr_t *, bool_t, char *, enum clnt_stat *);

struct mapfs *add_mfs(struct mapfs *, int, struct mapfs **, struct mapfs **);
void free_mfs(struct mapfs *);
static void dump_mfs(struct mapfs *, char *, int);
static char *dump_distance(struct mapfs *);
static void cache_free(struct cache_entry *);
static int cache_check(char *, rpcvers_t *, char *);
static void cache_enter(char *, rpcvers_t, rpcvers_t, char *, int);
void destroy_auth_client_handle(CLIENT *cl);

#ifdef CACHE_DEBUG
static void trace_host_cache(void);
static void trace_portmap_cache(void);
#endif /* CACHE_DEBUG */

static int rpc_timeout = 20;

#ifdef CACHE_DEBUG
/*
 * host cache counters. These variables do not need to be protected
 * by mutex's. They have been added to measure the utility of the
 * goodhost/deadhost cache in the lazy hierarchical mounting scheme.
 */
static int host_cache_accesses = 0;
static int host_cache_lookups = 0;
static int deadhost_cache_hits = 0;
static int goodhost_cache_hits = 0;

/*
 * portmap cache counters. These variables do not need to be protected
 * by mutex's. They have been added to measure the utility of the portmap
 * cache in the lazy hierarchical mounting scheme.
 */
static int portmap_cache_accesses = 0;
static int portmap_cache_lookups = 0;
static int portmap_cache_hits = 0;
#endif /* CACHE_DEBUG */

/*
 * There are the defaults (range) for the client when determining
 * which NFS version to use when probing the server (see above).
 * These will only be used when the vers mount option is not used and
 * these may be reset if /etc/default/nfs is configured to do so.
 */
static rpcvers_t vers_max_default = NFS_VERSMAX_DEFAULT;
static rpcvers_t vers_min_default = NFS_VERSMIN_DEFAULT;

/*
 * list of support services needed
 */
static char	*service_list[] = { STATD, LOCKD, NULL };
static char	*service_list_v4[] = { STATD, LOCKD, NFS4CBD, NFSMAPID, NULL };

static void read_default_nfs(void);
static int is_v4_mount(char *);
static void start_nfs4cbd(void);

int
mount_nfs(struct mapent *me, char *mntpnt, char *prevhost, int overlay,
    uid_t uid, action_list **alpp)
{
	struct mapfs *mfs, *mp;
	int err = -1;
	action_list *alp;
	char *dir;


	alp = *alpp;

	read_default_nfs();

	mfs = enum_servers(me, prevhost);
	if (mfs == NULL)
		return (ENOENT);

	/*
	 * Try loopback if we have something on localhost; if nothing
	 * works, we will fall back to NFS
	 */
	if (is_nfs_port(me->map_mntopts)) {
		for (mp = mfs; mp; mp = mp->mfs_next) {
			if (self_check(mp->mfs_host)) {
				err = loopbackmount(mp->mfs_dir,
				    mntpnt, me->map_mntopts, overlay);
				if (err) {
					mp->mfs_ignore = 1;
				} else {
					/*
					 * Free action_list if there
					 * is one as it is not needed.
					 * Make sure to set alpp to null
					 * so caller doesn't try to free it
					 * again.
					 */
					if (*alpp) {
						free(*alpp);
						*alpp = NULL;
					}
					break;
				}
			}
		}
	}
	if (err) {
		dir = strdup(mfs->mfs_dir);
		err = nfsmount(mfs, mntpnt, me->map_mntopts,
		    overlay, uid, alp);
		if (err && trace > 1) {
			trace_prt(1, "  Couldn't mount %s:%s, err=%d\n",
			    mfs->mfs_host ? mfs->mfs_host : "",
			    mfs->mfs_dir ? mfs->mfs_dir : dir, err);
		}
		free(dir);
	}
	free_mfs(mfs);
	return (err);
}


/*
 * Using the new ioctl SIOCTONLINK to determine if a host is on the same
 * subnet. Remove the old network, subnet check.
 */

static struct mapfs *
get_mysubnet_servers(struct mapfs *mfs_in)
{
	int s;
	struct mapfs *mfs, *p, *mfs_head = NULL, *mfs_tail = NULL;

	struct netconfig *nconf;
	NCONF_HANDLE *nc = NULL;
	struct nd_hostserv hs;
	struct nd_addrlist *retaddrs;
	struct netbuf *nb;
	struct sioc_addrreq areq;
	int res;
	int af;
	int i;
	int sa_size;

	hs.h_serv = "rpcbind";

	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {
		nc = setnetconfig();

		while (nconf = getnetconfig(nc)) {

			/*
			 * Care about INET family only. proto_done flag
			 * indicates if we have already covered this
			 * protocol family. If so skip it
			 */
			if (((strcmp(nconf->nc_protofmly, NC_INET6) == 0) ||
			    (strcmp(nconf->nc_protofmly, NC_INET) == 0)) &&
			    (nconf->nc_semantics == NC_TPI_CLTS)) {
			} else
				continue;

			hs.h_host = mfs->mfs_host;

			if (netdir_getbyname(nconf, &hs, &retaddrs) != ND_OK)
				continue;

			/*
			 * For each host address see if it's on our
			 * local subnet.
			 */

			if (strcmp(nconf->nc_protofmly, NC_INET6) == 0)
				af = AF_INET6;
			else
				af = AF_INET;
			nb = retaddrs->n_addrs;
			for (i = 0; i < retaddrs->n_cnt; i++, nb++) {
				memset(&areq.sa_addr, 0, sizeof (areq.sa_addr));
				memcpy(&areq.sa_addr, nb->buf, MIN(nb->len,
				    sizeof (areq.sa_addr)));
				if (res = subnet_test(af, &areq)) {
					p = add_mfs(mfs, DIST_MYNET,
					    &mfs_head, &mfs_tail);
					if (!p) {
						netdir_free(retaddrs,
						    ND_ADDRLIST);
						endnetconfig(nc);
						return (NULL);
					}
					break;
				}
			}  /* end of every host */
			if (trace > 2) {
				trace_prt(1, "get_mysubnet_servers: host=%s "
				    "netid=%s res=%s\n", mfs->mfs_host,
				    nconf->nc_netid, res == 1?"SUC":"FAIL");
			}

			netdir_free(retaddrs, ND_ADDRLIST);
		} /* end of while */

		endnetconfig(nc);

	} /* end of every map */

	return (mfs_head);

}

int
subnet_test(int af, struct sioc_addrreq *areq)
{
	int s;

	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
		return (0);
	}

	areq->sa_res = -1;

	if (ioctl(s, SIOCTONLINK, (caddr_t)areq) < 0) {
		syslog(LOG_ERR, "subnet_test:SIOCTONLINK failed");
		return (0);
	}
	close(s);
	if (areq->sa_res == 1)
		return (1);
	else
		return (0);


}

/*
 * ping a bunch of hosts at once and sort by who responds first
 */
static struct mapfs *
sort_servers(struct mapfs *mfs_in, int timeout)
{
	struct mapfs *m1 = NULL;
	enum clnt_stat clnt_stat;

	if (!mfs_in)
		return (NULL);

	clnt_stat = nfs_cast(mfs_in, &m1, timeout);

	if (!m1) {
		char buff[2048] = {'\0'};

		for (m1 = mfs_in; m1; m1 = m1->mfs_next) {
			(void) strcat(buff, m1->mfs_host);
			if (m1->mfs_next)
				(void) strcat(buff, ",");
		}

		syslog(LOG_ERR, "servers %s not responding: %s",
		    buff, clnt_sperrno(clnt_stat));
	}

	return (m1);
}

/*
 * Add a mapfs entry to the list described by *mfs_head and *mfs_tail,
 * provided it is not marked "ignored" and isn't a dupe of ones we've
 * already seen.
 */
struct mapfs *
add_mfs(struct mapfs *mfs, int distance, struct mapfs **mfs_head,
    struct mapfs **mfs_tail)
{
	struct mapfs *tmp, *new;

	for (tmp = *mfs_head; tmp; tmp = tmp->mfs_next)
		if ((strcmp(tmp->mfs_host, mfs->mfs_host) == 0 &&
		    strcmp(tmp->mfs_dir, mfs->mfs_dir) == 0) ||
		    mfs->mfs_ignore)
			return (*mfs_head);
	new = (struct mapfs *)malloc(sizeof (struct mapfs));
	if (!new) {
		syslog(LOG_ERR, "Memory allocation failed: %m");
		return (NULL);
	}
	bcopy(mfs, new, sizeof (struct mapfs));
	new->mfs_next = NULL;
	if (distance)
		new->mfs_distance = distance;
	if (!*mfs_head)
		*mfs_tail = *mfs_head = new;
	else {
		(*mfs_tail)->mfs_next = new;
		*mfs_tail = new;
	}
	return (*mfs_head);
}

static void
dump_mfs(struct mapfs *mfs, char *message, int level)
{
	struct mapfs *m1;

	if (trace <= level)
		return;

	trace_prt(1, "%s", message);
	if (!mfs) {
		trace_prt(0, "mfs is null\n");
		return;
	}
	for (m1 = mfs; m1; m1 = m1->mfs_next)
		trace_prt(0, "%s[%s] ", m1->mfs_host, dump_distance(m1));
	trace_prt(0, "\n");
}

static char *
dump_distance(struct mapfs *mfs)
{
	switch (mfs->mfs_distance) {
	case 0:			return ("zero");
	case DIST_SELF:		return ("self");
	case DIST_MYSUB:	return ("mysub");
	case DIST_MYNET:	return ("mynet");
	case DIST_OTHER:	return ("other");
	default:		return ("other");
	}
}

/*
 * Walk linked list "raw", building a new list consisting of members
 * NOT found in list "filter", returning the result.
 */
static struct mapfs *
filter_mfs(struct mapfs *raw, struct mapfs *filter)
{
	struct mapfs *mfs, *p, *mfs_head = NULL, *mfs_tail = NULL;
	int skip;

	if (!raw)
		return (NULL);
	for (mfs = raw; mfs; mfs = mfs->mfs_next) {
		for (skip = 0, p = filter; p; p = p->mfs_next) {
			if (strcmp(p->mfs_host, mfs->mfs_host) == 0 &&
			    strcmp(p->mfs_dir, mfs->mfs_dir) == 0) {
				skip = 1;
				break;
			}
		}
		if (skip)
			continue;
		p = add_mfs(mfs, 0, &mfs_head, &mfs_tail);
		if (!p)
			return (NULL);
	}
	return (mfs_head);
}

/*
 * Walk a linked list of mapfs structs, freeing each member.
 */
void
free_mfs(struct mapfs *mfs)
{
	struct mapfs *tmp;

	while (mfs) {
		tmp = mfs->mfs_next;
		free(mfs);
		mfs = tmp;
	}
}

/*
 * New code for NFS client failover: we need to carry and sort
 * lists of server possibilities rather than return a single
 * entry.  It preserves previous behaviour of sorting first by
 * locality (loopback-or-preferred/subnet/net/other) and then
 * by ping times.  We'll short-circuit this process when we
 * have ENOUGH or more entries.
 */
static struct mapfs *
enum_servers(struct mapent *me, char *preferred)
{
	struct mapfs *p, *m1, *m2, *mfs_head = NULL, *mfs_tail = NULL;

	/*
	 * Short-circuit for simple cases.
	 */
	if (!me->map_fs->mfs_next) {
		p = add_mfs(me->map_fs, DIST_OTHER, &mfs_head, &mfs_tail);
		if (!p)
			return (NULL);
		return (mfs_head);
	}

	dump_mfs(me->map_fs, "	enum_servers: mapent: ", 2);

	/*
	 * get addresses & see if any are myself
	 * or were mounted from previously in a
	 * hierarchical mount.
	 */
	if (trace > 2)
		trace_prt(1, "	enum_servers: looking for pref/self\n");
	for (m1 = me->map_fs; m1; m1 = m1->mfs_next) {
		if (m1->mfs_ignore)
			continue;
		if (self_check(m1->mfs_host) ||
		    strcmp(m1->mfs_host, preferred) == 0) {
			p = add_mfs(m1, DIST_SELF, &mfs_head, &mfs_tail);
			if (!p)
				return (NULL);
		}
	}
	if (trace > 2 && m1)
		trace_prt(1, "	enum_servers: pref/self found, %s\n",
		    m1->mfs_host);

	/*
	 * look for entries on this subnet
	 */
	dump_mfs(m1, "	enum_servers: input of get_mysubnet_servers: ", 2);
	m1 = get_mysubnet_servers(me->map_fs);
	dump_mfs(m1, "	enum_servers: output of get_mysubnet_servers: ", 3);
	if (m1 && m1->mfs_next) {
		m2 = sort_servers(m1, rpc_timeout / 2);
		dump_mfs(m2, "	enum_servers: output of sort_servers: ", 3);
		free_mfs(m1);
		m1 = m2;
	}

	for (m2 = m1; m2; m2 = m2->mfs_next) {
		p = add_mfs(m2, 0, &mfs_head, &mfs_tail);
		if (!p)
			return (NULL);
	}
	if (m1)
		free_mfs(m1);

	/*
	 * add the rest of the entries at the end
	 */
	m1 = filter_mfs(me->map_fs, mfs_head);
	dump_mfs(m1, "	enum_servers: etc: output of filter_mfs: ", 3);
	m2 = sort_servers(m1, rpc_timeout / 2);
	dump_mfs(m2, "	enum_servers: etc: output of sort_servers: ", 3);
	if (m1)
		free_mfs(m1);
	m1 = m2;
	for (m2 = m1; m2; m2 = m2->mfs_next) {
		p = add_mfs(m2, DIST_OTHER, &mfs_head, &mfs_tail);
		if (!p)
			return (NULL);
	}
	if (m1)
		free_mfs(m1);

	dump_mfs(mfs_head, "  enum_servers: output: ", 1);
	return (mfs_head);
}

static enum nfsstat
nfsmount(
	struct mapfs *mfs_in,
	char *mntpnt, char *opts,
	int overlay,
	uid_t uid,
	action_list *alp)
{
	CLIENT *cl;
	char remname[MAXPATHLEN], *mnttabtext = NULL;
	char mopts[MAX_MNTOPT_STR];
	char netname[MAXNETNAMELEN+1];
	char	*mntopts = NULL;
	int mnttabcnt = 0;
	int loglevel;
	struct mnttab m;
	struct nfs_args *argp = NULL, *head = NULL, *tail = NULL,
	    *prevhead, *prevtail;
	int flags;
	struct fhstatus fhs;
	struct timeval timeout;
	enum clnt_stat rpc_stat;
	enum nfsstat status;
	struct stat stbuf;
	struct netconfig *nconf;
	rpcvers_t vers, versmin; /* used to negotiate nfs version in pingnfs */
				/* and mount version with mountd */
	rpcvers_t outvers;	/* final version to be used during mount() */
	rpcvers_t nfsvers;	/* version in map options, 0 if not there */
	rpcvers_t mountversmax;	/* tracks the max mountvers during retries */

	/* used to negotiate nfs version using webnfs */
	rpcvers_t pubvers, pubversmin, pubversmax;
	int posix;
	struct nd_addrlist *retaddrs;
	struct mountres3 res3;
	nfs_fh3 fh3;
	char *fstype;
	int count, i;
	char scerror_msg[MAXMSGLEN];
	int *auths;
	int delay;
	int retries;
	char *nfs_proto = NULL;
	uint_t nfs_port = 0;
	char *p, *host, *rhost, *dir;
	struct mapfs *mfs = NULL;
	int error, last_error = 0;
	int replicated;
	int entries = 0;
	int v2cnt = 0, v3cnt = 0, v4cnt = 0;
	int v2near = 0, v3near = 0, v4near = 0;
	int skipentry = 0;
	char *nfs_flavor;
	seconfig_t nfs_sec;
	int sec_opt, scerror;
	struct sec_data *secdata;
	int secflags;
	struct netbuf *syncaddr;
	bool_t	use_pubfh;
	ushort_t thisport;
	int got_val;
	mfs_snego_t mfssnego_init, mfssnego;

	dump_mfs(mfs_in, "  nfsmount: input: ", 2);
	replicated = (mfs_in->mfs_next != NULL);
	m.mnt_mntopts = opts;
	if (replicated && hasmntopt(&m, MNTOPT_SOFT)) {
		if (verbose)
			syslog(LOG_WARNING,
		    "mount on %s is soft and will not be replicated.", mntpnt);
		replicated = 0;
	}
	if (replicated && !hasmntopt(&m, MNTOPT_RO)) {
		if (verbose)
			syslog(LOG_WARNING,
		    "mount on %s is not read-only and will not be replicated.",
			    mntpnt);
		replicated = 0;
	}
	if (replicated)
		loglevel = LOG_WARNING;
	else
		loglevel = LOG_ERR;

	if (trace > 1) {
		if (replicated)
			trace_prt(1, "	nfsmount: replicated mount on %s %s:\n",
			    mntpnt, opts);
		else
			trace_prt(1, "	nfsmount: standard mount on %s %s:\n",
			    mntpnt, opts);
		for (mfs = mfs_in; mfs; mfs = mfs->mfs_next)
			trace_prt(1, "	  %s:%s\n",
			    mfs->mfs_host, mfs->mfs_dir);
	}

	/*
	 * Make sure mountpoint is safe to mount on
	 */
	if (lstat(mntpnt, &stbuf) < 0) {
		syslog(LOG_ERR, "Couldn't stat %s: %m", mntpnt);
		return (NFSERR_NOENT);
	}

	/*
	 * Get protocol specified in options list, if any.
	 */
	if ((str_opt(&m, "proto", &nfs_proto)) == -1) {
		return (NFSERR_NOENT);
	}

	/*
	 * Get port specified in options list, if any.
	 */
	got_val = nopt(&m, MNTOPT_PORT, (int *)&nfs_port);
	if (!got_val)
		nfs_port = 0;	/* "unspecified" */
	if (nfs_port > USHRT_MAX) {
		syslog(LOG_ERR, "%s: invalid port number %d", mntpnt, nfs_port);
		return (NFSERR_NOENT);
	}

	/*
	 * Set mount(2) flags here, outside of the loop.
	 */
	flags = MS_OPTIONSTR;
	flags |= (hasmntopt(&m, MNTOPT_RO) == NULL) ? 0 : MS_RDONLY;
	flags |= (hasmntopt(&m, MNTOPT_NOSUID) == NULL) ? 0 : MS_NOSUID;
	flags |= overlay ? MS_OVERLAY : 0;
	if (mntpnt[strlen(mntpnt) - 1] != ' ')
		/* direct mount point without offsets */
		flags |= MS_OVERLAY;

	use_pubfh = (hasmntopt(&m, MNTOPT_PUBLIC) == NULL) ? FALSE : TRUE;

	(void) memset(&mfssnego_init, 0, sizeof (mfs_snego_t));
	if (hasmntopt(&m, MNTOPT_SECURE) != NULL) {
		if (++mfssnego_init.sec_opt > 1) {
			syslog(loglevel,
			    "conflicting security options");
			return (NFSERR_IO);
		}
		if (nfs_getseconfig_byname("dh", &mfssnego_init.nfs_sec)) {
			syslog(loglevel,
			    "error getting dh information from %s",
			    NFSSEC_CONF);
			return (NFSERR_IO);
		}
	}

	if (hasmntopt(&m, MNTOPT_SEC) != NULL) {
		if ((str_opt(&m, MNTOPT_SEC,
		    &mfssnego_init.nfs_flavor)) == -1) {
			syslog(LOG_ERR, "nfsmount: no memory");
			return (NFSERR_IO);
		}
	}

	if (mfssnego_init.nfs_flavor) {
		if (++mfssnego_init.sec_opt > 1) {
			syslog(loglevel,
			    "conflicting security options");
			free(mfssnego_init.nfs_flavor);
			return (NFSERR_IO);
		}
		if (nfs_getseconfig_byname(mfssnego_init.nfs_flavor,
		    &mfssnego_init.nfs_sec)) {
			syslog(loglevel,
			    "error getting %s information from %s",
			    mfssnego_init.nfs_flavor, NFSSEC_CONF);
			free(mfssnego_init.nfs_flavor);
			return (NFSERR_IO);
		}
		free(mfssnego_init.nfs_flavor);
	}

nextentry:
	skipentry = 0;

	got_val = nopt(&m, MNTOPT_VERS, (int *)&nfsvers);
	if (!got_val)
		nfsvers = 0;	/* "unspecified" */
	if (set_versrange(nfsvers, &vers, &versmin) != 0) {
		syslog(LOG_ERR, "Incorrect NFS version specified for %s",
		    mntpnt);
		last_error = NFSERR_NOENT;
		goto ret;
	}

	if (nfsvers != 0) {
		pubversmax = pubversmin = nfsvers;
	} else {
		pubversmax = vers;
		pubversmin = versmin;
	}

	/*
	 * Walk the whole list, pinging and collecting version
	 * info so that we can make sure the mount will be
	 * homogeneous with respect to version.
	 *
	 * If we have a version preference, this is easy; we'll
	 * just reject anything that doesn't match.
	 *
	 * If not, we want to try to provide the best compromise
	 * that considers proximity, preference for a higher version,
	 * sorted order, and number of replicas.  We will count
	 * the number of V2 and V3 replicas and also the number
	 * which are "near", i.e. the localhost or on the same
	 * subnet.
	 */
	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {


		if (mfs->mfs_ignore)
			continue;

		/*
		 * If the host is '[a:d:d:r:e:s:s'],
		 * only use 'a:d:d:r:e:s:s' for communication
		 */
		host = strdup(mfs->mfs_host);
		if (host == NULL) {
			syslog(LOG_ERR, "nfsmount: no memory");
			last_error = NFSERR_IO;
			goto out;
		}
		unbracket(&host);

		(void) memcpy(&mfssnego, &mfssnego_init, sizeof (mfs_snego_t));

		if (use_pubfh == TRUE || mfs->mfs_flags & MFS_URL) {
			char *path;

			if (nfs_port != 0 && mfs->mfs_port != 0 &&
			    nfs_port != mfs->mfs_port) {

				syslog(LOG_ERR, "nfsmount: port (%u) in nfs URL"
				    " not the same as port (%d) in port "
				    "option\n", mfs->mfs_port, nfs_port);
				last_error = NFSERR_IO;
				goto out;

			} else if (nfs_port != 0)
				thisport = nfs_port;
			else
				thisport = mfs->mfs_port;

			dir = mfs->mfs_dir;

			if ((mfs->mfs_flags & MFS_URL) == 0) {
				path = malloc(strlen(dir) + 2);
				if (path == NULL) {
					syslog(LOG_ERR, "nfsmount: no memory");
					last_error = NFSERR_IO;
					goto out;
				}
				path[0] = (char)WNL_NATIVEPATH;
				(void) strcpy(&path[1], dir);
			} else {
				path = dir;
			}

			argp = (struct nfs_args *)
			    malloc(sizeof (struct nfs_args));

			if (!argp) {
				if (path != dir)
					free(path);
				syslog(LOG_ERR, "nfsmount: no memory");
				last_error = NFSERR_IO;
				goto out;
			}
			(void) memset(argp, 0, sizeof (*argp));

			/*
			 * RDMA support
			 * By now Mount argument struct has been allocated,
			 * either a pub_fh path will be taken or the regular
			 * one. So here if a protocol was specified and it
			 * was not rdma we let it be, else we set DO_RDMA.
			 * If no proto was there we advise on trying RDMA.
			 */
			if (nfs_proto) {
				if (strcmp(nfs_proto, "rdma") == 0) {
					free(nfs_proto);
					nfs_proto = NULL;
					argp->flags |= NFSMNT_DORDMA;
				}
			} else
				argp->flags |= NFSMNT_TRYRDMA;

			for (pubvers = pubversmax; pubvers >= pubversmin;
			    pubvers--) {

				nconf = NULL;
				argp->addr = get_pubfh(host, pubvers, &mfssnego,
				    &nconf, nfs_proto, thisport, NULL,
				    &argp->fh, TRUE, path);

				if (argp->addr != NULL)
					break;

				if (nconf != NULL)
					freenetconfigent(nconf);
			}

			if (path != dir)
				free(path);

			if (argp->addr != NULL) {

				/*
				 * The use of llock option for NFSv4
				 * mounts is not required since file
				 * locking is included within the protocol
				 */
				if (pubvers != NFS_V4)
					argp->flags |= NFSMNT_LLOCK;

				argp->flags |= NFSMNT_PUBLIC;

				vers = pubvers;
				mfs->mfs_args = argp;
				mfs->mfs_version = pubvers;
				mfs->mfs_nconf = nconf;
				mfs->mfs_flags |= MFS_FH_VIA_WEBNFS;

			} else {
				free(argp);

				/*
				 * If -public was specified, give up
				 * on this entry now.
				 */
				if (use_pubfh == TRUE) {
					syslog(loglevel,
					    "%s: no public file handle support",
					    host);
					last_error = NFSERR_NOENT;
					mfs->mfs_ignore = 1;
					continue;
				}

				/*
				 * Back off to a conventional mount.
				 *
				 * URL's can contain escape characters. Get
				 * rid of them.
				 */
				path = malloc(strlen(dir) + 2);

				if (path == NULL) {
					syslog(LOG_ERR, "nfsmount: no memory");
					last_error = NFSERR_IO;
					goto out;
				}

				strcpy(path, dir);
				URLparse(path);
				mfs->mfs_dir = path;
				mfs->mfs_flags |= MFS_ALLOC_DIR;
				mfs->mfs_flags &= ~MFS_URL;
			}
		}

		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) ==  0) {
			i = pingnfs(host, get_retry(opts) + 1, &vers, versmin,
			    0, FALSE, NULL, nfs_proto);
			if (i != RPC_SUCCESS) {
				if (i == RPC_PROGVERSMISMATCH) {
					syslog(loglevel, "server %s: NFS "
					    "protocol version mismatch",
					    host);
				} else {
					syslog(loglevel, "server %s not "
					    "responding", host);
				}
				mfs->mfs_ignore = 1;
				last_error = NFSERR_NOENT;
				continue;
			}
			if (nfsvers != 0 && nfsvers != vers) {
				if (nfs_proto == NULL)
					syslog(loglevel,
					    "NFS version %d "
					    "not supported by %s",
					    nfsvers, host);
				else
					syslog(loglevel,
					    "NFS version %d "
					    "with proto %s "
					    "not supported by %s",
					    nfsvers, nfs_proto, host);
				mfs->mfs_ignore = 1;
				last_error = NFSERR_NOENT;
				continue;
			}
		}

		free(host);

		switch (vers) {
		case NFS_V4: v4cnt++; break;
		case NFS_V3: v3cnt++; break;
		case NFS_VERSION: v2cnt++; break;
		default: break;
		}

		/*
		 * It's not clear how useful this stuff is if
		 * we are using webnfs across the internet, but it
		 * can't hurt.
		 */
		if (mfs->mfs_distance &&
		    mfs->mfs_distance <= DIST_MYSUB) {
			switch (vers) {
			case NFS_V4: v4near++; break;
			case NFS_V3: v3near++; break;
			case NFS_VERSION: v2near++; break;
			default: break;
			}
		}

		/*
		 * If the mount is not replicated, we don't want to
		 * ping every entry, so we'll stop here.  This means
		 * that we may have to go back to "nextentry" above
		 * to consider another entry if we can't get
		 * all the way to mount(2) with this one.
		 */
		if (!replicated)
			break;

	}

	if (nfsvers == 0) {
		/*
		 * Choose the NFS version.
		 * We prefer higher versions, but will choose a one-
		 * version downgrade in service if we can use a local
		 * network interface and avoid a router.
		 */
		if (v4cnt && v4cnt >= v3cnt && (v4near || !v3near))
			nfsvers = NFS_V4;
		else if (v3cnt && v3cnt >= v2cnt && (v3near || !v2near))
			nfsvers = NFS_V3;
		else
			nfsvers = NFS_VERSION;
		if (trace > 2)
			trace_prt(1,
		    "  nfsmount: v4=%d[%d]v3=%d[%d],v2=%d[%d] => v%d.\n",
			    v4cnt, v4near, v3cnt, v3near,
			    v2cnt, v2near, nfsvers);
	}

	/*
	 * Since we don't support different NFS versions in replicated
	 * mounts, set fstype now.
	 * Also take the opportunity to set
	 * the mount protocol version as appropriate.
	 */
	switch (nfsvers) {
	case NFS_V4:
		fstype = MNTTYPE_NFS4;
		break;
	case NFS_V3:
		fstype = MNTTYPE_NFS3;
		if (use_pubfh == FALSE) {
			mountversmax = MOUNTVERS3;
			versmin = MOUNTVERS3;
		}
		break;
	case NFS_VERSION:
		fstype = MNTTYPE_NFS;
		if (use_pubfh == FALSE) {
			mountversmax = MOUNTVERS_POSIX;
			versmin = MOUNTVERS;
		}
		break;
	}

	/*
	 * Our goal here is to evaluate each of several possible
	 * replicas and try to come up with a list we can hand
	 * to mount(2).  If we don't have a valid "head" at the
	 * end of this process, it means we have rejected all
	 * potential server:/path tuples.  We will fail quietly
	 * in front of mount(2), and will have printed errors
	 * where we found them.
	 * XXX - do option work outside loop w careful design
	 * XXX - use macro for error condition free handling
	 */
	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {

		/*
		 * Initialize retry and delay values on a per-server basis.
		 */
		retries = get_retry(opts);
		delay = INITDELAY;
retry:
		if (mfs->mfs_ignore)
			continue;

		/*
		 * If we don't have a fh yet, and if this is not a replicated
		 * mount, we haven't done a pingnfs() on the next entry,
		 * so we don't know if the next entry is up or if it
		 * supports an NFS version we like.  So if we had a problem
		 * with an entry, we need to go back and run through some new
		 * code.
		 */
		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
		    !replicated && skipentry)
			goto nextentry;

		vers = mountversmax;
		host = mfs->mfs_host;
		dir = mfs->mfs_dir;

		/*
		 * Remember the possible '[a:d:d:r:e:s:s]' as the address to be
		 * later passed to mount(2) and used in the mnttab line, but
		 * only use 'a:d:d:r:e:s:s' for communication
		 */
		rhost = strdup(host);
		if (rhost == NULL) {
			syslog(LOG_ERR, "nfsmount: no memory");
			last_error = NFSERR_IO;
			goto out;
		}
		unbracket(&host);

		(void) sprintf(remname, "%s:%s", rhost, dir);
		if (trace > 4 && replicated)
			trace_prt(1, "	nfsmount: examining %s\n", remname);

		if (mfs->mfs_args == NULL) {

			/*
			 * Allocate nfs_args structure
			 */
			argp = (struct nfs_args *)
			    malloc(sizeof (struct nfs_args));

			if (!argp) {
				syslog(LOG_ERR, "nfsmount: no memory");
				last_error = NFSERR_IO;
				goto out;
			}

			(void) memset(argp, 0, sizeof (*argp));

			/*
			 * RDMA support
			 * By now Mount argument struct has been allocated,
			 * either a pub_fh path will be taken or the regular
			 * one. So here if a protocol was specified and it
			 * was not rdma we let it be, else we set DO_RDMA.
			 * If no proto was there we advise on trying RDMA.
			 */
			if (nfs_proto) {
				if (strcmp(nfs_proto, "rdma") == 0) {
					free(nfs_proto);
					nfs_proto = NULL;
					argp->flags |= NFSMNT_DORDMA;
				}
			} else
				argp->flags |= NFSMNT_TRYRDMA;
		} else {
			argp = mfs->mfs_args;
			mfs->mfs_args = NULL;

			/*
			 * Skip entry if we already have file handle but the
			 * NFS version is wrong.
			 */
			if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) &&
			    mfs->mfs_version != nfsvers) {

				free(argp);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
		}

		prevhead = head;
		prevtail = tail;
		if (!head)
			head = tail = argp;
		else
			tail = tail->nfs_ext_u.nfs_extB.next = argp;

		/*
		 * WebNFS and NFSv4 behave similarly in that they
		 * don't use the mount protocol.  Therefore, avoid
		 * mount protocol like things when version 4 is being
		 * used.
		 */
		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
		    nfsvers != NFS_V4) {
			timeout.tv_usec = 0;
			timeout.tv_sec = rpc_timeout;
			rpc_stat = RPC_TIMEDOUT;

			/* Create the client handle. */

			if (trace > 1) {
				trace_prt(1,
				    "  nfsmount: Get mount version: request "
				    "vers=%d min=%d\n", vers, versmin);
			}

			while ((cl = clnt_create_vers(host, MOUNTPROG, &outvers,
			    versmin, vers, "udp")) == NULL) {
				if (trace > 4) {
					trace_prt(1,
					    "  nfsmount: Can't get mount "
					    "version: rpcerr=%d\n",
					    rpc_createerr.cf_stat);
				}
				if (rpc_createerr.cf_stat == RPC_UNKNOWNHOST ||
				    rpc_createerr.cf_stat == RPC_TIMEDOUT)
					break;

			/*
			 * backoff and return lower version to retry the ping.
			 * XXX we should be more careful and handle
			 * RPC_PROGVERSMISMATCH here, because that error
			 * is handled in clnt_create_vers(). It's not done to
			 * stay in sync with the nfs mount command.
			 */
				vers--;
				if (vers < versmin)
					break;
				if (trace > 4) {
					trace_prt(1,
					    "  nfsmount: Try version=%d\n",
					    vers);
				}
			}

			if (cl == NULL) {
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOENT;

				if (rpc_createerr.cf_stat != RPC_UNKNOWNHOST &&
				    rpc_createerr.cf_stat !=
				    RPC_PROGVERSMISMATCH &&
				    retries-- > 0) {
					DELAY(delay);
					goto retry;
				}

				syslog(loglevel, "%s %s", host,
				    clnt_spcreateerror(
				    "server not responding"));
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			if (trace > 1) {
				trace_prt(1,
				    "	nfsmount: mount version=%d\n", outvers);
			}
#ifdef MALLOC_DEBUG
			add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
			add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
			    __FILE__, __LINE__);
#endif

			if (__clnt_bindresvport(cl) < 0) {
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOENT;

				if (retries-- > 0) {
					destroy_auth_client_handle(cl);
					DELAY(delay);
					goto retry;
				}

				syslog(loglevel, "mount %s: %s", host,
				    "Couldn't bind to reserved port");
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}

#ifdef MALLOC_DEBUG
			drop_alloc("AUTH_HANDLE", cl->cl_auth,
			    __FILE__, __LINE__);
#endif
			AUTH_DESTROY(cl->cl_auth);
			if ((cl->cl_auth = authsys_create_default()) == NULL) {
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOENT;

				if (retries-- > 0) {
					destroy_auth_client_handle(cl);
					DELAY(delay);
					goto retry;
				}

				syslog(loglevel, "mount %s: %s", host,
				    "Failed creating default auth handle");
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
#ifdef MALLOC_DEBUG
			add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
			    __FILE__, __LINE__);
#endif
		} else
			cl = NULL;

		/*
		 * set security options
		 */
		sec_opt = 0;
		(void) memset(&nfs_sec, 0, sizeof (nfs_sec));
		if (hasmntopt(&m, MNTOPT_SECURE) != NULL) {
			if (++sec_opt > 1) {
				syslog(loglevel,
				    "conflicting security options for %s",
				    remname);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_IO;
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			if (nfs_getseconfig_byname("dh", &nfs_sec)) {
				syslog(loglevel,
				    "error getting dh information from %s",
				    NFSSEC_CONF);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_IO;
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
		}

		nfs_flavor = NULL;
		if (hasmntopt(&m, MNTOPT_SEC) != NULL) {
			if ((str_opt(&m, MNTOPT_SEC, &nfs_flavor)) == -1) {
				syslog(LOG_ERR, "nfsmount: no memory");
				last_error = NFSERR_IO;
				destroy_auth_client_handle(cl);
				goto out;
			}
		}

		if (nfs_flavor) {
			if (++sec_opt > 1) {
				syslog(loglevel,
				    "conflicting security options for %s",
				    remname);
				free(nfs_flavor);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_IO;
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			if (nfs_getseconfig_byname(nfs_flavor, &nfs_sec)) {
				syslog(loglevel,
				    "error getting %s information from %s",
				    nfs_flavor, NFSSEC_CONF);
				free(nfs_flavor);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_IO;
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			free(nfs_flavor);
		}

		posix = (nfsvers != NFS_V4 &&
		    hasmntopt(&m, MNTOPT_POSIX) != NULL) ? 1 : 0;

		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
		    nfsvers != NFS_V4) {
			bool_t give_up_on_mnt;
			bool_t got_mnt_error;
		/*
		 * If we started with a URL, if first byte of path is not "/",
		 * then the mount will likely fail, so we should try again
		 * with a prepended "/".
		 */
			if (mfs->mfs_flags & MFS_ALLOC_DIR && *dir != '/')
				give_up_on_mnt = FALSE;
			else
				give_up_on_mnt = TRUE;

			got_mnt_error = FALSE;

try_mnt_slash:
			if (got_mnt_error == TRUE) {
				int i, l;

				give_up_on_mnt = TRUE;
				l = strlen(dir);

				/*
				 * Insert a "/" to front of mfs_dir.
				 */
				for (i = l; i > 0; i--)
					dir[i] = dir[i-1];

				dir[0] = '/';
			}

			/* Get fhandle of remote path from server's mountd */

			switch (outvers) {
			case MOUNTVERS:
				if (posix) {
					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					last_error = NFSERR_NOENT;
					syslog(loglevel,
					    "can't get posix info for %s",
					    host);
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}
		    /* FALLTHRU */
			case MOUNTVERS_POSIX:
				if (nfsvers == NFS_V3) {
					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					last_error = NFSERR_NOENT;
					syslog(loglevel,
					    "%s doesn't support NFS Version 3",
					    host);
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}
				rpc_stat = clnt_call(cl, MOUNTPROC_MNT,
				    xdr_dirpath, (caddr_t)&dir,
				    xdr_fhstatus, (caddr_t)&fhs, timeout);
				if (rpc_stat != RPC_SUCCESS) {

					if (give_up_on_mnt == FALSE) {
						got_mnt_error = TRUE;
						goto try_mnt_slash;
					}

				/*
				 * Given the way "clnt_sperror" works, the "%s"
				 * immediately following the "not responding"
				 * is correct.
				 */
					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					last_error = NFSERR_NOENT;

					if (retries-- > 0) {
						destroy_auth_client_handle(cl);
						DELAY(delay);
						goto retry;
					}

					if (trace > 3) {
						trace_prt(1,
						    "  nfsmount: mount RPC "
						    "failed for %s\n",
						    host);
					}
					syslog(loglevel,
					    "%s server not responding%s",
					    host, clnt_sperror(cl, ""));
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}
				if ((errno = fhs.fhs_status) != MNT_OK)  {

					if (give_up_on_mnt == FALSE) {
						got_mnt_error = TRUE;
						goto try_mnt_slash;
					}

					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					if (errno == EACCES) {
						status = NFSERR_ACCES;
					} else {
						syslog(loglevel, "%s: %m",
						    host);
						status = NFSERR_IO;
					}
					if (trace > 3) {
						trace_prt(1,
						    "  nfsmount: mount RPC gave"
						    " %d for %s:%s\n",
						    errno, host, dir);
					}
					last_error = status;
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}
				argp->fh = malloc((sizeof (fhandle)));
				if (!argp->fh) {
					syslog(LOG_ERR, "nfsmount: no memory");
					last_error = NFSERR_IO;
					destroy_auth_client_handle(cl);
					goto out;
				}
				(void) memcpy(argp->fh,
				    &fhs.fhstatus_u.fhs_fhandle,
				    sizeof (fhandle));
				break;
			case MOUNTVERS3:
				posix = 0;
				(void) memset((char *)&res3, '\0',
				    sizeof (res3));
				rpc_stat = clnt_call(cl, MOUNTPROC_MNT,
				    xdr_dirpath, (caddr_t)&dir,
				    xdr_mountres3, (caddr_t)&res3, timeout);
				if (rpc_stat != RPC_SUCCESS) {

					if (give_up_on_mnt == FALSE) {
						got_mnt_error = TRUE;
						goto try_mnt_slash;
					}

				/*
				 * Given the way "clnt_sperror" works, the "%s"
				 * immediately following the "not responding"
				 * is correct.
				 */
					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					last_error = NFSERR_NOENT;

					if (retries-- > 0) {
						destroy_auth_client_handle(cl);
						DELAY(delay);
						goto retry;
					}

					if (trace > 3) {
						trace_prt(1,
						    "  nfsmount: mount RPC "
						    "failed for %s\n",
						    host);
					}
					syslog(loglevel,
					    "%s server not responding%s",
					    remname, clnt_sperror(cl, ""));
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}
				if ((errno = res3.fhs_status) != MNT_OK)  {

					if (give_up_on_mnt == FALSE) {
						got_mnt_error = TRUE;
						goto try_mnt_slash;
					}

					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					if (errno == EACCES) {
						status = NFSERR_ACCES;
					} else {
						syslog(loglevel, "%s: %m",
						    remname);
						status = NFSERR_IO;
					}
					if (trace > 3) {
						trace_prt(1,
						    "  nfsmount: mount RPC gave"
						    " %d for %s:%s\n",
						    errno, host, dir);
					}
					last_error = status;
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}

			/*
			 *  Negotiate the security flavor for nfs_mount
			 */
				auths = res3.mountres3_u.mountinfo.
				    auth_flavors.auth_flavors_val;
				count = res3.mountres3_u.mountinfo.
				    auth_flavors.auth_flavors_len;

				if (sec_opt) {
					for (i = 0; i < count; i++)
						if (auths[i] ==
						    nfs_sec.sc_nfsnum) {
							break;
						}
					if (i >= count) {
						syslog(LOG_ERR,
						    "%s: does not support "
						    "security \"%s\"\n",
						    remname, nfs_sec.sc_name);
						clnt_freeres(cl, xdr_mountres3,
						    (caddr_t)&res3);
						free(argp);
						head = prevhead;
						tail = prevtail;
						if (tail)
							tail->nfs_ext_u.
							    nfs_extB.next =
							    NULL;
						last_error = NFSERR_IO;
						destroy_auth_client_handle(cl);
						skipentry = 1;
						mfs->mfs_ignore = 1;
						continue;
					}
				} else if (count > 0) {
					for (i = 0; i < count; i++) {
						if (!(scerror =
						    nfs_getseconfig_bynumber(
						    auths[i], &nfs_sec))) {
							sec_opt++;
							break;
						}
					}
					if (i >= count) {
						if (nfs_syslog_scerr(scerror,
						    scerror_msg)
						    != -1) {
							syslog(LOG_ERR,
							    "%s cannot be "
							    "mounted because it"
							    " is shared with "
							    "security flavor %d"
							    " which %s",
							    remname,
							    auths[i-1],
							    scerror_msg);
						}
						clnt_freeres(cl, xdr_mountres3,
						    (caddr_t)&res3);
						free(argp);
						head = prevhead;
						tail = prevtail;
						if (tail)
							tail->nfs_ext_u.
							    nfs_extB.next =
							    NULL;
						last_error = NFSERR_IO;
						destroy_auth_client_handle(cl);
						skipentry = 1;
						mfs->mfs_ignore = 1;
						continue;
						}
				}

				fh3.fh3_length =
				    res3.mountres3_u.mountinfo.fhandle.
				    fhandle3_len;
				(void) memcpy(fh3.fh3_u.data,
				    res3.mountres3_u.mountinfo.fhandle.
				    fhandle3_val,
				    fh3.fh3_length);
				clnt_freeres(cl, xdr_mountres3,
				    (caddr_t)&res3);
				argp->fh = malloc(sizeof (nfs_fh3));
				if (!argp->fh) {
					syslog(LOG_ERR, "nfsmount: no memory");
					last_error = NFSERR_IO;
					destroy_auth_client_handle(cl);
					goto out;
				}
				(void) memcpy(argp->fh, &fh3, sizeof (nfs_fh3));
				break;
			default:
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOENT;
				syslog(loglevel,
				    "unknown MOUNT version %ld on %s",
				    vers, remname);
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			} /* switch */
		}
		if (nfsvers == NFS_V4) {
			argp->fh = strdup(dir);
			if (argp->fh == NULL) {
				syslog(LOG_ERR, "nfsmount: no memory");
				last_error = NFSERR_IO;
				goto out;
			}
		}

		if (trace > 4)
			trace_prt(1, "	nfsmount: have %s filehandle for %s\n",
			    fstype, remname);

		argp->flags |= NFSMNT_NEWARGS;
		argp->flags |= NFSMNT_INT;	/* default is "intr" */
		argp->flags |= NFSMNT_HOSTNAME;
		argp->hostname = strdup(host);
		if (argp->hostname == NULL) {
			syslog(LOG_ERR, "nfsmount: no memory");
			last_error = NFSERR_IO;
			goto out;
		}

		/*
		 * In this case, we want NFSv4 to behave like
		 * non-WebNFS so that we get the server address.
		 */
		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0) {
			nconf = NULL;

			if (nfs_port != 0)
				thisport = nfs_port;
			else
				thisport = mfs->mfs_port;

			/*
			 * For NFSv4, we want to avoid rpcbind, so call
			 * get_server_netinfo() directly to tell it that
			 * we want to go "direct_to_server".  Otherwise,
			 * do what has always been done.
			 */
			if (nfsvers == NFS_V4) {
				enum clnt_stat cstat;

				argp->addr = get_server_netinfo(SERVER_ADDR,
				    host, NFS_PROGRAM, nfsvers, NULL,
				    &nconf, nfs_proto, thisport, NULL,
				    NULL, TRUE, NULL, &cstat);
			} else {
				argp->addr = get_addr(host, NFS_PROGRAM,
				    nfsvers, &nconf, nfs_proto,
				    thisport, NULL);
			}

			if (argp->addr == NULL) {
				if (argp->hostname)
					free(argp->hostname);
				free(argp->fh);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOENT;

				if (retries-- > 0) {
					destroy_auth_client_handle(cl);
					DELAY(delay);
					goto retry;
				}

				syslog(loglevel, "%s: no NFS service", host);
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			if (trace > 4)
				trace_prt(1,
				    "\tnfsmount: have net address for %s\n",
				    remname);

		} else {
			nconf = mfs->mfs_nconf;
			mfs->mfs_nconf = NULL;
		}

		argp->flags |= NFSMNT_KNCONF;
		argp->knconf = get_knconf(nconf);
		if (argp->knconf == NULL) {
			netbuf_free(argp->addr);
			freenetconfigent(nconf);
			if (argp->hostname)
				free(argp->hostname);
			free(argp->fh);
			free(argp);
			head = prevhead;
			tail = prevtail;
			if (tail)
				tail->nfs_ext_u.nfs_extB.next = NULL;
			last_error = NFSERR_NOSPC;
			destroy_auth_client_handle(cl);
			skipentry = 1;
			mfs->mfs_ignore = 1;
			continue;
		}
		if (trace > 4)
			trace_prt(1,
			    "\tnfsmount: have net config for %s\n",
			    remname);

		if (hasmntopt(&m, MNTOPT_SOFT) != NULL) {
			argp->flags |= NFSMNT_SOFT;
		}
		if (hasmntopt(&m, MNTOPT_NOINTR) != NULL) {
			argp->flags &= ~(NFSMNT_INT);
		}
		if (hasmntopt(&m, MNTOPT_NOAC) != NULL) {
			argp->flags |= NFSMNT_NOAC;
		}
		if (hasmntopt(&m, MNTOPT_NOCTO) != NULL) {
			argp->flags |= NFSMNT_NOCTO;
		}
		if (hasmntopt(&m, MNTOPT_FORCEDIRECTIO) != NULL) {
			argp->flags |= NFSMNT_DIRECTIO;
		}
		if (hasmntopt(&m, MNTOPT_NOFORCEDIRECTIO) != NULL) {
			argp->flags &= ~(NFSMNT_DIRECTIO);
		}

		/*
		 * Set up security data for argp->nfs_ext_u.nfs_extB.secdata.
		 */
		if (mfssnego.snego_done) {
			memcpy(&nfs_sec, &mfssnego.nfs_sec,
			    sizeof (seconfig_t));
		} else if (!sec_opt) {
			/*
			 * Get default security mode.
			 */
			if (nfs_getseconfig_default(&nfs_sec)) {
				syslog(loglevel,
				    "error getting default security entry\n");
				free_knconf(argp->knconf);
				netbuf_free(argp->addr);
				freenetconfigent(nconf);
				if (argp->hostname)
					free(argp->hostname);
				free(argp->fh);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_NOSPC;
				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			argp->flags |= NFSMNT_SECDEFAULT;
		}

		/*
		 * For AUTH_DH
		 * get the network address for the time service on
		 * the server.	If an RPC based time service is
		 * not available then try the IP time service.
		 *
		 * Eventurally, we want to move this code to nfs_clnt_secdata()
		 * when autod_nfs.c and mount.c can share the same
		 * get_the_addr/get_netconfig_info routine.
		 */
		secflags = 0;
		syncaddr = NULL;
		retaddrs = NULL;

		if (nfs_sec.sc_rpcnum == AUTH_DH || nfsvers == NFS_V4) {
		/*
		 * If not using the public fh and not NFS_V4, we can try
		 * talking RPCBIND. Otherwise, assume that firewalls
		 * prevent us from doing that.
		 */
			if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
			    nfsvers != NFS_V4) {
				enum clnt_stat cstat;
				syncaddr = get_server_netinfo(SERVER_ADDR,
				    host, RPCBPROG, RPCBVERS, NULL, &nconf,
				    NULL, 0, NULL, NULL, FALSE, NULL, &cstat);
			}

			if (syncaddr != NULL) {
				/* for flags in sec_data */
				secflags |= AUTH_F_RPCTIMESYNC;
			} else {
				struct nd_hostserv hs;
				int error;

				hs.h_host = host;
				hs.h_serv = "timserver";
				error = netdir_getbyname(nconf, &hs, &retaddrs);

				if (error != ND_OK &&
				    nfs_sec.sc_rpcnum == AUTH_DH) {
					syslog(loglevel,
					    "%s: secure: no time service\n",
					    host);
					free_knconf(argp->knconf);
					netbuf_free(argp->addr);
					freenetconfigent(nconf);
					if (argp->hostname)
						free(argp->hostname);
					free(argp->fh);
					free(argp);
					head = prevhead;
					tail = prevtail;
					if (tail)
						tail->nfs_ext_u.nfs_extB.next =
						    NULL;
					last_error = NFSERR_IO;
					destroy_auth_client_handle(cl);
					skipentry = 1;
					mfs->mfs_ignore = 1;
					continue;
				}

				if (error == ND_OK)
					syncaddr = retaddrs->n_addrs;

			/*
			 * For potential usage by NFS V4 when AUTH_DH
			 * is negotiated via SECINFO in the kernel.
			 */
				if (nfsvers == NFS_V4 && syncaddr &&
				    host2netname(netname, host, NULL)) {
					argp->syncaddr =
					    malloc(sizeof (struct netbuf));
					argp->syncaddr->buf =
					    malloc(syncaddr->len);
					(void) memcpy(argp->syncaddr->buf,
					    syncaddr->buf, syncaddr->len);
					argp->syncaddr->len = syncaddr->len;
					argp->syncaddr->maxlen =
					    syncaddr->maxlen;
					argp->netname = strdup(netname);
					argp->flags |= NFSMNT_SECURE;
				}
			} /* syncaddr */
		} /* AUTH_DH */

		/*
		 * TSOL notes: automountd in tsol extension
		 * has "read down" capability, i.e. we allow
		 * a user to trigger an nfs mount into a lower
		 * labeled zone. We achieve this by always having
		 * root issue the mount request so that the
		 * lookup ops can go past /zone/<zone_name>
		 * on the server side.
		 */
		if (is_system_labeled())
			nfs_sec.sc_uid = (uid_t)0;
		else
			nfs_sec.sc_uid = uid;
		/*
		 * If AUTH_DH is a chosen flavor now, its data will be stored
		 * in the sec_data structure via nfs_clnt_secdata().
		 */
		if (!(secdata = nfs_clnt_secdata(&nfs_sec, host, argp->knconf,
		    syncaddr, secflags))) {
			syslog(LOG_ERR,
			    "errors constructing security related data\n");
			if (secflags & AUTH_F_RPCTIMESYNC)
				netbuf_free(syncaddr);
			else if (retaddrs)
				netdir_free(retaddrs, ND_ADDRLIST);
			if (argp->syncaddr)
				netbuf_free(argp->syncaddr);
			if (argp->netname)
				free(argp->netname);
			if (argp->hostname)
				free(argp->hostname);
			free_knconf(argp->knconf);
			netbuf_free(argp->addr);
			freenetconfigent(nconf);
			free(argp->fh);
			free(argp);
			head = prevhead;
			tail = prevtail;
			if (tail)
				tail->nfs_ext_u.nfs_extB.next = NULL;
			last_error = NFSERR_IO;
			destroy_auth_client_handle(cl);
			skipentry = 1;
			mfs->mfs_ignore = 1;
			continue;
		}
		NFS_ARGS_EXTB_secdata(*argp, secdata);
		/* end of security stuff */

		if (trace > 4)
			trace_prt(1,
			    "  nfsmount: have secure info for %s\n", remname);

		if (hasmntopt(&m, MNTOPT_GRPID) != NULL) {
			argp->flags |= NFSMNT_GRPID;
		}
		if (nopt(&m, MNTOPT_RSIZE, &argp->rsize)) {
			argp->flags |= NFSMNT_RSIZE;
		}
		if (nopt(&m, MNTOPT_WSIZE, &argp->wsize)) {
			argp->flags |= NFSMNT_WSIZE;
		}
		if (nopt(&m, MNTOPT_TIMEO, &argp->timeo)) {
			argp->flags |= NFSMNT_TIMEO;
		}
		if (nopt(&m, MNTOPT_RETRANS, &argp->retrans)) {
			argp->flags |= NFSMNT_RETRANS;
		}
		if (nopt(&m, MNTOPT_ACTIMEO, &argp->acregmax)) {
			argp->flags |= NFSMNT_ACREGMAX;
			argp->flags |= NFSMNT_ACDIRMAX;
			argp->flags |= NFSMNT_ACDIRMIN;
			argp->flags |= NFSMNT_ACREGMIN;
			argp->acdirmin = argp->acregmin = argp->acdirmax
			    = argp->acregmax;
		} else {
			if (nopt(&m, MNTOPT_ACREGMIN, &argp->acregmin)) {
				argp->flags |= NFSMNT_ACREGMIN;
			}
			if (nopt(&m, MNTOPT_ACREGMAX, &argp->acregmax)) {
				argp->flags |= NFSMNT_ACREGMAX;
			}
			if (nopt(&m, MNTOPT_ACDIRMIN, &argp->acdirmin)) {
				argp->flags |= NFSMNT_ACDIRMIN;
			}
			if (nopt(&m, MNTOPT_ACDIRMAX, &argp->acdirmax)) {
				argp->flags |= NFSMNT_ACDIRMAX;
			}
		}

		if (posix) {
			argp->pathconf = NULL;
			if (error = get_pathconf(cl, dir, remname,
			    &argp->pathconf, retries)) {
				if (secflags & AUTH_F_RPCTIMESYNC)
					netbuf_free(syncaddr);
				else if (retaddrs)
					netdir_free(retaddrs, ND_ADDRLIST);
				free_knconf(argp->knconf);
				netbuf_free(argp->addr);
				freenetconfigent(nconf);
				nfs_free_secdata(
				    argp->nfs_ext_u.nfs_extB.secdata);
				if (argp->syncaddr)
					netbuf_free(argp->syncaddr);
				if (argp->netname)
					free(argp->netname);
				if (argp->hostname)
					free(argp->hostname);
				free(argp->fh);
				free(argp);
				head = prevhead;
				tail = prevtail;
				if (tail)
					tail->nfs_ext_u.nfs_extB.next = NULL;
				last_error = NFSERR_IO;

				if (error == RET_RETRY && retries-- > 0) {
					destroy_auth_client_handle(cl);
					DELAY(delay);
					goto retry;
				}

				destroy_auth_client_handle(cl);
				skipentry = 1;
				mfs->mfs_ignore = 1;
				continue;
			}
			argp->flags |= NFSMNT_POSIX;
			if (trace > 4)
				trace_prt(1,
				    "  nfsmount: have pathconf for %s\n",
				    remname);
		}

		/*
		 * free loop-specific data structures
		 */
		destroy_auth_client_handle(cl);
		freenetconfigent(nconf);
		if (secflags & AUTH_F_RPCTIMESYNC)
			netbuf_free(syncaddr);
		else if (retaddrs)
			netdir_free(retaddrs, ND_ADDRLIST);

		/*
		 * Decide whether to use remote host's lockd or local locking.
		 * If we are using the public fh, we've already turned
		 * LLOCK on.
		 */
		if (hasmntopt(&m, MNTOPT_LLOCK))
			argp->flags |= NFSMNT_LLOCK;
		if (!(argp->flags & NFSMNT_LLOCK) && nfsvers == NFS_VERSION &&
		    remote_lock(host, argp->fh)) {
			syslog(loglevel, "No network locking on %s : "
			"contact admin to install server change", host);
			argp->flags |= NFSMNT_LLOCK;
		}

		/*
		 * Build a string for /etc/mnttab.
		 * If possible, coalesce strings with same 'dir' info.
		 */
		if ((mfs->mfs_flags & MFS_URL) == 0) {
			char *tmp;

			if (mnttabcnt) {
				p = strrchr(mnttabtext, (int)':');
				if (!p || strcmp(p+1, dir) != 0) {
					mnttabcnt += strlen(remname) + 2;
				} else {
					*p = '\0';
					mnttabcnt += strlen(rhost) + 2;
				}
				if ((tmp = realloc(mnttabtext,
				    mnttabcnt)) != NULL) {
					mnttabtext = tmp;
					strcat(mnttabtext, ",");
				} else {
					free(mnttabtext);
					mnttabtext = NULL;
				}
			} else {
				mnttabcnt = strlen(remname) + 1;
				if ((mnttabtext = malloc(mnttabcnt)) != NULL)
					mnttabtext[0] = '\0';
			}

			if (mnttabtext != NULL)
				strcat(mnttabtext, remname);

		} else {
			char *tmp;
			int more_cnt = 0;
			char sport[16];

			more_cnt += strlen("nfs://");
			more_cnt += strlen(mfs->mfs_host);

			if (mfs->mfs_port != 0) {
				(void) sprintf(sport, ":%u", mfs->mfs_port);
			} else
				sport[0] = '\0';

			more_cnt += strlen(sport);
			more_cnt += 1; /* "/" */
			more_cnt += strlen(mfs->mfs_dir);

			if (mnttabcnt) {
				more_cnt += 1; /* "," */
				mnttabcnt += more_cnt;

				if ((tmp = realloc(mnttabtext,
				    mnttabcnt)) != NULL) {
					mnttabtext = tmp;
					strcat(mnttabtext, ",");
				} else {
					free(mnttabtext);
					mnttabtext = NULL;
				}
			} else {
				mnttabcnt = more_cnt + 1;
				if ((mnttabtext = malloc(mnttabcnt)) != NULL)
					mnttabtext[0] = '\0';
			}

			if (mnttabtext != NULL) {
				strcat(mnttabtext, "nfs://");
				strcat(mnttabtext, mfs->mfs_host);
				strcat(mnttabtext, sport);
				strcat(mnttabtext, "/");
				strcat(mnttabtext, mfs->mfs_dir);
			}
		}

		if (!mnttabtext) {
			syslog(LOG_ERR, "nfsmount: no memory");
			last_error = NFSERR_IO;
			goto out;
		}

		/*
		 * At least one entry, can call mount(2).
		 */
		entries++;

		/*
		 * If replication was defeated, don't do more work
		 */
		if (!replicated)
			break;
	}


	/*
	 * Did we get through all possibilities without success?
	 */
	if (!entries)
		goto out;

	/* Make "xattr" the default if "noxattr" is not specified. */
	strcpy(mopts, opts);
	if (!hasmntopt(&m, MNTOPT_NOXATTR) && !hasmntopt(&m, MNTOPT_XATTR)) {
		if (strlen(mopts) > 0)
			strcat(mopts, ",");
		strcat(mopts, "xattr");
	}

	/*
	 * enable services as needed.
	 */
	{
		char **sl;

		if (strcmp(fstype, MNTTYPE_NFS4) == 0)
			sl = service_list_v4;
		else
			sl = service_list;

		(void) _check_services(sl);
	}

	/*
	 * Whew; do the mount, at last.
	 */
	if (trace > 1) {
		trace_prt(1, "	mount %s %s (%s)\n", mnttabtext, mntpnt, mopts);
	}

	/*
	 * About to do a nfs mount, make sure the mount_to is set for
	 * potential ephemeral mounts with NFSv4.
	 */
	set_nfsv4_ephemeral_mount_to();

	/*
	 * If no action list pointer then do the mount, otherwise
	 * build the actions list pointer with the mount information.
	 * so the mount can be done in the kernel.
	 */
	if (alp == NULL) {
		if (mount(mnttabtext, mntpnt, flags | MS_DATA, fstype,
		    head, sizeof (*head), mopts, MAX_MNTOPT_STR) < 0) {
			if (trace > 1)
				trace_prt(1, "	Mount of %s on %s: %d\n",
				    mnttabtext, mntpnt, errno);
			if (errno != EBUSY || verbose)
				syslog(LOG_ERR,
				"Mount of %s on %s: %m", mnttabtext, mntpnt);
			last_error = NFSERR_IO;
			goto out;
		}

		last_error = NFS_OK;
		if (stat(mntpnt, &stbuf) == 0) {
			if (trace > 1) {
				trace_prt(1, "	mount %s dev=%x rdev=%x OK\n",
				    mnttabtext, stbuf.st_dev, stbuf.st_rdev);
			}
		} else {
			if (trace > 1) {
				trace_prt(1, "	mount %s OK\n", mnttabtext);
				trace_prt(1, "	stat of %s failed\n", mntpnt);
			}

		}
	} else {
		alp->action.action = AUTOFS_MOUNT_RQ;
		alp->action.action_list_entry_u.mounta.spec =
		    strdup(mnttabtext);
		alp->action.action_list_entry_u.mounta.dir = strdup(mntpnt);
		alp->action.action_list_entry_u.mounta.flags =
		    flags | MS_DATA;
		alp->action.action_list_entry_u.mounta.fstype =
		    strdup(fstype);
		alp->action.action_list_entry_u.mounta.dataptr = (char *)head;
		alp->action.action_list_entry_u.mounta.datalen =
		    sizeof (*head);
		mntopts = malloc(strlen(mopts) + 1);
		strcpy(mntopts, mopts);
		mntopts[strlen(mopts)] = '\0';
		alp->action.action_list_entry_u.mounta.optptr = mntopts;
		alp->action.action_list_entry_u.mounta.optlen =
		    strlen(mntopts) + 1;
		last_error = NFS_OK;
		goto ret;
	}

out:
	argp = head;
	while (argp) {
		if (argp->pathconf)
			free(argp->pathconf);
		free_knconf(argp->knconf);
		netbuf_free(argp->addr);
		if (argp->syncaddr)
			netbuf_free(argp->syncaddr);
		if (argp->netname) {
			free(argp->netname);
		}
		if (argp->hostname)
			free(argp->hostname);
		nfs_free_secdata(argp->nfs_ext_u.nfs_extB.secdata);
		free(argp->fh);
		head = argp;
		argp = argp->nfs_ext_u.nfs_extB.next;
		free(head);
	}
ret:
	if (nfs_proto)
		free(nfs_proto);
	if (mnttabtext)
		free(mnttabtext);

	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {

		if (mfs->mfs_flags & MFS_ALLOC_DIR) {
			free(mfs->mfs_dir);
			mfs->mfs_dir = NULL;
			mfs->mfs_flags &= ~MFS_ALLOC_DIR;
		}

		if (mfs->mfs_args != NULL && alp == NULL) {
			free(mfs->mfs_args);
			mfs->mfs_args = NULL;
		}

		if (mfs->mfs_nconf != NULL) {
			freenetconfigent(mfs->mfs_nconf);
			mfs->mfs_nconf = NULL;
		}
	}

	return (last_error);
}

/*
 * get_pathconf(cl, path, fsname, pcnf, cretries)
 * ugliness that requires that ppathcnf and pathcnf stay consistent
 * cretries is a copy of retries used to determine when to syslog
 * on retry situations.
 */
static int
get_pathconf(CLIENT *cl, char *path, char *fsname, struct pathcnf **pcnf,
    int cretries)
{
	struct ppathcnf *p = NULL;
	enum clnt_stat rpc_stat;
	struct timeval timeout;

	p = (struct ppathcnf *)malloc(sizeof (struct ppathcnf));
	if (p == NULL) {
		syslog(LOG_ERR, "get_pathconf: Out of memory");
		return (RET_ERR);
	}
	memset((caddr_t)p, 0, sizeof (struct ppathcnf));

	timeout.tv_sec = 10;
	timeout.tv_usec = 0;
	rpc_stat = clnt_call(cl, MOUNTPROC_PATHCONF,
	    xdr_dirpath, (caddr_t)&path, xdr_ppathcnf, (caddr_t)p, timeout);
	if (rpc_stat != RPC_SUCCESS) {
		if (cretries-- <= 0) {
			syslog(LOG_ERR,
			    "get_pathconf: %s: server not responding: %s",
			    fsname, clnt_sperror(cl, ""));
		}
		free(p);
		return (RET_RETRY);
	}
	if (_PC_ISSET(_PC_ERROR, p->pc_mask)) {
		syslog(LOG_ERR, "get_pathconf: no info for %s", fsname);
		free(p);
		return (RET_ERR);
	}
	*pcnf = (struct pathcnf *)p;
	return (RET_OK);
}

void
netbuf_free(struct netbuf *nb)
{
	if (nb == NULL)
		return;
	free(nb->buf);
	free(nb);
}

#define	SMALL_HOSTNAME		20
#define	SMALL_PROTONAME		10
#define	SMALL_PROTOFMLYNAME		10

struct portmap_cache {
	int cache_prog;
	int cache_vers;
	time_t cache_time;
	char cache_small_hosts[SMALL_HOSTNAME + 1];
	char *cache_hostname;
	char *cache_proto;
	char *cache_protofmly;
	char cache_small_protofmly[SMALL_PROTOFMLYNAME + 1];
	char cache_small_proto[SMALL_PROTONAME + 1];
	struct netbuf cache_srv_addr;
	struct portmap_cache *cache_prev, *cache_next;
};

rwlock_t portmap_cache_lock;
static int portmap_cache_valid_time = 30;
struct portmap_cache *portmap_cache_head, *portmap_cache_tail;

#ifdef MALLOC_DEBUG
void
portmap_cache_flush(void)
{
	struct  portmap_cache *next = NULL, *cp;

	(void) rw_wrlock(&portmap_cache_lock);
	for (cp = portmap_cache_head; cp; cp = cp->cache_next) {
		if (cp->cache_hostname != NULL &&
		    cp->cache_hostname !=
		    cp->cache_small_hosts)
			free(cp->cache_hostname);
		if (cp->cache_proto != NULL &&
		    cp->cache_proto !=
		    cp->cache_small_proto)
			free(cp->cache_proto);
		if (cp->cache_srv_addr.buf != NULL)
			free(cp->cache_srv_addr.buf);
		next = cp->cache_next;
		free(cp);
	}
	portmap_cache_head = NULL;
	portmap_cache_tail = NULL;
	(void) rw_unlock(&portmap_cache_lock);
}
#endif

/*
 * Returns 1 if the entry is found in the cache, 0 otherwise.
 */
static int
portmap_cache_lookup(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig *nconf, struct netbuf *addrp)
{
	struct	portmap_cache *cachep, *prev, *next = NULL, *cp;
	int	retval = 0;

	timenow = time(NULL);

	(void) rw_rdlock(&portmap_cache_lock);

	/*
	 * Increment the portmap cache counters for # accesses and lookups
	 * Use a smaller factor (100 vs 1000 for the host cache) since
	 * initial analysis shows this cache is looked up 10% that of the
	 * host cache.
	 */
#ifdef CACHE_DEBUG
	portmap_cache_accesses++;
	portmap_cache_lookups++;
	if ((portmap_cache_lookups%100) == 0)
		trace_portmap_cache();
#endif /* CACHE_DEBUG */

	for (cachep = portmap_cache_head; cachep;
	    cachep = cachep->cache_next) {
		if (timenow > cachep->cache_time) {
			/*
			 * We stumbled across an entry in the cache which
			 * has timed out. Free up all the entries that
			 * were added before it, which will positionally
			 * be after this entry. And adjust neighboring
			 * pointers.
			 * When we drop the lock and re-acquire it, we
			 * need to start from the beginning.
			 */
			(void) rw_unlock(&portmap_cache_lock);
			(void) rw_wrlock(&portmap_cache_lock);
			for (cp = portmap_cache_head;
			    cp && (cp->cache_time >= timenow);
			    cp = cp->cache_next)
				;
			if (cp == NULL)
				goto done;
			/*
			 * Adjust the link of the predecessor.
			 * Make the tail point to the new last entry.
			 */
			prev = cp->cache_prev;
			if (prev == NULL) {
				portmap_cache_head = NULL;
				portmap_cache_tail = NULL;
			} else {
				prev->cache_next = NULL;
				portmap_cache_tail = prev;
			}
			for (; cp; cp = next) {
				if (cp->cache_hostname != NULL &&
				    cp->cache_hostname !=
				    cp->cache_small_hosts)
					free(cp->cache_hostname);
				if (cp->cache_proto != NULL &&
				    cp->cache_proto !=
				    cp->cache_small_proto)
					free(cp->cache_proto);
				if (cp->cache_srv_addr.buf != NULL)
					free(cp->cache_srv_addr.buf);
				next = cp->cache_next;
				free(cp);
			}
			goto done;
		}
		if (cachep->cache_hostname == NULL ||
		    prog != cachep->cache_prog || vers != cachep->cache_vers ||
		    strcmp(nconf->nc_proto, cachep->cache_proto) != 0 ||
		    strcmp(nconf->nc_protofmly, cachep->cache_protofmly) != 0 ||
		    strcmp(hostname, cachep->cache_hostname) != 0)
			continue;
		/*
		 * Cache Hit.
		 */
#ifdef CACHE_DEBUG
		portmap_cache_hits++;	/* up portmap cache hit counter */
#endif /* CACHE_DEBUG */
		addrp->len = cachep->cache_srv_addr.len;
		memcpy(addrp->buf, cachep->cache_srv_addr.buf, addrp->len);
		retval = 1;
		break;
	}
done:
	(void) rw_unlock(&portmap_cache_lock);
	return (retval);
}

static void
portmap_cache_enter(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig *nconf, struct netbuf *addrp)
{
	struct portmap_cache *cachep;
	int protofmlylen;
	int protolen, hostnamelen;

	timenow = time(NULL);

	cachep = malloc(sizeof (struct portmap_cache));
	if (cachep == NULL)
		return;
	memset((char *)cachep, 0, sizeof (*cachep));

	hostnamelen = strlen(hostname);
	if (hostnamelen <= SMALL_HOSTNAME)
		cachep->cache_hostname = cachep->cache_small_hosts;
	else {
		cachep->cache_hostname = malloc(hostnamelen + 1);
		if (cachep->cache_hostname == NULL)
			goto nomem;
	}
	strcpy(cachep->cache_hostname, hostname);
	protolen = strlen(nconf->nc_proto);
	if (protolen <= SMALL_PROTONAME)
		cachep->cache_proto = cachep->cache_small_proto;
	else {
		cachep->cache_proto = malloc(protolen + 1);
		if (cachep->cache_proto == NULL)
			goto nomem;
	}
	protofmlylen = strlen(nconf->nc_protofmly);
	if (protofmlylen <= SMALL_PROTOFMLYNAME)
		cachep->cache_protofmly = cachep->cache_small_protofmly;
	else {
		cachep->cache_protofmly = malloc(protofmlylen + 1);
		if (cachep->cache_protofmly == NULL)
			goto nomem;
	}

	strcpy(cachep->cache_proto, nconf->nc_proto);
	cachep->cache_prog = prog;
	cachep->cache_vers = vers;
	cachep->cache_time = timenow + portmap_cache_valid_time;
	cachep->cache_srv_addr.len = addrp->len;
	cachep->cache_srv_addr.buf = malloc(addrp->len);
	if (cachep->cache_srv_addr.buf == NULL)
		goto nomem;
	memcpy(cachep->cache_srv_addr.buf, addrp->buf, addrp->maxlen);
	cachep->cache_prev = NULL;
	(void) rw_wrlock(&portmap_cache_lock);
	/*
	 * There's a window in which we could have multiple threads making
	 * the same cache entry. This can be avoided by walking the cache
	 * once again here to check and see if there are duplicate entries
	 * (after grabbing the write lock). This isn't fatal and I'm not
	 * going to bother with this.
	 */
#ifdef CACHE_DEBUG
	portmap_cache_accesses++;	/* up portmap cache access counter */
#endif /* CACHE_DEBUG */
	cachep->cache_next = portmap_cache_head;
	if (portmap_cache_head != NULL)
		portmap_cache_head->cache_prev = cachep;
	portmap_cache_head = cachep;
	(void) rw_unlock(&portmap_cache_lock);
	return;

nomem:
	syslog(LOG_ERR, "portmap_cache_enter: Memory allocation failed");
	if (cachep->cache_srv_addr.buf)
		free(cachep->cache_srv_addr.buf);
	if (cachep->cache_proto && protolen > SMALL_PROTONAME)
		free(cachep->cache_proto);
	if (cachep->cache_hostname && hostnamelen > SMALL_HOSTNAME)
		free(cachep->cache_hostname);
	if (cachep->cache_protofmly && protofmlylen > SMALL_PROTOFMLYNAME)
		free(cachep->cache_protofmly);
	if (cachep)
		free(cachep);
	cachep = NULL;
}

static int
get_cached_srv_addr(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig *nconf, struct netbuf *addrp)
{
	if (portmap_cache_lookup(hostname, prog, vers, nconf, addrp))
		return (1);
	if (rpcb_getaddr(prog, vers, nconf, addrp, hostname) == 0)
		return (0);
	portmap_cache_enter(hostname, prog, vers, nconf, addrp);
	return (1);
}

/*
 * Get a network address on "hostname" for program "prog"
 * with version "vers".  If the port number is specified (non zero)
 * then try for a TCP/UDP transport and set the port number of the
 * resulting IP address.
 *
 * If the address of a netconfig pointer was passed and
 * if it's not null, use it as the netconfig otherwise
 * assign the address of the netconfig that was used to
 * establish contact with the service.
 *
 * tinfo argument is for matching the get_addr() defined in
 * ../nfs/mount/mount.c
 */

static struct netbuf *
get_addr(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig **nconfp, char *proto, ushort_t port,
    struct t_info *tinfo)
{
	enum clnt_stat cstat;

	return (get_server_netinfo(SERVER_ADDR, hostname, prog, vers, NULL,
	    nconfp, proto, port, tinfo, NULL, FALSE, NULL, &cstat));
}

static struct netbuf *
get_pubfh(char *hostname, rpcvers_t vers, mfs_snego_t *mfssnego,
    struct netconfig **nconfp, char *proto, ushort_t port,
    struct t_info *tinfo, caddr_t *fhp, bool_t get_pubfh, char *fspath)
{
	enum clnt_stat cstat;

	return (get_server_netinfo(SERVER_FH, hostname, NFS_PROGRAM, vers,
	    mfssnego, nconfp, proto, port, tinfo, fhp, get_pubfh, fspath,
	    &cstat));
}

static enum clnt_stat
get_ping(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig **nconfp, ushort_t port, bool_t direct_to_server)
{
	enum clnt_stat cstat;

	(void) get_server_netinfo(SERVER_PING, hostname, prog,
	    vers, NULL, nconfp, NULL, port, NULL, NULL,
	    direct_to_server, NULL, &cstat);

	return (cstat);
}

void *
get_server_netinfo(
	enum type_of_stuff type_of_stuff,
	char *hostname,
	rpcprog_t prog,
	rpcvers_t vers,
	mfs_snego_t *mfssnego,
	struct netconfig **nconfp,
	char *proto,
	ushort_t port,			/* may be zero */
	struct t_info *tinfo,
	caddr_t *fhp,
	bool_t direct_to_server,
	char *fspath,
	enum clnt_stat *cstatp)
{
	struct netbuf *nb = NULL;
	struct netconfig *nconf = NULL;
	NCONF_HANDLE *nc = NULL;
	int error = 0;
	int fd = 0;
	struct t_bind *tbind = NULL;
	int nthtry = FIRST_TRY;

	if (nconfp && *nconfp) {
		return (get_netconfig_info(type_of_stuff, hostname,
		    prog, vers, nconf, port, tinfo, tbind, fhp,
		    direct_to_server, fspath, cstatp, mfssnego));
	}

	/*
	 * No nconf passed in.
	 *
	 * Try to get a nconf from /etc/netconfig.
	 * First choice is COTS, second is CLTS unless proto
	 * is specified.  When we retry, we reset the
	 * netconfig list, so that we search the whole list
	 * for the next choice.
	 */
	if ((nc = setnetpath()) == NULL)
		goto done;

	/*
	 * If proto is specified, then only search for the match,
	 * otherwise try COTS first, if failed, then try CLTS.
	 */
	if (proto) {
		while ((nconf = getnetpath(nc)) != NULL) {
			if (strcmp(nconf->nc_proto, proto))
				continue;
			/*
			 * If the port number is specified then TCP/UDP
			 * is needed. Otherwise any cots/clts will do.
			 */
			if (port)  {
				if ((strcmp(nconf->nc_protofmly, NC_INET) &&
				    strcmp(nconf->nc_protofmly, NC_INET6)) ||
				    (strcmp(nconf->nc_proto, NC_TCP) &&
				    strcmp(nconf->nc_proto, NC_UDP)))
					continue;
			}
			nb = get_netconfig_info(type_of_stuff, hostname,
			    prog, vers, nconf, port, tinfo, tbind, fhp,
			    direct_to_server, fspath, cstatp, mfssnego);
			if (*cstatp == RPC_SUCCESS)
				break;

			assert(nb == NULL);

		}
		if (nconf == NULL)
			goto done;
	} else {
retry:
		while ((nconf = getnetpath(nc)) != NULL) {
			if (nconf->nc_flag & NC_VISIBLE) {
				if (nthtry == FIRST_TRY) {
					if ((nconf->nc_semantics ==
					    NC_TPI_COTS_ORD) ||
					    (nconf->nc_semantics ==
					    NC_TPI_COTS)) {
						if (port == 0)
							break;
						if ((strcmp(nconf->nc_protofmly,
						    NC_INET) == 0 ||
						    strcmp(nconf->nc_protofmly,
						    NC_INET6) == 0) &&
						    (strcmp(nconf->nc_proto,
						    NC_TCP) == 0))
							break;
					}
				}
				if (nthtry == SECOND_TRY) {
					if (nconf->nc_semantics ==
					    NC_TPI_CLTS) {
						if (port == 0)
							break;
						if ((strcmp(nconf->nc_protofmly,
						    NC_INET) == 0 ||
						    strcmp(nconf->nc_protofmly,
						    NC_INET6) == 0) &&
						    (strcmp(nconf->nc_proto,
						    NC_UDP) == 0))
							break;
					}
				}
			}
		}

		if (nconf == NULL) {
			if (++nthtry <= MNT_PREF_LISTLEN) {
				endnetpath(nc);
				if ((nc = setnetpath()) == NULL)
					goto done;
				goto retry;
			} else
				goto done;
		} else {
			nb = get_netconfig_info(type_of_stuff, hostname,
			    prog, vers, nconf, port, tinfo, tbind, fhp,
			    direct_to_server, fspath, cstatp, mfssnego);
			if (*cstatp != RPC_SUCCESS)
				/*
				 * Continue the same search path in the
				 * netconfig db until no more matched nconf
				 * (nconf == NULL).
				 */
				goto retry;
		}
	}

	/*
	 * Got nconf and nb.  Now dup the netconfig structure (nconf)
	 * and return it thru nconfp.
	 */
	if (nconf != NULL) {
		if ((*nconfp = getnetconfigent(nconf->nc_netid)) == NULL) {
			syslog(LOG_ERR, "no memory\n");
			free(nb);
			nb = NULL;
		}
	} else {
		*nconfp = NULL;
	}
done:
	if (nc)
		endnetpath(nc);
	return (nb);
}

void *
get_server_fh(char *hostname, rpcprog_t	prog, rpcvers_t	vers,
    mfs_snego_t *mfssnego, struct netconfig *nconf, ushort_t port,
    struct t_info *tinfo, struct t_bind *tbind, caddr_t *fhp,
    bool_t direct_to_server, char *fspath, enum clnt_stat *cstat)
{
	AUTH *ah = NULL;
	AUTH *new_ah = NULL;
	struct snego_t	snego;
	enum clnt_stat cs = RPC_TIMEDOUT;
	struct timeval tv;
	bool_t file_handle = 1;
	enum snego_stat sec;
	CLIENT *cl = NULL;
	int fd = -1;
	struct netbuf *nb = NULL;

	if (direct_to_server != TRUE)
		return (NULL);

	if (prog == NFS_PROGRAM && vers == NFS_V4)
		if (strncasecmp(nconf->nc_proto, NC_UDP, strlen(NC_UDP)) == 0)
			goto done;

	if ((fd = t_open(nconf->nc_device, O_RDWR, tinfo)) < 0)
		goto done;

	/* LINTED pointer alignment */
	if ((tbind = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR)) == NULL)
		goto done;

	if (setup_nb_parms(nconf, tbind, tinfo, hostname, fd,
	    direct_to_server, port, prog, vers, file_handle) < 0) {
		goto done;
	}

	cl = clnt_tli_create(fd, nconf, &tbind->addr, prog, vers, 0, 0);
	if (cl == NULL)
		goto done;

	ah = authsys_create_default();
	if (ah != NULL) {
#ifdef MALLOC_DEBUG
		drop_alloc("AUTH_HANDLE", cl->cl_auth,
		    __FILE__, __LINE__);
#endif
		AUTH_DESTROY(cl->cl_auth);
		cl->cl_auth = ah;
#ifdef MALLOC_DEBUG
		add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
		    __FILE__, __LINE__);
#endif
	}

	if (!mfssnego->snego_done && vers != NFS_V4) {
		/*
		 * negotiate sec flavor.
		 */
		snego.cnt = 0;
		if ((sec = nfs_sec_nego(vers, cl, fspath, &snego)) ==
		    SNEGO_SUCCESS) {
			int jj;

			/*
			 * check if server supports the one
			 * specified in the sec= option.
			 */
			if (mfssnego->sec_opt) {
				for (jj = 0; jj < snego.cnt; jj++) {
					if (snego.array[jj] ==
					    mfssnego->nfs_sec.sc_nfsnum) {
						mfssnego->snego_done = TRUE;
						break;
					}
				}
			}

			/*
			 * find a common sec flavor
			 */
			if (!mfssnego->snego_done) {
				for (jj = 0; jj < snego.cnt; jj++) {
					if (!nfs_getseconfig_bynumber(
					    snego.array[jj],
					    &mfssnego->nfs_sec)) {
						mfssnego->snego_done = TRUE;
						break;
					}
				}
			}
			if (!mfssnego->snego_done)
				goto done;
			/*
			 * Now that the flavor has been
			 * negotiated, get the fh.
			 *
			 * First, create an auth handle using the negotiated
			 * sec flavor in the next lookup to
			 * fetch the filehandle.
			 */
			new_ah = nfs_create_ah(cl, hostname,
			    &mfssnego->nfs_sec);
			if (new_ah  == NULL)
				goto done;
#ifdef MALLOC_DEBUG
			drop_alloc("AUTH_HANDLE", cl->cl_auth,
			    __FILE__, __LINE__);
#endif
			AUTH_DESTROY(cl->cl_auth);
			cl->cl_auth = new_ah;
#ifdef MALLOC_DEBUG
			add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
			    __FILE__, __LINE__);
#endif
		} else if (sec == SNEGO_ARRAY_TOO_SMALL ||
		    sec == SNEGO_FAILURE) {
			goto done;
		}
	}

	switch (vers) {
	case NFS_VERSION:
		{
		wnl_diropargs arg;
		wnl_diropres res;

		memset((char *)&arg.dir, 0, sizeof (wnl_fh));
		memset((char *)&res, 0, sizeof (wnl_diropres));
		arg.name = fspath;
		if (wnlproc_lookup_2(&arg, &res, cl) !=
		    RPC_SUCCESS || res.status != WNL_OK)
			goto done;
		*fhp = malloc(sizeof (wnl_fh));

		if (*fhp == NULL) {
			syslog(LOG_ERR, "no memory\n");
			goto done;
		}

		memcpy((char *)*fhp,
		    (char *)&res.wnl_diropres_u.wnl_diropres.file,
		    sizeof (wnl_fh));
		cs = RPC_SUCCESS;
		}
		break;
	case NFS_V3:
		{
		WNL_LOOKUP3args arg;
		WNL_LOOKUP3res res;
		nfs_fh3 *fh3p;

		memset((char *)&arg.what.dir, 0, sizeof (wnl_fh3));
		memset((char *)&res, 0, sizeof (WNL_LOOKUP3res));
		arg.what.name = fspath;
		if (wnlproc3_lookup_3(&arg, &res, cl) !=
		    RPC_SUCCESS || res.status != WNL3_OK)
			goto done;

		fh3p = (nfs_fh3 *)malloc(sizeof (*fh3p));

		if (fh3p == NULL) {
			syslog(LOG_ERR, "no memory\n");
			goto done;
		}

		fh3p->fh3_length =
		    res.WNL_LOOKUP3res_u.res_ok.object.data.data_len;
		memcpy(fh3p->fh3_u.data,
		    res.WNL_LOOKUP3res_u.res_ok.object.data.data_val,
		    fh3p->fh3_length);

		*fhp = (caddr_t)fh3p;

		cs = RPC_SUCCESS;
		}
		break;
	case NFS_V4:
		tv.tv_sec = 10;
		tv.tv_usec = 0;
		cs = clnt_call(cl, NULLPROC, xdr_void, 0,
		    xdr_void, 0, tv);
		if (cs != RPC_SUCCESS)
			goto done;

		*fhp = strdup(fspath);
		if (fhp == NULL) {
			cs = RPC_SYSTEMERROR;
			goto done;
		}
		break;
	}
	nb = (struct netbuf *)malloc(sizeof (struct netbuf));
	if (nb == NULL) {
		syslog(LOG_ERR, "no memory\n");
		cs = RPC_SYSTEMERROR;
		goto done;
	}
	nb->buf = (char *)malloc(tbind->addr.maxlen);
	if (nb->buf == NULL) {
		syslog(LOG_ERR, "no memory\n");
		free(nb);
		nb = NULL;
		cs = RPC_SYSTEMERROR;
		goto done;
	}
	(void) memcpy(nb->buf, tbind->addr.buf, tbind->addr.len);
	nb->len = tbind->addr.len;
	nb->maxlen = tbind->addr.maxlen;
done:
	if (cstat != NULL)
		*cstat = cs;
	destroy_auth_client_handle(cl);
	cleanup_tli_parms(tbind, fd);
	return (nb);
}

/*
 * Sends a null call to the remote host's (NFS program, versp). versp
 * may be "NULL" in which case the default maximum version is used.
 * Upon return, versp contains the maximum version supported iff versp!= NULL.
 */
enum clnt_stat
pingnfs(
	char *hostpart,
	int attempts,
	rpcvers_t *versp,
	rpcvers_t versmin,
	ushort_t port,			/* may be zero */
	bool_t usepub,
	char *path,
	char *proto)
{
	CLIENT *cl = NULL;
	struct timeval rpc_to_new = {15, 0};
	static struct timeval rpc_rtrans_new = {-1, -1};
	enum clnt_stat clnt_stat;
	int i, j;
	rpcvers_t versmax;	/* maximum version to try against server */
	rpcvers_t outvers;	/* version supported by host on last call */
	rpcvers_t vers_to_try;	/* to try different versions against host */
	char *hostname;
	struct netconfig *nconf;

	hostname = strdup(hostpart);
	if (hostname == NULL) {
		return (RPC_SYSTEMERROR);
	}
	unbracket(&hostname);

	if (path != NULL && strcmp(hostname, "nfs") == 0 &&
	    strncmp(path, "//", 2) == 0) {
		char *sport;

		hostname = strdup(path+2);

		if (hostname == NULL)
			return (RPC_SYSTEMERROR);

		path = strchr(hostname, '/');

		/*
		 * This cannot happen. If it does, give up
		 * on the ping as this is obviously a corrupt
		 * entry.
		 */
		if (path == NULL) {
			free(hostname);
			return (RPC_SUCCESS);
		}

		/*
		 * Probable end point of host string.
		 */
		*path = '\0';

		sport = strchr(hostname, ':');

		if (sport != NULL && sport < path) {

			/*
			 * Actual end point of host string.
			 */
			*sport = '\0';
			port = htons((ushort_t)atoi(sport+1));
		}

		usepub = TRUE;
	}

	/* Pick up the default versions and then set them appropriately */
	if (versp) {
		versmax = *versp;
		/* use versmin passed in */
	} else {
		read_default_nfs();
		set_versrange(0, &versmax, &versmin);
	}

	if (proto &&
	    strncasecmp(proto, NC_UDP, strlen(NC_UDP)) == 0 &&
	    versmax == NFS_V4) {
		if (versmin == NFS_V4) {
			if (versp) {
				*versp = versmax - 1;
				return (RPC_SUCCESS);
			}
			return (RPC_PROGUNAVAIL);
		} else {
			versmax--;
		}
	}

	if (versp)
		*versp = versmax;

	switch (cache_check(hostname, versp, proto)) {
	case GOODHOST:
		if (hostname != hostpart)
			free(hostname);
		return (RPC_SUCCESS);
	case DEADHOST:
		if (hostname != hostpart)
			free(hostname);
		return (RPC_TIMEDOUT);
	case NOHOST:
	default:
		break;
	}

	/*
	 * XXX The retransmission time rpcbrmttime is a global defined
	 * in the rpc library (rpcb_clnt.c). We use (and like) the default
	 * value of 15 sec in the rpc library. The code below is to protect
	 * us in case it changes. This need not be done under a lock since
	 * any # of threads entering this function will get the same
	 * retransmission value.
	 */
	if (rpc_rtrans_new.tv_sec == -1 && rpc_rtrans_new.tv_usec == -1) {
		__rpc_control(CLCR_GET_RPCB_RMTTIME, (char *)&rpc_rtrans_new);
		if (rpc_rtrans_new.tv_sec != 15 && rpc_rtrans_new.tv_sec != 0)
			if (trace > 1)
				trace_prt(1, "RPC library rttimer changed\n");
	}

	/*
	 * XXX Manipulate the total timeout to get the number of
	 * desired retransmissions. This code is heavily dependant on
	 * the RPC backoff mechanism in clnt_dg_call (clnt_dg.c).
	 */
	for (i = 0, j = rpc_rtrans_new.tv_sec; i < attempts-1; i++) {
		if (j < RPC_MAX_BACKOFF)
			j *= 2;
		else
			j = RPC_MAX_BACKOFF;
		rpc_to_new.tv_sec += j;
	}

	vers_to_try = versmax;

	/*
	 * check the host's version within the timeout
	 */
	if (trace > 1)
		trace_prt(1, "	ping: %s timeout=%ld request vers=%d min=%d\n",
		    hostname, rpc_to_new.tv_sec, versmax, versmin);

	if (usepub == FALSE) {
		do {
			/*
			 * If NFSv4, then we do the same thing as is used
			 * for public filehandles so that we avoid rpcbind
			 */
			if (vers_to_try == NFS_V4) {
				if (trace > 4) {
				trace_prt(1, "  pingnfs: Trying ping via "
				    "\"circuit_v\"\n");
				}

				cl = clnt_create_service_timed(hostname, "nfs",
				    NFS_PROGRAM, vers_to_try,
				    port, "circuit_v", &rpc_to_new);
				if (cl != NULL) {
					outvers = vers_to_try;
					break;
				}
				if (trace > 4) {
					trace_prt(1,
					    "  pingnfs: Can't ping via "
					    "\"circuit_v\" %s: RPC error=%d\n",
					    hostname, rpc_createerr.cf_stat);
				}

			} else {
				cl = clnt_create_vers_timed(hostname,
				    NFS_PROGRAM, &outvers, versmin, vers_to_try,
				    "datagram_v", &rpc_to_new);
				if (cl != NULL)
					break;
				if (trace > 4) {
					trace_prt(1,
					    "  pingnfs: Can't ping via "
					    "\"datagram_v\"%s: RPC error=%d\n",
					    hostname, rpc_createerr.cf_stat);
				}
				if (rpc_createerr.cf_stat == RPC_UNKNOWNHOST ||
				    rpc_createerr.cf_stat == RPC_TIMEDOUT)
					break;
				if (rpc_createerr.cf_stat ==
				    RPC_PROGNOTREGISTERED) {
					if (trace > 4) {
						trace_prt(1,
						    "  pingnfs: Trying ping "
						    "via \"circuit_v\"\n");
					}
					cl = clnt_create_vers_timed(hostname,
					    NFS_PROGRAM, &outvers,
					    versmin, vers_to_try,
					    "circuit_v", &rpc_to_new);
					if (cl != NULL)
						break;
					if (trace > 4) {
						trace_prt(1,
						    "  pingnfs: Can't ping "
						    "via \"circuit_v\" %s: "
						    "RPC error=%d\n",
						    hostname,
						    rpc_createerr.cf_stat);
					}
				}
			}

		/*
		 * backoff and return lower version to retry the ping.
		 * XXX we should be more careful and handle
		 * RPC_PROGVERSMISMATCH here, because that error is handled
		 * in clnt_create_vers(). It's not done to stay in sync
		 * with the nfs mount command.
		 */
			vers_to_try--;
			if (vers_to_try < versmin)
				break;
			if (versp != NULL) {	/* recheck the cache */
				*versp = vers_to_try;
				if (trace > 4) {
					trace_prt(1,
					    "  pingnfs: check cache: vers=%d\n",
					    *versp);
				}
				switch (cache_check(hostname, versp, proto)) {
				case GOODHOST:
					if (hostname != hostpart)
						free(hostname);
					return (RPC_SUCCESS);
				case DEADHOST:
					if (hostname != hostpart)
						free(hostname);
					return (RPC_TIMEDOUT);
				case NOHOST:
				default:
					break;
				}
			}
			if (trace > 4) {
				trace_prt(1, "  pingnfs: Try version=%d\n",
				    vers_to_try);
			}
		} while (cl == NULL);


		if (cl == NULL) {
			if (verbose)
				syslog(LOG_ERR, "pingnfs: %s%s",
				    hostname, clnt_spcreateerror(""));
			clnt_stat = rpc_createerr.cf_stat;
		} else {
			clnt_destroy(cl);
			clnt_stat = RPC_SUCCESS;
		}

	} else {
		for (vers_to_try = versmax; vers_to_try >= versmin;
		    vers_to_try--) {

			nconf = NULL;

			if (trace > 4) {
				trace_prt(1, "  pingnfs: Try version=%d "
				    "using get_ping()\n", vers_to_try);
			}

			clnt_stat = get_ping(hostname, NFS_PROGRAM,
			    vers_to_try, &nconf, port, TRUE);

			if (nconf != NULL)
				freenetconfigent(nconf);

			if (clnt_stat == RPC_SUCCESS) {
				outvers = vers_to_try;
				break;
			}
		}
	}

	if (trace > 1)
		clnt_stat == RPC_SUCCESS ?
		    trace_prt(1, "	pingnfs OK: nfs version=%d\n", outvers):
		    trace_prt(1, "	pingnfs FAIL: can't get nfs version\n");

	if (clnt_stat == RPC_SUCCESS) {
		cache_enter(hostname, versmax, outvers, proto, GOODHOST);
		if (versp != NULL)
			*versp = outvers;
	} else
		cache_enter(hostname, versmax, versmax, proto, DEADHOST);

	if (hostpart != hostname)
		free(hostname);

	return (clnt_stat);
}

#define	MNTTYPE_LOFS	"lofs"

int
loopbackmount(char *fsname, char *dir, char *mntopts, int overlay)
{
	struct mnttab mnt;
	int flags = 0;
	char fstype[] = MNTTYPE_LOFS;
	int dirlen;
	struct stat st;
	char optbuf[MAX_MNTOPT_STR];

	dirlen = strlen(dir);
	if (dir[dirlen-1] == ' ')
		dirlen--;

	if (dirlen == strlen(fsname) &&
	    strncmp(fsname, dir, dirlen) == 0) {
		syslog(LOG_ERR,
		    "Mount of %s on %s would result in deadlock, aborted\n",
		    fsname, dir);
		return (RET_ERR);
	}
	mnt.mnt_mntopts = mntopts;
	if (hasmntopt(&mnt, MNTOPT_RO) != NULL)
		flags |= MS_RDONLY;

	(void) strlcpy(optbuf, mntopts, sizeof (optbuf));

	if (overlay)
		flags |= MS_OVERLAY;

	if (trace > 1) {
		trace_prt(1, "  loopbackmount: fsname=%s, dir=%s, flags=%d\n",
		    fsname, dir, flags);
	}

	if (is_system_labeled()) {
		if (create_homedir((const char *)fsname,
		    (const char *)dir) == 0) {
			return (NFSERR_NOENT);
		}
	}

	if (mount(fsname, dir, flags | MS_DATA | MS_OPTIONSTR, fstype,
	    NULL, 0, optbuf, sizeof (optbuf)) < 0) {
		syslog(LOG_ERR, "Mount of %s on %s: %m", fsname, dir);
		return (RET_ERR);
	}

	if (stat(dir, &st) == 0) {
		if (trace > 1) {
			trace_prt(1,
			    "  loopbackmount of %s on %s dev=%x rdev=%x OK\n",
			    fsname, dir, st.st_dev, st.st_rdev);
		}
	} else {
		if (trace > 1) {
			trace_prt(1,
			    "  loopbackmount of %s on %s OK\n", fsname, dir);
			trace_prt(1, "	stat of %s failed\n", dir);
		}
	}

	return (0);
}

/*
 * Look for the value of a numeric option of the form foo=x.  If found, set
 * *valp to the value and return non-zero.  If not found or the option is
 * malformed, return zero.
 */

int
nopt(struct mnttab *mnt, char *opt, int *valp)
{
	char *equal;
	char *str;

	/*
	 * We should never get a null pointer, but if we do, it's better to
	 * ignore the option than to dump core.
	 */

	if (valp == NULL) {
		syslog(LOG_DEBUG, "null pointer for %s option", opt);
		return (0);
	}

	if (str = hasmntopt(mnt, opt)) {
		if (equal = strchr(str, '=')) {
			*valp = atoi(&equal[1]);
			return (1);
		} else {
			syslog(LOG_ERR, "Bad numeric option '%s'", str);
		}
	}
	return (0);
}

int
nfsunmount(struct mnttab *mnt)
{
	struct timeval timeout;
	CLIENT *cl;
	enum clnt_stat rpc_stat;
	char *host, *path;
	struct replica *list;
	int i, count = 0;
	int isv4mount = is_v4_mount(mnt->mnt_mountp);

	if (trace > 1)
		trace_prt(1, "	nfsunmount: umount %s\n", mnt->mnt_mountp);

	if (umount(mnt->mnt_mountp) < 0) {
		if (trace > 1) {
			trace_prt(1, "	nfsunmount: umount %s FAILED\n",
			    mnt->mnt_mountp);
		}
		if (errno)
			return (errno);
	}

	/*
	 * If this is a NFSv4 mount, the mount protocol was not used
	 * so we just return.
	 */
	if (isv4mount) {
		if (trace > 1) {
			trace_prt(1, "	nfsunmount: umount %s OK\n",
			    mnt->mnt_mountp);
		}
		return (0);
	}

	/*
	 * If mounted with -o public, then no need to contact server
	 * because mount protocol was not used.
	 */
	if (hasmntopt(mnt, MNTOPT_PUBLIC) != NULL) {
		return (0);
	}

	/*
	 * The rest of this code is advisory to the server.
	 * If it fails return success anyway.
	 */

	list = parse_replica(mnt->mnt_special, &count);
	if (!list) {
		if (count >= 0)
			syslog(LOG_ERR, "Memory allocation failed: %m");
		return (ENOMEM);
	}

	for (i = 0; i < count; i++) {

		host = list[i].host;
		path = list[i].path;

		/*
		 * Skip file systems mounted using WebNFS, because mount
		 * protocol was not used.
		 */
		if (strcmp(host, "nfs") == 0 && strncmp(path, "//", 2) == 0)
			continue;

		cl = clnt_create(host, MOUNTPROG, MOUNTVERS, "datagram_v");
		if (cl == NULL)
			break;
#ifdef MALLOC_DEBUG
		add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
		add_alloc("AUTH_HANDLE", cl->cl_auth, 0, __FILE__, __LINE__);
#endif
		if (__clnt_bindresvport(cl) < 0) {
			if (verbose) {
				syslog(LOG_ERR, "umount %s:%s: %s", host, path,
				    "Couldn't bind to reserved port");
			}
			destroy_auth_client_handle(cl);
			continue;
		}
#ifdef MALLOC_DEBUG
		drop_alloc("AUTH_HANDLE", cl->cl_auth, __FILE__, __LINE__);
#endif
		AUTH_DESTROY(cl->cl_auth);
		if ((cl->cl_auth = authsys_create_default()) == NULL) {
			if (verbose) {
				syslog(LOG_ERR, "umount %s:%s: %s", host, path,
				    "Failed creating default auth handle");
			}
			destroy_auth_client_handle(cl);
			continue;
		}
#ifdef MALLOC_DEBUG
		add_alloc("AUTH_HANDLE", cl->cl_auth, 0, __FILE__, __LINE__);
#endif
		timeout.tv_usec = 0;
		timeout.tv_sec = 5;
		rpc_stat = clnt_call(cl, MOUNTPROC_UMNT, xdr_dirpath,
		    (caddr_t)&path, xdr_void, (char *)NULL, timeout);
		if (verbose && rpc_stat != RPC_SUCCESS) {
			syslog(LOG_ERR, "%s: %s", host,
			    clnt_sperror(cl, "unmount"));
		}
		destroy_auth_client_handle(cl);
	}

	free_replica(list, count);

	if (trace > 1)
		trace_prt(1, "	nfsunmount: umount %s OK\n", mnt->mnt_mountp);

	return (0);
}

/*
 * Put a new entry in the cache chain by prepending it to the front.
 * If there isn't enough memory then just give up.
 */
static void
cache_enter(char *host, rpcvers_t reqvers, rpcvers_t outvers, char *proto,
    int state)
{
	struct cache_entry *entry;
	int cache_time = 30;	/* sec */

	timenow = time(NULL);

	entry = (struct cache_entry *)malloc(sizeof (struct cache_entry));
	if (entry == NULL)
		return;
	(void) memset((caddr_t)entry, 0, sizeof (struct cache_entry));
	entry->cache_host = strdup(host);
	if (entry->cache_host == NULL) {
		cache_free(entry);
		return;
	}
	entry->cache_reqvers = reqvers;
	entry->cache_outvers = outvers;
	entry->cache_proto = (proto == NULL ? NULL : strdup(proto));
	entry->cache_state = state;
	entry->cache_time = timenow + cache_time;
	(void) rw_wrlock(&cache_lock);
#ifdef CACHE_DEBUG
	host_cache_accesses++;		/* up host cache access counter */
#endif /* CACHE DEBUG */
	entry->cache_next = cache_head;
	cache_head = entry;
	(void) rw_unlock(&cache_lock);
}

static int
cache_check(char *host, rpcvers_t *versp, char *proto)
{
	int state = NOHOST;
	struct cache_entry *ce, *prev;

	timenow = time(NULL);

	(void) rw_rdlock(&cache_lock);

#ifdef CACHE_DEBUG
	/* Increment the lookup and access counters for the host cache */
	host_cache_accesses++;
	host_cache_lookups++;
	if ((host_cache_lookups%1000) == 0)
		trace_host_cache();
#endif /* CACHE DEBUG */

	for (ce = cache_head; ce; ce = ce->cache_next) {
		if (timenow > ce->cache_time) {
			(void) rw_unlock(&cache_lock);
			(void) rw_wrlock(&cache_lock);
			for (prev = NULL, ce = cache_head; ce;
			    prev = ce, ce = ce->cache_next) {
				if (timenow > ce->cache_time) {
					cache_free(ce);
					if (prev)
						prev->cache_next = NULL;
					else
						cache_head = NULL;
					break;
				}
			}
			(void) rw_unlock(&cache_lock);
			return (state);
		}
		if (strcmp(host, ce->cache_host) != 0)
			continue;
		if ((proto == NULL && ce->cache_proto != NULL) ||
		    (proto != NULL && ce->cache_proto == NULL))
			continue;
		if (proto != NULL &&
		    strcmp(proto, ce->cache_proto) != 0)
			continue;

		if (versp == NULL ||
		    (versp != NULL && *versp == ce->cache_reqvers) ||
		    (versp != NULL && *versp == ce->cache_outvers)) {
			if (versp != NULL)
				*versp = ce->cache_outvers;
			state = ce->cache_state;

			/* increment the host cache hit counters */
#ifdef CACHE_DEBUG
			if (state == GOODHOST)
				goodhost_cache_hits++;
			if (state == DEADHOST)
				deadhost_cache_hits++;
#endif /* CACHE_DEBUG */
			(void) rw_unlock(&cache_lock);
			return (state);
		}
	}
	(void) rw_unlock(&cache_lock);
	return (state);
}

/*
 * Free a cache entry and all entries
 * further down the chain since they
 * will also be expired.
 */
static void
cache_free(struct cache_entry *entry)
{
	struct cache_entry *ce, *next = NULL;

	for (ce = entry; ce; ce = next) {
		if (ce->cache_host)
			free(ce->cache_host);
		if (ce->cache_proto)
			free(ce->cache_proto);
		next = ce->cache_next;
		free(ce);
	}
}

#ifdef MALLOC_DEBUG
void
cache_flush(void)
{
	(void) rw_wrlock(&cache_lock);
	cache_free(cache_head);
	cache_head = NULL;
	(void) rw_unlock(&cache_lock);
}

void
flush_caches(void)
{
	mutex_lock(&cleanup_lock);
	cond_signal(&cleanup_start_cv);
	(void) cond_wait(&cleanup_done_cv, &cleanup_lock);
	mutex_unlock(&cleanup_lock);
	cache_flush();
	portmap_cache_flush();
}
#endif

/*
 * Returns 1, if port option is NFS_PORT or
 *	nfsd is running on the port given
 * Returns 0, if both port is not NFS_PORT and nfsd is not
 *	running on the port.
 */

static int
is_nfs_port(char *opts)
{
	struct mnttab m;
	uint_t nfs_port = 0;
	struct servent sv;
	char buf[256];
	int got_port;

	m.mnt_mntopts = opts;

	/*
	 * Get port specified in options list, if any.
	 */
	got_port = nopt(&m, MNTOPT_PORT, (int *)&nfs_port);

	/*
	 * if no port specified or it is same as NFS_PORT return nfs
	 * To use any other daemon the port number should be different
	 */
	if (!got_port || nfs_port == NFS_PORT)
		return (1);
	/*
	 * If daemon is nfsd, return nfs
	 */
	if (getservbyport_r(nfs_port, NULL, &sv, buf, 256) == &sv &&
	    strcmp(sv.s_name, "nfsd") == 0)
		return (1);

	/*
	 * daemon is not nfs
	 */
	return (0);
}


/*
 * destroy_auth_client_handle(cl)
 * destroys the created client handle
 */
void
destroy_auth_client_handle(CLIENT *cl)
{
	if (cl) {
		if (cl->cl_auth) {
#ifdef MALLOC_DEBUG
			drop_alloc("AUTH_HANDLE", cl->cl_auth,
			    __FILE__, __LINE__);
#endif
			AUTH_DESTROY(cl->cl_auth);
			cl->cl_auth = NULL;
		}
#ifdef MALLOC_DEBUG
		drop_alloc("CLNT_HANDLE", cl,
		    __FILE__, __LINE__);
#endif
		clnt_destroy(cl);
	}
}


/*
 * Attempt to figure out which version of NFS to use in pingnfs().  If
 * the version number was specified (i.e., non-zero), then use it.
 * Otherwise, default to the compiled-in default or the default as set
 * by the /etc/default/nfs configuration (as read by read_default().
 */
int
set_versrange(rpcvers_t nfsvers, rpcvers_t *vers, rpcvers_t *versmin)
{
	switch (nfsvers) {
	case 0:
		*vers = vers_max_default;
		*versmin = vers_min_default;
		break;
	case NFS_V4:
		*vers = NFS_V4;
		*versmin = NFS_V4;
		break;
	case NFS_V3:
		*vers = NFS_V3;
		*versmin = NFS_V3;
		break;
	case NFS_VERSION:
		*vers = NFS_VERSION;		/* version 2 */
		*versmin = NFS_VERSMIN;		/* version 2 */
		break;
	default:
		return (-1);
	}
	return (0);
}

#ifdef CACHE_DEBUG
/*
 * trace_portmap_cache()
 * traces the portmap cache values at desired points
 */
static void
trace_portmap_cache(void)
{
	syslog(LOG_ERR, "portmap_cache: accesses=%d lookups=%d hits=%d\n",
	    portmap_cache_accesses, portmap_cache_lookups,
	    portmap_cache_hits);
}

/*
 * trace_host_cache()
 * traces the host cache values at desired points
 */
static void
trace_host_cache(void)
{
	syslog(LOG_ERR,
	    "host_cache: accesses=%d lookups=%d deadhits=%d goodhits=%d\n",
	    host_cache_accesses, host_cache_lookups, deadhost_cache_hits,
	    goodhost_cache_hits);
}
#endif /* CACHE_DEBUG */

/*
 * Read the NFS SMF properties to determine if the
 * client has been configured for a new min/max for the NFS version to
 * use.
 */

#define	SVC_NFS_CLIENT	"svc:/network/nfs/client"

static void
read_default_nfs(void)
{
	struct stat buf;
	char defval[4];
	int errno, bufsz;
	int tmp, ret = 0;

	bufsz = 4;
	ret = nfs_smf_get_prop("client_versmin", defval, DEFAULT_INSTANCE,
	    SCF_TYPE_INTEGER, SVC_NFS_CLIENT, &bufsz);
	if (ret == SA_OK) {
		errno = 0;
		tmp = strtol(defval, NULL, 10);
		if (errno == 0) {
			vers_min_default = tmp;
		}
	}

	bufsz = 4;
	ret = nfs_smf_get_prop("client_versmax", defval, DEFAULT_INSTANCE,
	    SCF_TYPE_INTEGER, SVC_NFS_CLIENT, &bufsz);
	if (ret == SA_OK) {
		errno = 0;
		tmp = strtol(defval, NULL, 10);
		if (errno == 0) {
			vers_max_default = tmp;
		}
	}

	/*
	 * Quick sanity check on the values picked up from the
	 * defaults file.  Make sure that a mistake wasn't
	 * made that will confuse things later on.
	 * If so, reset to compiled-in defaults
	 */
	if (vers_min_default > vers_max_default ||
	    vers_min_default < NFS_VERSMIN ||
	    vers_max_default > NFS_VERSMAX) {
		if (trace > 1) {
			trace_prt(1,
	"  read_default: version minimum/maximum incorrectly configured\n");
			trace_prt(1,
"  read_default: config is min=%d, max%d. Resetting to min=%d, max%d\n",
			    vers_min_default, vers_max_default,
			    NFS_VERSMIN_DEFAULT,
			    NFS_VERSMAX_DEFAULT);
		}
		vers_min_default = NFS_VERSMIN_DEFAULT;
		vers_max_default = NFS_VERSMAX_DEFAULT;
	}
}

/*
 *  Find the mnttab entry that corresponds to "name".
 *  We're not sure what the name represents: either
 *  a mountpoint name, or a special name (server:/path).
 *  Return the last entry in the file that matches.
 */
static struct extmnttab *
mnttab_find(char *dirname)
{
	FILE *fp;
	struct extmnttab mnt;
	struct extmnttab *res = NULL;

	fp = fopen(MNTTAB, "r");
	if (fp == NULL) {
		if (trace > 1)
			trace_prt(1, "	mnttab_find: unable to open mnttab\n");
		return (NULL);
	}
	while (getextmntent(fp, &mnt, sizeof (struct extmnttab)) == 0) {
		if (strcmp(mnt.mnt_mountp, dirname) == 0 ||
		    strcmp(mnt.mnt_special, dirname) == 0) {
			if (res)
				fsfreemnttab(res);
			res = fsdupmnttab(&mnt);
		}
	}

	resetmnttab(fp);
	fclose(fp);
	if (res == NULL) {
		if (trace > 1) {
			trace_prt(1, "	mnttab_find: unable to find %s\n",
			    dirname);
		}
	}
	return (res);
}

/*
 * This function's behavior is taken from nfsstat.
 * Trying to determine what NFS version was used for the mount.
 */
static int
is_v4_mount(char *mntpath)
{
	kstat_ctl_t *kc = NULL;		/* libkstat cookie */
	kstat_t *ksp;
	ulong_t fsid;
	struct mntinfo_kstat mik;
	struct extmnttab *mntp;
	uint_t mnt_minor;

	if ((mntp = mnttab_find(mntpath)) == NULL)
		return (FALSE);

	/* save the minor number and free the struct so we don't forget */
	mnt_minor = mntp->mnt_minor;
	fsfreemnttab(mntp);

	if ((kc = kstat_open()) == NULL)
		return (FALSE);

	for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
		if (ksp->ks_type != KSTAT_TYPE_RAW)
			continue;
		if (strcmp(ksp->ks_module, "nfs") != 0)
			continue;
		if (strcmp(ksp->ks_name, "mntinfo") != 0)
			continue;
		if (mnt_minor != ksp->ks_instance)
			continue;

		if (kstat_read(kc, ksp, &mik) == -1)
			continue;

		(void) kstat_close(kc);
		if (mik.mik_vers == 4)
			return (TRUE);
		else
			return (FALSE);
	}
	(void) kstat_close(kc);

	return (FALSE);
}

static int
create_homedir(const char *src, const char *dst)
{

	struct stat stbuf;
	char *dst_username;
	struct passwd *pwd, pwds;
	char buf_pwd[NSS_BUFLEN_PASSWD];
	int homedir_len;
	int dst_dir_len;
	int src_dir_len;

	if (trace > 1)
		trace_prt(1, "entered create_homedir\n");

	if (stat(src, &stbuf) == 0) {
		if (trace > 1)
			trace_prt(1, "src exists\n");
		return (1);
	}

	dst_username = strrchr(dst, '/');
	if (dst_username) {
		dst_username++; /* Skip over slash */
		pwd = getpwnam_r(dst_username, &pwds, buf_pwd,
		    sizeof (buf_pwd));
		if (pwd == NULL) {
			return (0);
		}
	} else {
		return (0);
	}

	homedir_len = strlen(pwd->pw_dir);
	dst_dir_len = strlen(dst) - homedir_len;
	src_dir_len = strlen(src) - homedir_len;

	/* Check that the paths are in the same zone */
	if (src_dir_len < dst_dir_len ||
	    (strncmp(dst, src, dst_dir_len) != 0)) {
		if (trace > 1)
			trace_prt(1, "	paths don't match\n");
		return (0);
	}
	/* Check that mountpoint is an auto_home entry */
	if (dst_dir_len < 0 ||
	    (strcmp(pwd->pw_dir, dst + dst_dir_len) != 0)) {
		return (0);
	}

	/* Check that source is an home directory entry */
	if (src_dir_len < 0 ||
	    (strcmp(pwd->pw_dir, src + src_dir_len) != 0)) {
		if (trace > 1) {
			trace_prt(1, "	homedir (2) doesn't match %s\n",
			    src+src_dir_len);
		}
		return (0);
	}

	if (mkdir(src,
	    S_IRUSR | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH) == -1) {
		if (trace > 1) {
			trace_prt(1, "	Couldn't mkdir %s\n", src);
		}
		return (0);
	}

	if (chown(src, pwd->pw_uid, pwd->pw_gid) == -1) {
		unlink(src);
		return (0);
	}

	/* Created new home directory for the user */
	return (1);
}

void
free_nfs_args(struct nfs_args *argp)
{
	struct nfs_args *oldp;
	while (argp) {
		if (argp->pathconf)
			free(argp->pathconf);
		if (argp->knconf)
			free_knconf(argp->knconf);
		if (argp->addr)
			netbuf_free(argp->addr);
		if (argp->syncaddr)
			netbuf_free(argp->syncaddr);
		if (argp->netname)
			free(argp->netname);
		if (argp->hostname)
			free(argp->hostname);
		if (argp->nfs_ext_u.nfs_extB.secdata)
			nfs_free_secdata(argp->nfs_ext_u.nfs_extB.secdata);
		if (argp->fh)
			free(argp->fh);
		if (argp->nfs_ext_u.nfs_extA.secdata) {
			sec_data_t	*sd;
			sd = argp->nfs_ext_u.nfs_extA.secdata;
			if (sd == NULL)
				break;
			switch (sd->rpcflavor) {
			case AUTH_NONE:
			case AUTH_UNIX:
			case AUTH_LOOPBACK:
				break;
			case AUTH_DES:
			{
				dh_k4_clntdata_t	*dhk4;
				dhk4 = (dh_k4_clntdata_t *)sd->data;
				if (dhk4 == NULL)
					break;
				if (dhk4->syncaddr.buf)
					free(dhk4->syncaddr.buf);
				if (dhk4->knconf->knc_protofmly)
					free(dhk4->knconf->knc_protofmly);
				if (dhk4->knconf->knc_proto)
					free(dhk4->knconf->knc_proto);
				if (dhk4->knconf)
					free(dhk4->knconf);
				if (dhk4->netname)
					free(dhk4->netname);
				free(dhk4);
				break;
			}
			case RPCSEC_GSS:
			{
				gss_clntdata_t	*gss;
				gss = (gss_clntdata_t *)sd->data;
				if (gss == NULL)
					break;
				if (gss->mechanism.elements)
					free(gss->mechanism.elements);
				free(gss);
				break;
			}
			}
		}
		oldp = argp;
		if (argp->nfs_args_ext == NFS_ARGS_EXTB)
			argp = argp->nfs_ext_u.nfs_extB.next;
		else
			argp = NULL;
		free(oldp);
	}
}

void *
get_netconfig_info(enum type_of_stuff type_of_stuff, char *hostname,
    rpcprog_t prog, rpcvers_t vers, struct netconfig *nconf,
    ushort_t port, struct t_info *tinfo, struct t_bind *tbind,
    caddr_t *fhp, bool_t direct_to_server, char *fspath,
    enum clnt_stat *cstat, mfs_snego_t *mfssnego)
{
	struct netconfig *nb = NULL;
	int ping_server = 0;


	if (nconf == NULL)
		return (NULL);

	switch (type_of_stuff) {
	case SERVER_FH:
		nb = get_server_fh(hostname, prog, vers, mfssnego,
		    nconf, port, tinfo, tbind, fhp, direct_to_server,
		    fspath, cstat);
		break;
	case SERVER_PING:
		ping_server = 1;
		/* FALLTHROUGH */
	case SERVER_ADDR:
		nb = get_server_addrorping(hostname, prog, vers,
		    nconf, port, tinfo, tbind, fhp, direct_to_server,
		    fspath, cstat, ping_server);
		break;
	default:
		assert(nb != NULL);
	}
	return (nb);
}

/*
 * Get the server address or can we ping it or not.
 * Check the portmap cache first for server address.
 * If no entries there, ping the server with a NULLPROC rpc.
 */
void *
get_server_addrorping(char *hostname, rpcprog_t prog, rpcvers_t vers,
    struct netconfig *nconf, ushort_t port, struct t_info *tinfo,
    struct t_bind *tbind, caddr_t *fhp, bool_t direct_to_server,
    char *fspath, enum clnt_stat *cstat, int ping_server)
{
	struct timeval tv;
	enum clnt_stat cs = RPC_TIMEDOUT;
	struct netbuf *nb = NULL;
	CLIENT *cl = NULL;
	int fd = -1;

	if (prog == NFS_PROGRAM && vers == NFS_V4)
		if (strncasecmp(nconf->nc_proto, NC_UDP, strlen(NC_UDP)) == 0)
			goto done;

	if ((fd = t_open(nconf->nc_device, O_RDWR, tinfo)) < 0) {
		goto done;
	}

	/* LINTED pointer alignment */
	if ((tbind = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR))
	    == NULL) {
		goto done;
	}

	if (direct_to_server != TRUE) {
		if (!ping_server) {
			if (get_cached_srv_addr(hostname, prog, vers,
			    nconf, &tbind->addr) == 0)
				goto done;
		} else {
			if (port == 0)
				goto done;
		}
	}
	if (setup_nb_parms(nconf, tbind, tinfo, hostname,
	    fd, direct_to_server, port, prog, vers, 0) < 0)
		goto done;

	if (port || (direct_to_server == TRUE)) {
		tv.tv_sec = 10;
		tv.tv_usec = 0;
		cl = clnt_tli_create(fd, nconf, &tbind->addr,
		    prog, vers, 0, 0);
		if (cl == NULL)
			goto done;

		cs = clnt_call(cl, NULLPROC, xdr_void, 0,
		    xdr_void, 0, tv);
		if (cs != RPC_SUCCESS) {
			syslog(LOG_ERR, "error is %d", cs);
			goto done;
		}
	}
	if (!ping_server) {
		nb = (struct netbuf *)malloc(sizeof (struct netbuf));
		if (nb == NULL) {
			syslog(LOG_ERR, "no memory\n");
			goto done;
		}
		nb->buf = (char *)malloc(tbind->addr.maxlen);
		if (nb->buf == NULL) {
			syslog(LOG_ERR, "no memory\n");
			free(nb);
			nb = NULL;
			goto done;
		}
		(void) memcpy(nb->buf, tbind->addr.buf, tbind->addr.len);
		nb->len = tbind->addr.len;
		nb->maxlen = tbind->addr.maxlen;
		cs = RPC_SUCCESS;
	}
done:
	destroy_auth_client_handle(cl);
	cleanup_tli_parms(tbind, fd);
	*cstat = cs;
	return (nb);
}
/*
 * 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
 */
/*
 *	autod_parse.c
 *
 *	Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 *	Use is subject to license terms.
 *      Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <errno.h>
#include <pwd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/tiuser.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <thread.h>
#include <rpc/rpc.h>
#include <rpcsvc/mount.h>
#include <fcntl.h>
#include <limits.h>
#include "automount.h"

/*
 * This structure is used to determine the hierarchical
 * relationship between directories
 */
typedef struct _hiernode {
	char dirname[MAXFILENAMELEN+1];
	struct _hiernode *subdir;
	struct _hiernode *leveldir;
	struct mapent *mapent;
} hiernode;

void free_mapent(struct mapent *);

static int mapline_to_mapent(struct mapent **, struct mapline *, char *, char *,
				char *, char *, uint_t);
static int hierarchical_sort(struct mapent *, hiernode **, char *, char *);
static int push_options(hiernode *, char *, char *, int);
static int set_mapent_opts(struct mapent *, char *, char *, char *);
static void get_opts(char *, char *, char *, bool_t *);
static int fstype_opts(struct mapent *, char *, char *, char *);
static int modify_mapents(struct mapent **, char *, char *, char *, hiernode *,
			char *, uint_t, bool_t);
static int set_and_fake_mapent_mntlevel(hiernode *, char *, char *, char *,
				struct mapent **, uint_t, char *, bool_t);
static int mark_level1_root(hiernode *, char *);
static int mark_and_fake_level1_noroot(hiernode *, char *, char *, char *,
				    struct mapent **, uint_t i, char *);
static int convert_mapent_to_automount(struct mapent *, char *, char *);
static int automount_opts(char **, char *);
static int parse_fsinfo(char *, struct mapent *);
static int parse_nfs(char *, struct mapent *, char *, char *, char **, char **,
				int);
static int parse_special(struct mapent *, char *, char *, char **, char **,
				int);
static int get_dir_from_path(char *, char **, int);
static int alloc_hiernode(hiernode **, char *);
static void free_hiernode(hiernode *);
static void trace_mapents(char *, struct mapent *);
static void trace_hierarchy(hiernode *, int);
static struct mapent *do_mapent_hosts(char *, char *, uint_t);
static void freeex_ent(struct exportnode *);
static void freeex(struct exportnode *);
static void dump_mapent_err(struct mapent *, char *, char *);

#define	PARSE_OK	0
#define	PARSE_ERROR	-1
#define	MAX_FSLEN	32

/*
 * mapentry error type defininitions
 */
#define	MAPENT_NOERR	0
#define	MAPENT_UATFS	1

/*
 * parse_entry(char *key, char *mapname, char *mapopts, struct mapline *ml,
 *			char *subdir, uint_t isdirect, bool_t mount_access)
 * Parses the data in ml to build a mapentry list containing the information
 * for the mounts/lookups to be performed. Builds an intermediate mapentry list
 * by processing ml, hierarchically sorts (builds a tree of) the list according
 * to mountpoint. Then pushes options down the hierarchy, and fills in the mount
 * file system. Finally, modifies the intermediate list depending on how far
 * in the hierarchy the current request is (uses subdir). Deals with special
 * case of /net map parsing.
 * Returns a pointer to the head of the mapentry list.
 */
struct mapent *
parse_entry(char *key, char *mapname, char *mapopts, struct mapline *ml,
    char *subdir, uint_t isdirect, bool_t mount_access)
{
	char *p;
	char defaultopts[AUTOFS_MAXOPTSLEN];

	struct mapent *mapents = NULL;
	hiernode *rootnode = NULL;
	char *lp = ml->linebuf;

	if (trace > 1)
		trace_prt(1, "  mapline: %s\n", ml->linebuf);

	/*
	 * Assure the key is only one token long.
	 * This prevents options from sneaking in through the
	 * command line or corruption of /etc/mnttab.
	 */
	for (p = key; *p != '\0'; p++) {
		if (isspace(*p)) {
			syslog(LOG_ERR,
			"parse_entry: bad key in map %s: %s", mapname, key);
			return ((struct mapent *)NULL);
		}
	}

	/*
	 * select the appropriate parser, and build the mapentry list
	 */
	if (strcmp(lp, "-hosts") == 0) {
		/*
		 * the /net parser - uses do_mapent_hosts to build mapents.
		 * The mapopts are considered default for every entry, so we
		 * don't push options down hierarchies.
		 */
		mapents = do_mapent_hosts(mapopts, key, isdirect);
		if (mapents == NULL)		/* nothing to free */
			return (mapents);

		if (trace > 3)
			trace_mapents("do_mapent_hosts:(return)", mapents);

		if (hierarchical_sort(mapents, &rootnode, key, mapname)
		    != PARSE_OK)
			goto parse_error;
	} else {
		/*
		 * all other parsing
		 */
		if (mapline_to_mapent(&mapents, ml, key, mapname,
		    mapopts, defaultopts, isdirect) != PARSE_OK)
			goto parse_error;

		if (mapents == NULL)
			return (mapents);

		if (hierarchical_sort(mapents, &rootnode, key, mapname)
		    != PARSE_OK)
			goto parse_error;

		if (push_options(rootnode, defaultopts, mapopts,
		    MAPENT_NOERR) != PARSE_OK)
			goto parse_error;

		if (trace > 3) {
			trace_prt(1, "\n\tpush_options (return)\n");
			trace_prt(0, "\tdefault options=%s\n", defaultopts);
			trace_hierarchy(rootnode, 0);
		};

		if (parse_fsinfo(mapname, mapents) != PARSE_OK)
			goto parse_error;
	}

	/*
	 * Modify the mapentry list. We *must* do this only after
	 * the mapentry list is completely built (since we need to
	 * have parse_fsinfo called first).
	 */
	if (modify_mapents(&mapents, mapname, mapopts, subdir,
	    rootnode, key, isdirect, mount_access) != PARSE_OK)
		goto parse_error;

	/*
	 * XXX: its dangerous to use rootnode after modify mapents as
	 * it may be pointing to mapents that have been freed
	 */
	if (rootnode != NULL)
		free_hiernode(rootnode);

	return (mapents);

parse_error:
	syslog(LOG_ERR, "parse_entry: mapentry parse error: map=%s key=%s",
	    mapname, key);
	free_mapent(mapents);
	if (rootnode != NULL)
		free_hiernode(rootnode);
	return ((struct mapent *)NULL);
}


/*
 * mapline_to_mapent(struct mapent **mapents, struct mapline *ml,
 *		char *key, char *mapname, char *mapopts, char *defaultopts,
 *              uint_t isdirect)
 * Parses the mapline information in ml word by word to build an intermediate
 * mapentry list, which is passed back to the caller. The mapentries may have
 * holes (example no options), as they are completed only later. The logic is
 * awkward, but needed to provide the supported flexibility in the map entries.
 * (especially the first line). Note that the key is the full pathname of the
 * directory to be mounted in a direct map, and ml is the mapentry beyond key.
 * Returns PARSE_OK or an appropriate error value.
 */
static int
mapline_to_mapent(struct mapent **mapents, struct mapline *ml, char *key,
    char *mapname, char *mapopts, char *defaultopts,
    uint_t isdirect)
{
	struct mapent *me = NULL;
	struct mapent *mp;
	char w[MAXPATHLEN];
	char wq[MAXPATHLEN];
	char w1[MAXPATHLEN];
	int implied;

	char *lp = ml->linebuf;
	char *lq = ml->lineqbuf;

	/* do any macro expansions that are required to complete ml */
	if (macro_expand(key, lp, lq, LINESZ)) {
		syslog(LOG_ERR,
		"mapline_to_mapent: map %s: line too long (max %d chars)",
		    mapname, LINESZ - 1);
		return (PARSE_ERROR);
	}
	if (trace > 3 && (strcmp(ml->linebuf, lp) != 0))
		trace_prt(1,
		    "  mapline_to_mapent: (expanded) mapline (%s,%s)\n",
		    ml->linebuf, ml->lineqbuf);

	/* init the head of mapentry list to null */
	*mapents = NULL;

	/*
	 * Get the first word - its either a '-' if default options provided,
	 * a '/', if the mountroot is implicitly provided, or a mount filesystem
	 * if the mountroot is implicit. Note that if the first word begins with
	 * a '-' then the second must be read and it must be a mountpoint or a
	 * mount filesystem. Use mapopts if no default opts are provided.
	 */
	if (getword(w, wq, &lp, &lq, ' ', sizeof (w)) == -1)
		return (PARSE_ERROR);
	if (*w == '-') {
		strcpy(defaultopts, w);
		if (getword(w, wq, &lp, &lq, ' ', sizeof (w)) == -1)
			return (PARSE_ERROR);
	} else
		strcpy(defaultopts, mapopts);

	/*
	 * implied is true if there is no '/'
	 * We need the same code path if we have an smbfs mount.
	 */
	implied = (*w != '/') || (strstr(defaultopts, "fstype=smbfs") != NULL);
	while (*w == '/' || implied) {
		mp = me;
		if ((me = (struct mapent *)malloc(sizeof (*me))) == NULL)
			goto alloc_failed;
		(void) memset((char *)me, 0, sizeof (*me));
		if (*mapents == NULL)	/* special case of head */
			*mapents = me;
		else
			mp->map_next = me;

		/*
		 * direct maps get an empty string as root - to be filled
		 * by the entire path later. Indirect maps get /key as the
		 * map root. Note that xfn maps don't care about the root
		 * - they override it in getmapent_fn().
		 */
		if (isdirect) {
			*w1 = '\0';
		} else {
			strcpy(w1, "/");
			strcat(w1, key);
		}
		if ((me->map_root = strdup(w1)) == NULL)
			goto alloc_failed;

		/* mntpnt is empty for the mount root */
		if (strcmp(w, "/") == 0 || implied)
			me->map_mntpnt = strdup("");
		else
			me->map_mntpnt = strdup(w);
		if (me->map_mntpnt == NULL)
			goto alloc_failed;

		/*
		 * If implied, the word must be a mount filesystem,
		 * and its already read in; also turn off implied - its
		 * not applicable except for the mount root. Else,
		 * read another (or two) words depending on if there's
		 * an option.
		 */
		if (implied)   /* must be a mount filesystem */
			implied = 0;
		else {
			if (getword(w, wq, &lp, &lq, ' ', sizeof (w)) == -1)
				return (PARSE_ERROR);
			if (w[0] == '-') {
				/* mount options */
				if ((me->map_mntopts = strdup(w)) == NULL)
					goto alloc_failed;
				if (getword(w, wq, &lp, &lq, ' ',
				    sizeof (w)) == -1)
					return (PARSE_ERROR);
			}
		}

		/*
		 * must be a mount filesystem or a set of filesystems at
		 * this point.
		 */
		if (w[0] == '\0' || w[0] == '-') {
			syslog(LOG_ERR,
			"mapline_to_mapent: bad location=%s map=%s key=%s",
			    w, mapname, key);
			return (PARSE_ERROR);
		}

		/*
		 * map_fsw and map_fswq hold information which will be
		 * used to determine filesystem information at a later
		 * point. This is required since we can only find out
		 * about the mount file system after the directories
		 * are hierarchically sorted and options have been pushed
		 * down the hierarchies.
		 */
		if (((me->map_fsw = strdup(w)) == NULL) ||
		    ((me->map_fswq = strdup(wq)) == NULL))
			goto alloc_failed;

		/*
		 * the next word, if any, is either another mount point or a
		 * mount filesystem if more than one server is listed.
		 */
		if (getword(w, wq, &lp, &lq, ' ', sizeof (w)) == -1)
			return (PARSE_ERROR);
		while (*w && *w != '/') {	/* more than 1 server listed */
			int len;
			char *fsw, *fswq;
			len = strlen(me->map_fsw) + strlen(w) + 4;
			if ((fsw = (char *)malloc(len)) == NULL)
				goto alloc_failed;
			sprintf(fsw, "%s   %s", me->map_fsw, w);
			free(me->map_fsw);
			me->map_fsw = fsw;
			len = strlen(me->map_fswq) + strlen(wq) + 4;
			if ((fswq = (char *)malloc(len)) == NULL)
				goto alloc_failed;
			sprintf(fswq, "%s   %s", me->map_fswq, wq);
			free(me->map_fswq);
			me->map_fswq = fswq;
			if (getword(w, wq, &lp, &lq, ' ', sizeof (w)) == -1)
				return (PARSE_ERROR);
		}

		/* initialize flags */
		me->map_mntlevel = -1;
		me->map_modified = FALSE;
		me->map_faked = FALSE;
		me->map_err = MAPENT_NOERR;

		me->map_next = NULL;
	}

	if (*mapents == NULL || w[0] != '\0') {	/* sanity check */
		if (verbose) {
			if (*mapents == NULL)
				syslog(LOG_ERR,
				"mapline_to_mapent: parsed with null mapents");
			else
				syslog(LOG_ERR,
				"mapline_to_mapent: parsed nononempty w=%s", w);
		}
		return (PARSE_ERROR);
	}

	if (trace > 3)
		trace_mapents("mapline_to_mapent:", *mapents);

	return (PARSE_OK);

alloc_failed:
	syslog(LOG_ERR, "mapline_to_mapent: Memory allocation failed");
	return (ENOMEM);
}

/*
 * hierarchical_sort(struct mapent *mapents, hiernode **rootnode, char *key
 *                   char *mapname)
 * sorts the mntpnts in each mapent to build a hierarchy of nodes, with
 * with the rootnode being the mount root. The hierarchy is setup as
 * levels, and subdirs below each level. Provides a link from node to
 * the relevant mapentry.
 * Returns PARSE_OK or appropriate error value
 */
static int
hierarchical_sort(struct mapent *mapents, hiernode **rootnode, char *key,
    char *mapname)
{
	hiernode *prevnode, *currnode, *newnode;
	char *path;
	char dirname[MAXFILENAMELEN];

	int rc = PARSE_OK;
	struct mapent *me = mapents;

	/* allocate the rootnode with a default path of "" */
	*rootnode = NULL;
	if ((rc = alloc_hiernode(rootnode, "")) != PARSE_OK)
		return (rc);

	/*
	 * walk through mapents - for each mapent, locate the position
	 * within the hierarchy by walking across leveldirs, and
	 * subdirs of matched leveldirs. Starts one level below
	 * the root (assumes an implicit match with rootnode).
	 * XXX - this could probably be done more cleanly using recursion.
	 */
	while (me != NULL) {

		path = me->map_mntpnt;

		if ((rc = get_dir_from_path(dirname, &path,
		    sizeof (dirname))) != PARSE_OK)
			return (rc);

		prevnode = *rootnode;
		currnode = (*rootnode)->subdir;

		while (dirname[0] != '\0') {
			if (currnode != NULL) {
				if (strcmp(currnode->dirname, dirname) == 0) {
					/*
					 * match found - mntpnt is a child of
					 * this node
					 */
					prevnode = currnode;
					currnode = currnode->subdir;
				} else {
					prevnode = currnode;
					currnode = currnode->leveldir;

					if (currnode == NULL) {
						/*
						 * No more leveldirs to match.
						 * Add a new one
						 */
						if ((rc = alloc_hiernode
						    (&newnode, dirname))
						    != PARSE_OK)
							return (rc);
						prevnode->leveldir = newnode;
						prevnode = newnode;
						currnode = newnode->subdir;
					} else {
						/* try this leveldir */
						continue;
					}
				}
			} else {
				/* no more subdirs to match. Add a new one */
				if ((rc = alloc_hiernode(&newnode,
				    dirname)) != PARSE_OK)
					return (rc);
				prevnode->subdir = newnode;
				prevnode = newnode;
				currnode = newnode->subdir;
			}
			if ((rc = get_dir_from_path(dirname, &path,
			    sizeof (dirname))) != PARSE_OK)
				return (rc);
		}

		if (prevnode->mapent != NULL) {
			/* duplicate mntpoint found */
			syslog(LOG_ERR,
			"hierarchical_sort: duplicate mntpnt map=%s key=%s",
			    mapname, key);
			return (PARSE_ERROR);
		}

		/* provide a pointer from node to mapent */
		prevnode->mapent = me;
		me = me->map_next;
	}

	if (trace > 3) {
		trace_prt(1, "\n\thierarchical_sort:\n");
		trace_hierarchy(*rootnode, 0);	/* 0 is rootnode's level */
	}

	return (rc);
}

/*
 * push_options(hiernode *node, char *opts, char *mapopts, int err)
 * Pushes the options down a hierarchical structure. Works recursively from the
 * root, which is passed in on the first call. Uses a replacement policy.
 * If a node points to a mapentry, and it has an option, then thats the option
 * for that mapentry. Else, the node's mapent inherits the option from the
 * default (which may be the global option for the entry or mapopts).
 * err is useful in flagging entries with errors in pushing options.
 * returns PARSE_OK or appropriate error value.
 */
static int
push_options(hiernode *node, char *defaultopts, char *mapopts, int err)
{
	int rc = PARSE_OK;
	struct mapent *me = NULL;

	/* ensure that all the dirs at a level are passed the default options */
	while (node != NULL) {
		me = node->mapent;
		if (me != NULL) {	/* not all nodes point to a mapentry */
			me->map_err = err;
			if ((rc = set_mapent_opts(me, me->map_mntopts,
			    defaultopts, mapopts)) != PARSE_OK)
				return (rc);
		}

		/* push the options to subdirs */
		if (node->subdir != NULL) {
			if (node->mapent && strcmp(node->mapent->map_fstype,
			    MNTTYPE_AUTOFS) == 0)
				err = MAPENT_UATFS;
			if ((rc = push_options(node->subdir, defaultopts,
			    mapopts, err)) != PARSE_OK)
				return (rc);
		}
		node = node->leveldir;
	}
	return (rc);
}

#define	FSTYPE "fstype"
#define	FSTYPE_EQ "fstype="
#define	NO_OPTS ""

/*
 * set_mapent_opts(struct mapent *me, char *opts, char *defaultopts,
 *			char *mapopts)
 * sets the mapentry's options, fstype and mounter fields by separating
 * out the fstype part from the opts. Use default options if opts is NULL.
 * Note taht defaultopts may be the same as mapopts.
 * Returns PARSE_OK or appropriate error value.
 */
static int
set_mapent_opts(struct mapent *me, char *opts, char *defaultopts,
    char *mapopts)
{
	char entryopts[AUTOFS_MAXOPTSLEN];
	char fstype[MAX_FSLEN], mounter[MAX_FSLEN];
	int rc = PARSE_OK;
	bool_t fstype_opt = FALSE;

	strcpy(fstype, MNTTYPE_NFS);		/* default */

	/* set options to default options, if none exist for this entry */
	if (opts == NULL) {
		opts = defaultopts;
		if (defaultopts == NULL) { /* NULL opts for entry */
			strcpy(mounter, fstype);
			goto done;
		}
	}
	if (*opts == '-')
		opts++;

	/* separate opts into fstype and (other) entrypopts */
	get_opts(opts,	entryopts, fstype, &fstype_opt);

	/* replace any existing opts */
	if (me->map_mntopts != NULL)
		free(me->map_mntopts);
	if ((me->map_mntopts = strdup(entryopts)) == NULL)
		return (ENOMEM);
	strcpy(mounter,	fstype);

	/*
	 * child options are exactly fstype = somefs, we need to do some
	 * more option pushing work.
	 */
	if (fstype_opt == TRUE &&
	    (strcmp(me->map_mntopts, NO_OPTS) == 0)) {
		free(me->map_mntopts);
		if ((rc = fstype_opts(me, opts, defaultopts,
		    mapopts)) != PARSE_OK)
			return (rc);
	}

done:
	if (((me->map_fstype = strdup(fstype)) == NULL) ||
	    ((me->map_mounter = strdup(mounter)) == NULL)) {
		if (me->map_fstype != NULL)
			free(me->map_fstype);
		syslog(LOG_ERR, "set_mapent_opts: No memory");
		return (ENOMEM);
	}

	return (rc);
}

/*
 * Check the option string for an "fstype"
 * option.  If found, return the fstype
 * and the option string with the fstype
 * option removed, e.g.
 *
 *  input:  "fstype=nfs,ro,nosuid"
 *  opts:   "ro,nosuid"
 *  fstype: "nfs"
 *
 * Also indicates if the fstype option was present
 * by setting a flag, if the pointer to the flag
 * is not NULL.
 */
static void
get_opts(char *input, char *opts, char *fstype, bool_t *fstype_opt)
{
	char *p, *pb;
	char buf[MAXOPTSLEN];
	char *placeholder;

	*opts = '\0';
	(void) strcpy(buf, input);
	pb = buf;
	while (p = (char *)strtok_r(pb, ",", &placeholder)) {
		pb = NULL;
		if (strncmp(p, FSTYPE_EQ, 7) == 0) {
			if (fstype_opt != NULL)
				*fstype_opt = TRUE;
			(void) strcpy(fstype, p + 7);
		} else {
			if (*opts)
				(void) strcat(opts, ",");
			(void) strcat(opts, p);
		}
	}
}

/*
 * fstype_opts(struct mapent *me, char *opts, char *defaultopts,
 *				char *mapopts)
 * We need to push global options to the child entry if it is exactly
 * fstype=somefs.
 */
static int
fstype_opts(struct mapent *me, char *opts, char *defaultopts,
    char *mapopts)
{
	char pushentryopts[AUTOFS_MAXOPTSLEN];
	char pushfstype[MAX_FSLEN];

	if (defaultopts && *defaultopts == '-')
		defaultopts++;

	/*
	 * the options to push are the global defaults for the entry,
	 * if they exist, or mapopts, if the global defaults for the
	 * entry does not exist.
	 */
	if (strcmp(defaultopts, opts) == 0) {
		if (*mapopts == '-')
			mapopts++;
		get_opts(mapopts, pushentryopts, pushfstype, NULL);
	} else {
		get_opts(defaultopts, pushentryopts, pushfstype, NULL);
	}

	me->map_mntopts = strdup(pushentryopts);

	if (!me->map_mntopts) {
		syslog(LOG_ERR, "fstype_opts: No memory");
		return (ENOMEM);
	}

	return (PARSE_OK);
}

/*
 * modify_mapents(struct mapent **mapents, char *mapname,
 *			char *mapopts, char *subdir, hiernode *rootnode,
 *			char *key, uint_t isdirect, bool_t mount_access)
 * modifies the intermediate mapentry list into the final one, and passes
 * back a pointer to it. The final list may contain faked mapentries for
 * hiernodes that do not point to a mapentry, or converted mapentries, if
 * hiernodes that point to a mapentry need to be converted from nfs to autofs.
 * mounts. Entries that are not directly 1 level below the subdir are removed.
 * Returns PARSE_OK or PARSE_ERROR
 */
static int
modify_mapents(struct mapent **mapents, char *mapname,
    char *mapopts, char *subdir, hiernode *rootnode,
    char *key, uint_t isdirect, bool_t mount_access)
{
	struct mapent *mp = NULL;
	char w[MAXPATHLEN];

	struct mapent *me;
	int rc = PARSE_OK;
	struct mapent *faked_mapents = NULL;

	/*
	 * correct the mapentry mntlevel from default -1 to level depending on
	 * position in hierarchy, and build any faked mapentries, if required
	 * at one level below the rootnode given by subdir.
	 */
	if ((rc = set_and_fake_mapent_mntlevel(rootnode, subdir, key, mapname,
	    &faked_mapents, isdirect, mapopts, mount_access)) != PARSE_OK)
		return (rc);

	/*
	 * attaches faked mapents to real mapents list. Assumes mapents
	 * is not NULL.
	 */
	me = *mapents;
	while (me->map_next != NULL)
		me = me->map_next;
	me->map_next = faked_mapents;

	/*
	 * get rid of nodes marked at level -1
	 */
	me = *mapents;
	while (me != NULL) {
		if ((me->map_mntlevel ==  -1) || (me->map_err) ||
		    (mount_access == FALSE && me->map_mntlevel == 0)) {
			/*
			 * syslog any errors and free entry
			 */
			if (me->map_err)
				dump_mapent_err(me, key, mapname);

			if (me ==  (*mapents)) {
				/* special case when head has to be freed */
				*mapents = me->map_next;
				if ((*mapents) ==  NULL) {
					/* something wierd happened */
					if (verbose)
						syslog(LOG_ERR,
						"modify_mapents: level error");
					return (PARSE_ERROR);
				}

				/* separate out the node */
				me->map_next = NULL;
				free_mapent(me);
				me = *mapents;
			} else {
				mp->map_next = me->map_next;
				me->map_next = NULL;
				free_mapent(me);
				me = mp->map_next;
			}
			continue;
		}

		/*
		 * convert level 1 mapents that are not already autonodes
		 * to autonodes
		 */
		if (me->map_mntlevel == 1 &&
		    (strcmp(me->map_fstype, MNTTYPE_AUTOFS) != 0) &&
		    (me->map_faked != TRUE)) {
			if ((rc = convert_mapent_to_automount(me, mapname,
			    mapopts)) != PARSE_OK)
				return (rc);
		}
		strcpy(w, (me->map_mntpnt+strlen(subdir)));
		strcpy(me->map_mntpnt, w);
		mp = me;
		me = me->map_next;
	}

	if (trace > 3)
		trace_mapents("modify_mapents:", *mapents);

	return (PARSE_OK);
}

/*
 * set_and_fake_mapent_mntlevel(hiernode *rootnode, char *subdir, char *key,
 *			char *mapname, struct mapent **faked_mapents,
 *			uint_t isdirect, char *mapopts, bool_t mount_access)
 * sets the mapentry mount levels (depths) with respect to the subdir.
 * Assigns a value of 0 to the new root. Finds the level1 directories by
 * calling mark_*_level1_*(). Also cleans off extra /'s in level0 and
 * level1 map_mntpnts. Note that one level below the new root is an existing
 * mapentry if there's a mapentry (nfs mount) corresponding to the root,
 * and the direct subdir set for the root, if there's no mapentry corresponding
 * to the root (we install autodirs). Returns PARSE_OK or error value.
 */
static int
set_and_fake_mapent_mntlevel(hiernode *rootnode, char *subdir, char *key,
    char *mapname, struct mapent **faked_mapents,
    uint_t isdirect, char *mapopts, bool_t mount_access)
{
	char dirname[MAXFILENAMELEN];
	char traversed_path[MAXPATHLEN]; /* used in building fake mapentries */

	char *subdir_child = subdir;
	hiernode *prevnode = rootnode;
	hiernode *currnode = rootnode->subdir;
	int rc = PARSE_OK;
	traversed_path[0] = '\0';

	/*
	 * find and mark the root by tracing down subdir. Use traversed_path
	 * to keep track of how far we go, while guaranteeing that it
	 * contains no '/' at the end. Took some mucking to get that right.
	 */
	if ((rc = get_dir_from_path(dirname, &subdir_child, sizeof (dirname)))
	    != PARSE_OK)
		return (rc);

	if (dirname[0] != '\0') {
		if (strlcat(traversed_path, "/", sizeof (traversed_path)) >=
		    sizeof (traversed_path))
			return (PARSE_ERROR);
		if (strlcat(traversed_path, dirname, sizeof (traversed_path)) >=
		    sizeof (traversed_path))
			return (PARSE_ERROR);
	}

	prevnode = rootnode;
	currnode = rootnode->subdir;
	while (dirname[0] != '\0' && currnode != NULL) {
		if (strcmp(currnode->dirname, dirname) == 0) {

			/* subdir is a child of currnode */
			prevnode = currnode;
			currnode = currnode->subdir;

			if ((rc = get_dir_from_path(dirname, &subdir_child,
			    sizeof (dirname))) != PARSE_OK)
				return (rc);
			if (dirname[0] != '\0') {
				if (strlcat(traversed_path, "/",
				    sizeof (traversed_path)) >=
				    sizeof (traversed_path))
					return (PARSE_ERROR);
				if (strlcat(traversed_path, dirname,
				    sizeof (traversed_path)) >=
				    sizeof (traversed_path))
					return (PARSE_ERROR);
			}
		} else {
			/* try next leveldir */
			prevnode = currnode;
			currnode = currnode->leveldir;
		}
	}

	if (dirname[0] != '\0') {
		if (verbose)
			syslog(LOG_ERR,
			"set_and_fake_mapent_mntlevel: subdir=%s error: map=%s",
			    subdir, mapname);
		return (PARSE_ERROR);
	}

	/*
	 * see if level of root really points to a mapent and if
	 * have access to that filessystem - call appropriate
	 * routine to mark level 1 nodes, and build faked entries
	 */
	if (prevnode->mapent != NULL && mount_access == TRUE) {
		if (trace > 3)
			trace_prt(1, "  node mountpoint %s\t travpath=%s\n",
			    prevnode->mapent->map_mntpnt, traversed_path);

		/*
		 * Copy traversed path map_mntpnt to get rid of any extra
		 * '/' the map entry may contain.
		 */
		if (strlen(prevnode->mapent->map_mntpnt) <
		    strlen(traversed_path)) { /* sanity check */
			if (verbose)
				syslog(LOG_ERR,
				"set_and_fake_mapent_mntlevel: path=%s error",
				    traversed_path);
			return (PARSE_ERROR);
		}
		if (strcmp(prevnode->mapent->map_mntpnt, traversed_path) != 0)
			strcpy(prevnode->mapent->map_mntpnt, traversed_path);

		prevnode->mapent->map_mntlevel = 0; /* root level is 0 */
		if (currnode != NULL) {
			if ((rc = mark_level1_root(currnode,
			    traversed_path)) != PARSE_OK)
				return (rc);
		}
	} else if (currnode != NULL) {
		if (trace > 3)
			trace_prt(1, "  No rootnode, travpath=%s\n",
			    traversed_path);
		if ((rc = mark_and_fake_level1_noroot(currnode,
		    traversed_path, key, mapname, faked_mapents, isdirect,
		    mapopts)) != PARSE_OK)
			return (rc);
	}

	if (trace > 3) {
		trace_prt(1, "\n\tset_and_fake_mapent_mntlevel\n");
		trace_hierarchy(rootnode, 0);
	}

	return (rc);
}


/*
 * mark_level1_root(hiernode *node, char *traversed_path)
 * marks nodes upto one level below the rootnode given by subdir
 * recursively. Called if rootnode points to a mapent.
 * In this routine, a level 1 node is considered to be the 1st existing
 * mapentry below the root node, so there's no faking involved.
 * Returns PARSE_OK or error value
 */
static int
mark_level1_root(hiernode *node, char *traversed_path)
{
	/* ensure we touch all leveldirs */
	while (node) {
		/*
		 * mark node level as 1, if one exists - else walk down
		 * subdirs until we find one.
		 */
		if (node->mapent ==  NULL) {
			char w[MAXPATHLEN];

			if (node->subdir != NULL) {
				sprintf(w, "%s/%s", traversed_path,
				    node->dirname);
				if (mark_level1_root(node->subdir, w)
				    == PARSE_ERROR)
					return (PARSE_ERROR);
			} else {
				if (verbose) {
					syslog(LOG_ERR,
					"mark_level1_root: hierarchy error");
				}
				return (PARSE_ERROR);
			}
		} else {
			char w[MAXPATHLEN];

			sprintf(w, "%s/%s", traversed_path, node->dirname);
			if (trace > 3)
				trace_prt(1, "  node mntpnt %s\t travpath %s\n",
				    node->mapent->map_mntpnt, w);

			/* replace mntpnt with travpath to clean extra '/' */
			if (strlen(node->mapent->map_mntpnt) < strlen(w)) {
				if (verbose) {
					syslog(LOG_ERR,
					"mark_level1_root: path=%s error",
					    traversed_path);
				}
				return (PARSE_ERROR);
			}
			if (strcmp(node->mapent->map_mntpnt, w) != 0)
				strcpy(node->mapent->map_mntpnt, w);
			node->mapent->map_mntlevel = 1;
		}
		node = node->leveldir;
	}
	return (PARSE_OK);
}

/*
 * mark_and_fake_level1_noroot(hiernode *node, char *traversed_path,
 *			char *key,char *mapname, struct mapent **faked_mapents,
 *			uint_t isdirect, char *mapopts)
 * Called if the root of the hierarchy does not point to a mapent. marks nodes
 * upto one physical level below the rootnode given by subdir. checks if
 * there's a real mapentry. If not, it builds a faked one (autonode) at that
 * point. The faked autonode is direct, with the map being the same as the
 * original one from which the call originated. Options are same as that of
 * the map and assigned in automount_opts(). Returns PARSE_OK or error value.
 */
static int
mark_and_fake_level1_noroot(hiernode *node, char *traversed_path,
    char *key, char *mapname, struct mapent **faked_mapents,
    uint_t isdirect, char *mapopts)
{
	struct mapent *me;
	int rc = 0;
	char faked_map_mntpnt[MAXPATHLEN];
	char w1[MAXPATHLEN];
	char w[MAXPATHLEN];

	while (node != NULL) {
		if (node->mapent != NULL) {
			/*
			 * existing mapentry at level 1 - copy travpath to
			 * get rid of extra '/' in mntpnt
			 */
			sprintf(w, "%s/%s", traversed_path, node->dirname);
			if (trace > 3)
				trace_prt(1, "  node mntpnt=%s\t travpath=%s\n",
				    node->mapent->map_mntpnt, w);
			if (strlen(node->mapent->map_mntpnt) < strlen(w)) {
				/* sanity check */
				if (verbose)
					syslog(LOG_ERR,
					"mark_fake_level1_noroot:path=%s error",
					    traversed_path);
				return (PARSE_ERROR);
			}
			if (strcmp(node->mapent->map_mntpnt, w) != 0)
				strcpy(node->mapent->map_mntpnt, w);
			node->mapent->map_mntlevel = 1;
		} else {
			/*
			 * build the faked autonode
			 */
			if ((me = (struct mapent *)malloc(sizeof (*me)))
			    == NULL) {
				syslog(LOG_ERR,
				"mark_and_fake_level1_noroot: out of memory");
				return (ENOMEM);
			}
			(void) memset((char *)me, 0, sizeof (*me));

			if ((me->map_fs = (struct mapfs *)
			    malloc(sizeof (struct mapfs))) == NULL)
				return (ENOMEM);
			(void) memset(me->map_fs, 0, sizeof (struct mapfs));

			if (isdirect) {
				*w1 = '\0';
			} else {
				strcpy(w1, "/");
				strcat(w1, key);
			}
			me->map_root = strdup(w1);

			sprintf(faked_map_mntpnt, "%s/%s", traversed_path,
			    node->dirname);
			me->map_mntpnt = strdup(faked_map_mntpnt);
			me->map_fstype = strdup(MNTTYPE_AUTOFS);
			me->map_mounter = strdup(MNTTYPE_AUTOFS);

			/* set options */
			if ((rc = automount_opts(&me->map_mntopts, mapopts))
			    != PARSE_OK)
				return (rc);
			me->map_fs->mfs_dir = strdup(mapname);
			me->map_mntlevel = 1;
			me->map_modified = FALSE;
			me->map_faked = TRUE;   /* mark as faked */
			if (me->map_root == NULL ||
			    me->map_mntpnt == NULL ||
			    me->map_fstype == NULL ||
			    me->map_mounter == NULL ||
			    me->map_mntopts == NULL ||
			    me->map_fs->mfs_dir == NULL) {
				syslog(LOG_ERR,
				"mark_and_fake_level1_noroot: out of memory");
				free_mapent(*faked_mapents);
				return (ENOMEM);
			}

			if (*faked_mapents == NULL)
				*faked_mapents = me;
			else {			/* attach to the head */
				me->map_next = *faked_mapents;
				*faked_mapents = me;
			}
			node->mapent = me;
		}
		node = node->leveldir;
	}
	return (rc);
}

/*
 * convert_mapent_to_automount(struct mapent *me, char *mapname,
 *				char *mapopts)
 * change the mapentry me to an automount - free fields first and NULL them
 * to avoid freeing again, while freeing the mapentry at a later stage.
 * Could have avoided freeing entries here as we don't really look at them.
 * Give the converted mapent entry the options that came with the map using
 * automount_opts(). Returns PARSE_OK or appropriate error value.
 */
static int
convert_mapent_to_automount(struct mapent *me, char *mapname,
    char *mapopts)
{
	struct mapfs *mfs = me->map_fs;		/* assumes it exists */
	int rc = PARSE_OK;

	/* free relevant entries */
	if (mfs->mfs_host) {
		free(mfs->mfs_host);
		mfs->mfs_host = NULL;
	}
	while (me->map_fs->mfs_next != NULL) {
		mfs = me->map_fs->mfs_next;
		if (mfs->mfs_host)
			free(mfs->mfs_host);
		if (mfs->mfs_dir)
			free(mfs->mfs_dir);
		me->map_fs->mfs_next = mfs->mfs_next;	/* nulls eventually */
		free((void*)mfs);
	}

	/* replace relevant entries */
	if (me->map_fstype)
		free(me->map_fstype);
	if ((me->map_fstype = strdup(MNTTYPE_AUTOFS)) == NULL)
		goto alloc_failed;

	if (me->map_mounter)
		free(me->map_mounter);
	if ((me->map_mounter = strdup(me->map_fstype)) == NULL)
		goto alloc_failed;

	if (me->map_fs->mfs_dir)
		free(me->map_fs->mfs_dir);
	if ((me->map_fs->mfs_dir = strdup(mapname)) == NULL)
		goto alloc_failed;

	/* set options */
	if (me->map_mntopts)
		free(me->map_mntopts);
	if ((rc = automount_opts(&me->map_mntopts, mapopts)) != PARSE_OK)
		return (rc);

	/* mucked with this entry, set the map_modified field to TRUE */
	me->map_modified = TRUE;

	return (rc);

alloc_failed:
	syslog(LOG_ERR,
	    "convert_mapent_to_automount: Memory allocation failed");
	return (ENOMEM);
}

/*
 * automount_opts(char **map_mntopts, char *mapopts)
 * modifies automount opts - gets rid of all "indirect" and "direct" strings
 * if they exist, and then adds a direct string to force a direct automount.
 * Rest of the mapopts stay intact. Returns PARSE_OK or appropriate error.
 */
static int
automount_opts(char **map_mntopts, char *mapopts)
{
	char *opts;
	char *opt;
	int len;
	char *placeholder;
	char buf[AUTOFS_MAXOPTSLEN];

	char *addopt = "direct";

	len = strlen(mapopts)+ strlen(addopt)+2;	/* +2 for ",", '\0' */
	if (len > AUTOFS_MAXOPTSLEN) {
		syslog(LOG_ERR,
		"option string %s too long (max=%d)", mapopts,
		    AUTOFS_MAXOPTSLEN-8);
		return (PARSE_ERROR);
	}

	if (((*map_mntopts) = ((char *)malloc(len))) == NULL) {
		syslog(LOG_ERR,	"automount_opts: Memory allocation failed");
		return (ENOMEM);
	}
	memset(*map_mntopts, 0, len);

	strcpy(buf, mapopts);
	opts = buf;
	while ((opt = strtok_r(opts, ",", &placeholder)) != NULL) {
		opts = NULL;

		/* remove trailing and leading spaces */
		while (isspace(*opt))
			opt++;
		len = strlen(opt)-1;
		while (isspace(opt[len]))
			opt[len--] = '\0';

		/*
		 * if direct or indirect found, get rid of it, else put it
		 * back
		 */
		if ((strcmp(opt, "indirect") == 0) ||
		    (strcmp(opt, "direct") == 0))
			continue;
		if (*map_mntopts[0] != '\0')
			strcat(*map_mntopts, ",");
		strcat(*map_mntopts, opt);
	}

	/* add the direct string at the end */
	if (*map_mntopts[0] != '\0')
		strcat(*map_mntopts,	",");
	strcat(*map_mntopts, addopt);

	return (PARSE_OK);
}

/*
 * parse_fsinfo(char *mapname, struct mapent *mapents)
 * parses the filesystem information stored in me->map_fsw and me->map_fswq
 * and calls appropriate filesystem parser.
 * Returns PARSE_OK or an appropriate error value.
 */
static int
parse_fsinfo(char *mapname, struct mapent *mapents)
{
	struct mapent *me = mapents;
	char *bufp;
	char *bufq;
	int wordsz = MAXPATHLEN;
	int err = 0;

	while (me != NULL) {
		bufp = "";
		bufq = "";
		if (strcmp(me->map_fstype, MNTTYPE_NFS) == 0) {
			err = parse_nfs(mapname, me, me->map_fsw,
			    me->map_fswq, &bufp, &bufq, wordsz);
		} else {
			err = parse_special(me, me->map_fsw, me->map_fswq,
			    &bufp, &bufq, wordsz);
		}

		if (err != PARSE_OK || *me->map_fsw != '\0' ||
		    *me->map_fswq != '\0') {
			/* sanity check */
			if (verbose)
				syslog(LOG_ERR,
				"parse_fsinfo: mount location error %s",
				    me->map_fsw);
			return (PARSE_ERROR);
		}

		me = me->map_next;
	}

	if (trace > 3) {
		trace_mapents("parse_fsinfo:", mapents);
	}

	return (PARSE_OK);
}

/*
 * This function parses the map entry for a nfs type file system
 * The input is the string lp (and lq) which can be one of the
 * following forms:
 * a) host[(penalty)][,host[(penalty)]]... :/directory
 * b) host[(penalty)]:/directory[ host[(penalty)]:/directory]...
 * This routine constructs a mapfs link-list for each of
 * the hosts and the corresponding file system. The list
 * is then attatched to the mapent struct passed in.
 */
int
parse_nfs(char *mapname, struct mapent *me, char *fsw, char *fswq,
    char **lp, char **lq, int wsize)
{
	struct mapfs *mfs, **mfsp;
	char *wlp, *wlq;
	char *hl, hostlist[1024], *hlq, hostlistq[1024];
	char hostname_and_penalty[MXHOSTNAMELEN+5];
	char *hn, *hnq, hostname[MXHOSTNAMELEN+1];
	char dirname[MAXPATHLEN+1], subdir[MAXPATHLEN+1];
	char qbuff[MAXPATHLEN+1], qbuff1[MAXPATHLEN+1];
	char pbuff[10], pbuffq[10];
	int penalty;
	char w[MAXPATHLEN];
	char wq[MAXPATHLEN];
	int host_cnt;

	mfsp = &me->map_fs;
	*mfsp = NULL;

	/*
	 * there may be more than one entry in the map list. Get the
	 * first one. Use temps to handle the word information and
	 * copy back into fsw and fswq fields when done.
	 */
	*lp = fsw;
	*lq = fswq;
	if (getword(w, wq, lp, lq, ' ', wsize) == -1)
		return (PARSE_ERROR);
	while (*w && *w != '/') {
		bool_t maybe_url;

		maybe_url = TRUE;

		wlp = w; wlq = wq;
		if (getword(hostlist, hostlistq, &wlp, &wlq, ':',
		    sizeof (hostlist)) == -1)
			return (PARSE_ERROR);
		if (!*hostlist)
			goto bad_entry;

		if (strcmp(hostlist, "nfs") != 0)
			maybe_url = FALSE;

		if (getword(dirname, qbuff, &wlp, &wlq, ':',
		    sizeof (dirname)) == -1)
			return (PARSE_ERROR);
		if (*dirname == '\0')
			goto bad_entry;

		if (maybe_url == TRUE && strncmp(dirname, "//", 2) != 0)
			maybe_url = FALSE;

		/*
		 * See the next block comment ("Once upon a time ...") to
		 * understand this. It turns the deprecated concept
		 * of "subdir mounts" produced some useful code for handling
		 * the possibility of a ":port#" in the URL.
		 */
		if (maybe_url == FALSE)
			*subdir = '/';
		else
			*subdir = ':';

		*qbuff = ' ';

		/*
		 * Once upon time, before autofs, there was support for
		 * "subdir mounts". The idea was to "economize" the
		 * number of mounts, so if you had a number of entries
		 * all referring to a common subdirectory, e.g.
		 *
		 *	carol    seasons:/export/home11/carol
		 *	ted	 seasons:/export/home11/ted
		 *	alice	 seasons:/export/home11/alice
		 *
		 * then you could tell the automounter to mount a
		 * common mountpoint which was delimited by the second
		 * colon:
		 *
		 *	carol    seasons:/export/home11:carol
		 *	ted	 seasons:/export/home11:ted
		 *	alice	 seasons:/export/home11:alice
		 *
		 * The automounter would mount seasons:/export/home11
		 * then for any other map entry that referenced the same
		 * directory it would build a symbolic link that
		 * appended the remainder of the path after the second
		 * colon, i.e.  once the common subdir was mounted, then
		 * other directories could be accessed just by link
		 * building - no further mounts required.
		 *
		 * In theory the "mount saving" idea sounded good. In
		 * practice the saving didn't amount to much and the
		 * symbolic links confused people because the common
		 * mountpoint had to have a pseudonym.
		 *
		 * To remain backward compatible with the existing
		 * maps, we interpret a second colon as a slash.
		 */
		if (getword(subdir+1, qbuff+1, &wlp, &wlq, ':',
		    sizeof (subdir)) == -1)
			return (PARSE_ERROR);

		if (*(subdir+1))
			(void) strcat(dirname, subdir);

		hl = hostlist; hlq = hostlistq;

		host_cnt = 0;
		for (;;) {

			if (getword(hostname_and_penalty, qbuff, &hl, &hlq, ',',
			    sizeof (hostname_and_penalty)) == -1)
				return (PARSE_ERROR);
			if (!*hostname_and_penalty)
				break;

			host_cnt++;
			if (host_cnt > 1)
				maybe_url = FALSE;

			hn = hostname_and_penalty;
			hnq = qbuff;
			if (getword(hostname, qbuff1, &hn, &hnq, '(',
			    sizeof (hostname)) == -1)
				return (PARSE_ERROR);
			if (hostname[0] == '\0')
				goto bad_entry;

			if (strcmp(hostname, hostname_and_penalty) == 0) {
				penalty = 0;
			} else {
				maybe_url = FALSE;
				hn++; hnq++;
				if (getword(pbuff, pbuffq, &hn, &hnq, ')',
				    sizeof (pbuff)) == -1)
					return (PARSE_ERROR);
				if (!*pbuff)
					penalty = 0;
				else
					penalty = atoi(pbuff);
			}
			mfs = (struct mapfs *)malloc(sizeof (*mfs));
			if (mfs == NULL) {
				syslog(LOG_ERR,
				"parse_nfs: Memory allocation failed");
				return (PARSE_ERROR);
			}
			(void) memset(mfs, 0, sizeof (*mfs));
			*mfsp = mfs;
			mfsp = &mfs->mfs_next;

			if (maybe_url == TRUE) {
				char *host;
				char *path;
				char *sport;

				host = dirname+2;
				path = strchr(host, '/');
				if (path == NULL) {
					syslog(LOG_ERR, "parse_nfs: illegal "
					    "nfs url syntax: %s", host);

					return (PARSE_ERROR);
				}
				*path = '\0';
				sport = strchr(host, ':');

				if (sport != NULL && sport < path) {
					*sport = '\0';
					mfs->mfs_port = atoi(sport+1);

					if (mfs->mfs_port > USHRT_MAX) {
						syslog(LOG_ERR,
						    "parse_nfs: invalid "
						    "port number (%d) in "
						    "NFS URL",
						    mfs->mfs_port);

						return (PARSE_ERROR);
					}

				}

				path++;
				if (*path == '\0')
					path = ".";

				mfs->mfs_flags |= MFS_URL;

				mfs->mfs_host = strdup(host);
				mfs->mfs_dir = strdup(path);
			} else {
				mfs->mfs_host = strdup(hostname);
				mfs->mfs_dir = strdup(dirname);
			}

			mfs->mfs_penalty = penalty;
			if (mfs->mfs_host == NULL || mfs->mfs_dir == NULL) {
				syslog(LOG_ERR,
				    "parse_nfs: Memory allocation failed");
				return (PARSE_ERROR);
			}
		}
		/*
		 * We check host_cnt to make sure we haven't parsed an entry
		 * with no host information.
		 */
		if (host_cnt == 0) {
			syslog(LOG_ERR,
			    "parse_nfs: invalid host specified - bad entry "
			    "in map %s \"%s\"",
			    mapname, w);
			return (PARSE_ERROR);
		}
		if (getword(w, wq, lp, lq, ' ', wsize) == -1)
			return (PARSE_ERROR);
	}

	strcpy(fsw, w);
	strcpy(fswq, wq);

	return (PARSE_OK);

bad_entry:
	syslog(LOG_ERR, "parse_nfs: bad entry in map %s \"%s\"", mapname, w);
	return (PARSE_ERROR);
}

static int
parse_special(struct mapent *me, char *w, char *wq, char **lp, char **lq,
    int wsize)
{
	char devname[MAXPATHLEN + 1], qbuf[MAXPATHLEN + 1];
	char *wlp, *wlq;
	struct mapfs *mfs;

	wlp = w;
	wlq = wq;
	if (getword(devname, qbuf, &wlp, &wlq, ' ', sizeof (devname)) == -1)
		return (PARSE_ERROR);
	if (devname[0] == '\0')
		return (PARSE_ERROR);

	mfs = malloc(sizeof (struct mapfs));
	if (mfs == NULL)
		return (PARSE_ERROR);
	(void) memset(mfs, 0, sizeof (*mfs));

	/*
	 * A device name that begins with a slash could
	 * be confused with a mountpoint path, hence use
	 * a colon to escape a device string that begins
	 * with a slash, e.g.
	 *
	 *	foo  -ro  /bar  foo:/bar
	 * and
	 *	foo  -ro  /dev/sr0
	 *
	 * would confuse the parser.  The second instance
	 * must use a colon:
	 *
	 *	foo  -ro  :/dev/sr0
	 */
	mfs->mfs_dir = strdup(&devname[devname[0] == ':']);
	if (mfs->mfs_dir == NULL)
		return (PARSE_ERROR);
	me->map_fs = mfs;
	if (getword(w, wq, lp, lq, ' ', wsize) == -1)
		return (PARSE_ERROR);
	return (0);
}

/*
 * get_dir_from_path(char *dir, char **path, int dirsz)
 * gets the directory name dir from path for max string of length dirsz.
 * A modification of the getword routine. Assumes the delimiter is '/'
 * and that excess /'s are redundant.
 * Returns PARSE_OK or PARSE_ERROR
 */
static int
get_dir_from_path(char *dir, char **path, int dirsz)
{
	char *tmp = dir;
	int count = dirsz;

	if (dirsz <= 0) {
		if (verbose)
			syslog(LOG_ERR,
			"get_dir_from_path: invalid directory size %d", dirsz);
		return (PARSE_ERROR);
	}

	/* get rid of leading /'s in path */
	while (**path == '/')
		(*path)++;

	/* now at a word or at the end of path */
	while ((**path) && ((**path) != '/')) {
		if (--count <= 0) {
			*tmp = '\0';
			syslog(LOG_ERR,
			"get_dir_from_path: max pathlength exceeded %d", dirsz);
			return (PARSE_ERROR);
		}
		*dir++ = *(*path)++;
	}

	*dir = '\0';

	/* get rid of trailing /'s in path */
	while (**path == '/')
		(*path)++;

	return (PARSE_OK);
}

/*
 * alloc_hiernode(hiernode **newnode, char *dirname)
 * allocates a new hiernode corresponding to a new directory entry
 * in the hierarchical structure, and passes a pointer to it back
 * to the calling program.
 * Returns PARSE_OK or appropriate error value.
 */
static int
alloc_hiernode(hiernode **newnode, char *dirname)
{
	if ((*newnode = (hiernode *)malloc(sizeof (hiernode))) == NULL) {
		syslog(LOG_ERR,	"alloc_hiernode: Memory allocation failed");
		return (ENOMEM);
	}

	memset(((char *)*newnode), 0, sizeof (hiernode));
	strcpy(((*newnode)->dirname), dirname);
	return (PARSE_OK);
}

/*
 * free_hiernode(hiernode *node)
 * frees the allocated hiernode given the head of the structure
 * recursively calls itself until it frees entire structure.
 * Returns nothing.
 */
static void
free_hiernode(hiernode *node)
{
	hiernode *currnode = node;
	hiernode *prevnode = NULL;

	while (currnode != NULL) {
		if (currnode->subdir != NULL)
			free_hiernode(currnode->subdir);
		prevnode = currnode;
		currnode = currnode->leveldir;
		free((void*)prevnode);
	}
}

/*
 * free_mapent(struct mapent *)
 * free the mapentry and its fields
 */
void
free_mapent(struct mapent *me)
{
	struct mapfs *mfs;
	struct mapent *m;

	while (me) {
		while (me->map_fs) {
			mfs = me->map_fs;
			if (mfs->mfs_host)
				free(mfs->mfs_host);
			if (mfs->mfs_dir)
				free(mfs->mfs_dir);
			if (mfs->mfs_args)
				free(mfs->mfs_args);
			if (mfs->mfs_nconf)
				freenetconfigent(mfs->mfs_nconf);
			me->map_fs = mfs->mfs_next;
			free(mfs);
		}

		if (me->map_root)
			free(me->map_root);
		if (me->map_mntpnt)
			free(me->map_mntpnt);
		if (me->map_mntopts)
			free(me->map_mntopts);
		if (me->map_fstype)
			free(me->map_fstype);
		if (me->map_mounter)
			free(me->map_mounter);
		if (me->map_fsw)
			free(me->map_fsw);
		if (me->map_fswq)
			free(me->map_fswq);

		m = me;
		me = me->map_next;
		free(m);
	}
}

/*
 * trace_mapents(struct mapent *mapents)
 * traces through the mapentry structure and prints it element by element
 * returns nothing
 */
static void
trace_mapents(char *s, struct mapent *mapents)
{
	struct mapfs  *mfs;
	struct mapent *me;

	trace_prt(1, "\n\t%s\n", s);
	for (me = mapents; me; me = me->map_next) {
		trace_prt(1, "  (%s,%s)\t %s%s -%s\n",
		    me->map_fstype ? me->map_fstype : "",
		    me->map_mounter ? me->map_mounter : "",
		    me->map_root  ? me->map_root : "",
		    me->map_mntpnt ? me->map_mntpnt : "",
		    me->map_mntopts ? me->map_mntopts : "");
		for (mfs = me->map_fs; mfs; mfs = mfs->mfs_next)
			trace_prt(0, "\t\t%s:%s\n",
			    mfs->mfs_host ? mfs->mfs_host: "",
			    mfs->mfs_dir ? mfs->mfs_dir : "");

		trace_prt(1, "\tme->map_fsw=%s\n",
		    me->map_fsw ? me->map_fsw:"",
		    me->map_fswq ? me->map_fsw:"");
		trace_prt(1, "\t mntlevel=%d\t%s\t%s err=%d\n",
		    me->map_mntlevel,
		    me->map_modified ? "modify=TRUE":"modify=FALSE",
		    me->map_faked ? "faked=TRUE":"faked=FALSE",
		    me->map_err);
	}
}

/*
 * trace_hierarchy(hiernode *node)
 * traces the allocated hiernode given the head of the structure
 * recursively calls itself until it traces entire structure.
 * the first call made at the root is made with a zero level.
 * nodelevel is simply used to print tab and make the tracing clean.
 * Returns nothing.
 */
static void
trace_hierarchy(hiernode *node, int nodelevel)
{
	hiernode *currnode = node;
	int i;

	while (currnode != NULL) {
		if (currnode->subdir != NULL) {
			for (i = 0; i < nodelevel; i++)
				trace_prt(0, "\t");
			trace_prt(0, "\t(%s, ", currnode->dirname);
			if (currnode->mapent) {
				trace_prt(0, "%d, %s)\n",
				    currnode->mapent->map_mntlevel,
				    currnode->mapent->map_mntopts ?
				    currnode->mapent->map_mntopts:"");
			}
			else
				trace_prt(0, " ,)\n");
			nodelevel++;
			trace_hierarchy(currnode->subdir, nodelevel);
		} else {
			for (i = 0; i < nodelevel; i++)
				trace_prt(0, "\t");
			trace_prt(0, "\t(%s, ", currnode->dirname);
			if (currnode->mapent) {
				trace_prt(0, "%d, %s)\n",
				    currnode->mapent->map_mntlevel,
				    currnode->mapent->map_mntopts ?
				    currnode->mapent->map_mntopts:"");
			}
			else
				trace_prt(0, ", )\n");
		}
		currnode = currnode->leveldir;
	}
}

struct mapent *
do_mapent_hosts(char *mapopts, char *host, uint_t isdirect)
{
	CLIENT *cl;
	struct mapent *me, *ms, *mp;
	struct mapfs *mfs;
	struct exportnode *ex = NULL;
	struct exportnode *exlist, *texlist, **texp, *exnext;
	struct timeval timeout;
	enum clnt_stat clnt_stat;
	char name[MAXPATHLEN];
	char entryopts[MAXOPTSLEN];
	char fstype[32], mounter[32];
	int exlen, duplicate;
	struct mnttab mb;	/* needed for hasmntopt() to get nfs version */
	rpcvers_t nfsvers;	/* version in map options, 0 if not there */
	rpcvers_t vers, versmin; /* used to negotiate nfs vers in pingnfs() */
	int retries, delay;
	int foundvers;

	if (trace > 1)
		trace_prt(1, "  do_mapent_hosts: host %s\n", host);

	/* check for special case: host is me */

	if (self_check(host)) {
		ms = (struct mapent *)malloc(sizeof (*ms));
		if (ms == NULL)
			goto alloc_failed;
		(void) memset((char *)ms, 0, sizeof (*ms));
		(void) strcpy(fstype, MNTTYPE_NFS);
		get_opts(mapopts, entryopts, fstype, NULL);
		ms->map_mntopts = strdup(entryopts);
		if (ms->map_mntopts == NULL)
			goto alloc_failed;
		ms->map_mounter = strdup(fstype);
		if (ms->map_mounter == NULL)
			goto alloc_failed;
		ms->map_fstype = strdup(MNTTYPE_NFS);
		if (ms->map_fstype == NULL)
			goto alloc_failed;

		if (isdirect)
			name[0] = '\0';
		else {
			(void) strcpy(name, "/");
			(void) strcat(name, host);
		}
		ms->map_root = strdup(name);
		if (ms->map_root == NULL)
			goto alloc_failed;
		ms->map_mntpnt = strdup("");
		if (ms->map_mntpnt == NULL)
			goto alloc_failed;
		mfs = (struct mapfs *)malloc(sizeof (*mfs));
		if (mfs == NULL)
			goto alloc_failed;
		(void) memset((char *)mfs, 0, sizeof (*mfs));
		ms->map_fs = mfs;
		mfs->mfs_host = strdup(host);
		if (mfs->mfs_host == NULL)
			goto alloc_failed;
		mfs->mfs_dir  = strdup("/");
		if (mfs->mfs_dir == NULL)
			goto alloc_failed;

		/* initialize mntlevel and modify */
		ms->map_mntlevel = -1;
		ms->map_modified = FALSE;
		ms->map_faked = FALSE;

		if (trace > 1)
			trace_prt(1,
			"  do_mapent_hosts: self-host %s OK\n", host);

		return (ms);
	}

	/*
	 * Call pingnfs. Note that we can't have replicated hosts in /net.
	 * XXX - we would like to avoid duplicating the across the wire calls
	 * made here in nfsmount(). The pingnfs cache should help avoid it.
	 */
	mb.mnt_mntopts = mapopts;
	foundvers = nopt(&mb, MNTOPT_VERS, (int *)&nfsvers);
	if (!foundvers)
		nfsvers = 0;
	if (set_versrange(nfsvers, &vers, &versmin) != 0) {
		syslog(LOG_ERR, "Incorrect NFS version specified for %s", host);
		return (NULL);
	}
	if (pingnfs(host, get_retry(mapopts) + 1, &vers, versmin, 0, FALSE,
	    NULL, NULL) != RPC_SUCCESS)
		return (NULL);

	retries = get_retry(mapopts);
	delay = INITDELAY;
retry:
	/* get export list of host */
	cl = clnt_create(host, MOUNTPROG, MOUNTVERS, "circuit_v");
	if (cl == NULL) {
		cl = clnt_create(host, MOUNTPROG, MOUNTVERS, "datagram_v");
		if (cl == NULL) {
			syslog(LOG_ERR,
			"do_mapent_hosts: %s %s", host, clnt_spcreateerror(""));
			return (NULL);
		}

	}
#ifdef MALLOC_DEBUG
	add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
	add_alloc("AUTH_HANDLE", cl->cl_auth, 0, __FILE__, __LINE__);
#endif

	timeout.tv_usec = 0;
	timeout.tv_sec  = 25;
	if (clnt_stat = clnt_call(cl, MOUNTPROC_EXPORT, xdr_void, 0,
	    xdr_exports, (caddr_t)&ex, timeout)) {

		if (retries-- > 0) {
			clnt_destroy(cl);
			DELAY(delay);
			goto retry;
		}

		syslog(LOG_ERR,
		    "do_mapent_hosts: %s: export list: %s",
		    host, clnt_sperrno(clnt_stat));
#ifdef MALLOC_DEBUG
		drop_alloc("CLNT_HANDLE", cl, __FILE__, __LINE__);
		drop_alloc("AUTH_HANDLE", cl->cl_auth, __FILE__, __LINE__);
#endif
		clnt_destroy(cl);
		return ((struct mapent *)NULL);
	}

#ifdef MALLOC_DEBUG
	drop_alloc("CLNT_HANDLE", cl, __FILE__, __LINE__);
	drop_alloc("AUTH_HANDLE", cl->cl_auth, __FILE__, __LINE__);
#endif
	clnt_destroy(cl);

	if (ex == NULL) {
		if (trace > 1)
			trace_prt(1,
			    gettext("  getmapent_hosts: null export list\n"));
		return ((struct mapent *)NULL);
	}

	/* now sort by length of names - to get mount order right */
	exlist = ex;
	texlist = NULL;
	for (; ex; ex = exnext) {
		exnext = ex->ex_next;
		exlen = strlen(ex->ex_dir);
		duplicate = 0;
		for (texp = &texlist; *texp; texp = &((*texp)->ex_next)) {
			if (exlen < (int)strlen((*texp)->ex_dir))
				break;
			duplicate = (strcmp(ex->ex_dir, (*texp)->ex_dir) == 0);
			if (duplicate) {
				/* disregard duplicate entry */
				freeex_ent(ex);
				break;
			}
		}
		if (!duplicate) {
			ex->ex_next = *texp;
			*texp = ex;
		}
	}
	exlist = texlist;

	(void) strcpy(fstype, MNTTYPE_NFS);
	get_opts(mapopts, entryopts, fstype, NULL);
	(void) strcpy(mounter, fstype);

	/* Now create a mapent from the export list */
	ms = NULL;
	me = NULL;

	for (ex = exlist; ex; ex = ex->ex_next) {
		mp = me;
		me = (struct mapent *)malloc(sizeof (*me));
		if (me == NULL)
			goto alloc_failed;
		(void) memset((char *)me, 0, sizeof (*me));

		if (ms == NULL)
			ms = me;
		else
			mp->map_next = me;

		if (isdirect)
			name[0] = '\0';
		else {
			(void) strcpy(name, "/");
			(void) strcat(name, host);
		}
		me->map_root = strdup(name);
		if (me->map_root == NULL)
			goto alloc_failed;

		*name = '\0';
		if (strcmp(ex->ex_dir, "/") != 0) {
			if (*(ex->ex_dir) != '/')
				(void) strcpy(name, "/");
			(void) strcat(name, ex->ex_dir);
		}
		me->map_mntpnt = strdup(name);
		if (me->map_mntpnt == NULL)
			goto alloc_failed;

		me->map_fstype = strdup(fstype);
		if (me->map_fstype == NULL)
			goto alloc_failed;
		me->map_mounter = strdup(mounter);
		if (me->map_mounter == NULL)
			goto alloc_failed;
		me->map_mntopts = strdup(entryopts);
		if (me->map_mntopts == NULL)
			goto alloc_failed;

		mfs = (struct mapfs *)malloc(sizeof (*mfs));
		if (mfs == NULL)
			goto alloc_failed;
		(void) memset((char *)mfs, 0, sizeof (*mfs));
		me->map_fs = mfs;
		mfs->mfs_host = strdup(host);
		if (mfs->mfs_host == NULL)
			goto alloc_failed;
		mfs->mfs_dir = strdup(ex->ex_dir);
		if (mfs->mfs_dir == NULL)
			goto alloc_failed;

		/* initialize mntlevel and modify values */
		me->map_mntlevel = -1;
		me->map_modified = FALSE;
		me->map_faked = FALSE;
	}
	freeex(exlist);

	if (trace > 1)
		trace_prt(1, "  do_mapent_hosts: host %s OK\n", host);

	return (ms);

alloc_failed:
	syslog(LOG_ERR, "do_mapent_hosts: Memory allocation failed");
	free_mapent(ms);
	freeex(exlist);
	return (NULL);
}


static void
freeex_ent(struct exportnode *ex)
{
	struct groupnode *groups, *tmpgroups;

	free(ex->ex_dir);
	groups = ex->ex_groups;
	while (groups) {
		free(groups->gr_name);
		tmpgroups = groups->gr_next;
		free((char *)groups);
		groups = tmpgroups;
	}
	free(ex);
}

static void
freeex(struct exportnode *ex)
{
	struct exportnode *tmpex;

	while (ex) {
		tmpex = ex->ex_next;
		freeex_ent(ex);
		ex = tmpex;
	}
}

static const char uatfs_err[] = "submount under fstype=autofs not supported";
/*
 * dump_mapent_err(struct mapent *me, char *key, char *mapname)
 * syslog appropriate error in mapentries.
 */
static void dump_mapent_err(struct mapent *me, char *key, char *mapname)
{
	switch (me->map_err) {
	case MAPENT_NOERR:
		if (verbose)
			syslog(LOG_ERR,
			"map=%s key=%s mntpnt=%s: no error");
		break;
	case MAPENT_UATFS:
		syslog(LOG_ERR,
		"mountpoint %s in map %s key %s not mounted: %s",
		    me->map_mntpnt, mapname, key, uatfs_err);
		break;
	default:
		if (verbose)
			syslog(LOG_ERR,
			"map=%s key=%s mntpnt=%s: unknown mapentry error");
	}
}
/*
 * 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.
 */

/*
 *	autod_readdir.c
 */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/param.h>
#include <errno.h>
#include <pwd.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include "automount.h"

static void build_dir_entry_list(struct autofs_rddir_cache *rdcp,
				struct dir_entry *list);
static int autofs_rddir_cache_enter(char *map, ulong_t bucket_size,
				struct autofs_rddir_cache **rdcpp);
int autofs_rddir_cache_lookup(char *map, struct autofs_rddir_cache **rdcpp);
static int autofs_rddir_cache_delete(struct autofs_rddir_cache *rdcp);
static int create_dirents(struct autofs_rddir_cache *rdcp, ulong_t offset,
				autofs_rddirres *res);
struct dir_entry *rddir_entry_lookup(char *name, struct dir_entry *list);
static void free_offset_tbl(struct off_tbl *head);
static void free_dir_list(struct dir_entry *head);

#define	OFFSET_BUCKET_SIZE	100

rwlock_t autofs_rddir_cache_lock;		/* readdir cache lock */
struct autofs_rddir_cache *rddir_head;		/* readdir cache head */

int
do_readdir(autofs_rddirargs *rda, autofs_rddirres *rd)
{
	struct dir_entry *list = NULL, *l;
	struct autofs_rddir_cache *rdcp = NULL;
	int error;
	int cache_time = RDDIR_CACHE_TIME;

	if (automountd_nobrowse) {
		/*
		 * Browsability was disabled return an empty list.
		 */
		rd->rd_status = AUTOFS_OK;
		rd->rd_rddir.rddir_size = 0;
		rd->rd_rddir.rddir_eof = 1;
		rd->rd_rddir.rddir_entries = NULL;

		return (0);
	}

	rw_rdlock(&autofs_rddir_cache_lock);
	error = autofs_rddir_cache_lookup(rda->rda_map, &rdcp);
	if (error) {
		rw_unlock(&autofs_rddir_cache_lock);
		rw_wrlock(&autofs_rddir_cache_lock);
		error = autofs_rddir_cache_lookup(rda->rda_map, &rdcp);
		if (error) {
			if (trace > 2)
				trace_prt(1,
				"map %s not found, adding...\n", rda->rda_map);
			/*
			 * entry doesn't exist, add it.
			 */
			error = autofs_rddir_cache_enter(rda->rda_map,
					OFFSET_BUCKET_SIZE, &rdcp);
		}
	}
	rw_unlock(&autofs_rddir_cache_lock);

	if (error)
		return (error);

	assert(rdcp != NULL);
	assert(rdcp->in_use);

	if (!rdcp->full) {
		rw_wrlock(&rdcp->rwlock);
		if (!rdcp->full) {
			/*
			 * cache entry hasn't been filled up, do it now.
			 */
			char *stack[STACKSIZ];
			char **stkptr;

			/*
			 * Initialize the stack of open files
			 * for this thread
			 */
			stack_op(INIT, NULL, stack, &stkptr);
			(void) getmapkeys(rda->rda_map, &list, &error,
			    &cache_time, stack, &stkptr, rda->uid);
			if (!error)
				build_dir_entry_list(rdcp, list);
			else if (list) {
				free_dir_list(list);
				list = NULL;
			}
		}
	} else
		rw_rdlock(&rdcp->rwlock);

	rd->rd_bufsize = rda->rda_count;
	if (!error) {
		error = create_dirents(rdcp, rda->rda_offset, rd);
		if (error) {
			if (rdcp->offtp) {
				free_offset_tbl(rdcp->offtp);
				rdcp->offtp = NULL;
			}
			if (rdcp->entp) {
				free_dir_list(rdcp->entp);
				rdcp->entp = NULL;
			}
			rdcp->full = 0;
			list = NULL;
		}
	}

	if (trace > 2) {
		/*
		 * print this list only once
		 */
		for (l = list; l != NULL; l = l->next)
			trace_prt(0, "%s\n", l->name);
		trace_prt(0, "\n");
	}

	if (!error) {
		rd->rd_status = AUTOFS_OK;
		if (cache_time) {
			/*
			 * keep list of entries for up to
			 * 'cache_time' seconds
			 */
			rdcp->ttl = time((time_t *)NULL) + cache_time;
		} else {
			/*
			 * the underlying name service indicated not
			 * to cache contents.
			 */
			if (rdcp->offtp) {
				free_offset_tbl(rdcp->offtp);
				rdcp->offtp = NULL;
			}
			if (rdcp->entp) {
				free_dir_list(rdcp->entp);
				rdcp->entp = NULL;
			}
			rdcp->full = 0;
		}
	} else {
		/*
		 * return an empty list
		 */
		rd->rd_rddir.rddir_size = 0;
		rd->rd_rddir.rddir_eof = 1;
		rd->rd_rddir.rddir_entries = NULL;

		/*
		 * Invalidate cache and set error
		 */
		switch (error) {
		case ENOENT:
			rd->rd_status = AUTOFS_NOENT;
			break;
		case ENOMEM:
			rd->rd_status = AUTOFS_NOMEM;
			break;
		default:
			rd->rd_status = AUTOFS_ECOMM;
		}
	}
	rw_unlock(&rdcp->rwlock);

	mutex_lock(&rdcp->lock);
	rdcp->in_use--;
	mutex_unlock(&rdcp->lock);

	assert(rdcp->in_use >= 0);

	return (error);
}

#define	roundtoint(x)	(((x) + sizeof (int) - 1) & ~(sizeof (int) - 1))
#define	DIRENT64_RECLEN(namelen)	\
	(((int)(((dirent64_t *)0)->d_name) + 1 + (namelen) + 7) & ~ 7)

static int
create_dirents(
	struct autofs_rddir_cache *rdcp,
	ulong_t offset,
	autofs_rddirres *res)
{
	uint_t total_bytes_wanted;
	int bufsize;
	ushort_t this_reclen;
	int outcount = 0;
	int namelen;
	struct dir_entry *list = NULL, *l, *nl;
	struct dirent64 *dp;
	char *outbuf;
	struct off_tbl *offtp, *next = NULL;
	int this_bucket = 0;
	int error = 0;
	int x = 0, y = 0;

	assert(RW_LOCK_HELD(&rdcp->rwlock));
	for (offtp = rdcp->offtp; offtp != NULL; offtp = next) {
		x++;
		next = offtp->next;
		this_bucket = (next == NULL);
		if (!this_bucket)
			this_bucket = (offset < next->offset);
		if (this_bucket) {
			/*
			 * has to be in this bucket
			 */
			assert(offset >= offtp->offset);
			list = offtp->first;
			break;
		}
		/*
		 * loop to look in next bucket
		 */
	}

	for (l = list; l != NULL && l->offset < offset; l = l->next)
		y++;

	if (l == NULL) {
		/*
		 * reached end of directory
		 */
		error = 0;
		goto empty;
	}

	if (trace > 2)
		trace_prt(1, "%s: offset searches (%d, %d)\n", rdcp->map, x, y);

	total_bytes_wanted = res->rd_bufsize;
	bufsize = total_bytes_wanted + sizeof (struct dirent64);
	outbuf = malloc(bufsize);
	if (outbuf == NULL) {
		syslog(LOG_ERR, "memory allocation error\n");
		error = ENOMEM;
		goto empty;
	}
	memset(outbuf, 0, bufsize);
	/* LINTED pointer alignment */
	dp = (struct dirent64 *)outbuf;

	while (l) {
		nl = l->next;
		namelen = strlen(l->name);
		this_reclen = DIRENT64_RECLEN(namelen);
		if (outcount + this_reclen > total_bytes_wanted) {
			break;
		}
		dp->d_ino = (ino64_t)l->nodeid;
		if (nl) {
			/*
			 * get the next elements offset
			 */
			dp->d_off = (off64_t)nl->offset;
		} else {
			/*
			 * This is the last element
			 * make offset one plus the current.
			 */
			dp->d_off = (off64_t)l->offset + 1;
		}
		(void) strcpy(dp->d_name, l->name);
		dp->d_reclen = (ushort_t)this_reclen;
		outcount += dp->d_reclen;
		dp = (struct dirent64 *)((int)dp + dp->d_reclen);
		assert(outcount <= total_bytes_wanted);
		l = l->next;
	}

	res->rd_rddir.rddir_size = (long)outcount;
	if (outcount > 0) {
		/*
		 * have some entries
		 */
		res->rd_rddir.rddir_eof = (l == NULL);
		/* LINTED pointer alignment */
		res->rd_rddir.rddir_entries = (struct dirent64 *)outbuf;
		error = 0;
	} else {
		/*
		 * total_bytes_wanted is not large enough for one
		 * directory entry
		 */
		res->rd_rddir.rddir_eof = 0;
		res->rd_rddir.rddir_entries = NULL;
		free(outbuf);
		error = EIO;
	}
	return (error);

empty:
	res->rd_rddir.rddir_size = 0L;
	res->rd_rddir.rddir_eof = TRUE;
	res->rd_rddir.rddir_entries = NULL;
	return (error);
}


/*
 * add new entry to cache for 'map'
 */
static int
autofs_rddir_cache_enter(
	char *map,
	ulong_t bucket_size,
	struct autofs_rddir_cache **rdcpp)
{
	struct autofs_rddir_cache *p;
	assert(RW_LOCK_HELD(&autofs_rddir_cache_lock));

	/*
	 * Add to front of the list at this time
	 */
	p = (struct autofs_rddir_cache *)malloc(sizeof (*p));
	if (p == NULL) {
		syslog(LOG_ERR,
			"autofs_rddir_cache_enter: memory allocation failed\n");
		return (ENOMEM);
	}
	memset((char *)p, 0, sizeof (*p));

	p->map = malloc(strlen(map) + 1);
	if (p->map == NULL) {
		syslog(LOG_ERR,
			"autofs_rddir_cache_enter: memory allocation failed\n");
		free(p);
		return (ENOMEM);
	}
	strcpy(p->map, map);

	p->bucket_size = bucket_size;
	/*
	 * no need to grab mutex lock since I haven't yet made the
	 * node visible to the list
	 */
	p->in_use = 1;
	(void) rwlock_init(&p->rwlock, USYNC_THREAD, NULL);
	(void) mutex_init(&p->lock, USYNC_THREAD, NULL);

	if (rddir_head == NULL)
		rddir_head = p;
	else {
		p->next = rddir_head;
		rddir_head = p;
	}
	*rdcpp = p;

	return (0);
}

/*
 * find 'map' in readdir cache
 */
int
autofs_rddir_cache_lookup(char *map, struct autofs_rddir_cache **rdcpp)
{
	struct autofs_rddir_cache *p;

	assert(RW_LOCK_HELD(&autofs_rddir_cache_lock));
	for (p = rddir_head; p != NULL; p = p->next) {
		if (strcmp(p->map, map) == 0) {
			/*
			 * found matching entry
			 */
			*rdcpp = p;
			mutex_lock(&p->lock);
			p->in_use++;
			mutex_unlock(&p->lock);
			return (0);
		}
	}
	/*
	 * didn't find entry
	 */
	return (ENOENT);
}

/*
 * free the offset table
 */
static void
free_offset_tbl(struct off_tbl *head)
{
	struct off_tbl *p, *next = NULL;

	for (p = head; p != NULL; p = next) {
		next = p->next;
		free(p);
	}
}

/*
 * free the directory entries
 */
static void
free_dir_list(struct dir_entry *head)
{
	struct dir_entry *p, *next = NULL;

	for (p = head; p != NULL; p = next) {
		next = p->next;
		assert(p->name);
		free(p->name);
		free(p);
	}
}

static void
autofs_rddir_cache_entry_free(struct autofs_rddir_cache *p)
{
	assert(RW_LOCK_HELD(&autofs_rddir_cache_lock));
	assert(!p->in_use);
	if (p->map)
		free(p->map);
	if (p->offtp)
		free_offset_tbl(p->offtp);
	if (p->entp)
		free_dir_list(p->entp);
	free(p);
}

/*
 * Remove entry from the rddircache
 * the caller must own the autofs_rddir_cache_lock.
 */
static int
autofs_rddir_cache_delete(struct autofs_rddir_cache *rdcp)
{
	struct autofs_rddir_cache *p, *prev;

	assert(RW_LOCK_HELD(&autofs_rddir_cache_lock));
	/*
	 * Search cache for entry
	 */
	prev = NULL;
	for (p = rddir_head; p != NULL; p = p->next) {
		if (p == rdcp) {
			/*
			 * entry found, remove from list if not in use
			 */
			if (p->in_use)
				return (EBUSY);
			if (prev)
				prev->next = p->next;
			else
				rddir_head = p->next;
			autofs_rddir_cache_entry_free(p);
			return (0);
		}
		prev = p;
	}
	syslog(LOG_ERR, "Couldn't find entry %x in cache\n", p);
	return (ENOENT);
}

/*
 * Return entry that matches name, NULL otherwise.
 * Assumes the readers lock for this list has been grabed.
 */
struct dir_entry *
rddir_entry_lookup(char *name, struct dir_entry *list)
{
	return (btree_lookup(list, name));
}

static void
build_dir_entry_list(struct autofs_rddir_cache *rdcp, struct dir_entry *list)
{
	struct dir_entry *p;
	ulong_t offset = AUTOFS_DAEMONCOOKIE, offset_list = AUTOFS_DAEMONCOOKIE;
	struct off_tbl *offtp, *last = NULL;
	ino_t inonum = 4;

	assert(RW_LOCK_HELD(&rdcp->rwlock));
	assert(rdcp->entp == NULL);
	rdcp->entp = list;
	for (p = list; p != NULL; p = p->next) {
		p->nodeid = inonum;
		p->offset = offset;
		if (offset >= offset_list) {
			/*
			 * add node to index table
			 */
			offtp = (struct off_tbl *)
				malloc(sizeof (struct off_tbl));
			if (offtp != NULL) {
				offtp->offset = offset;
				offtp->first = p;
				offtp->next = NULL;
				offset_list += rdcp->bucket_size;
			} else {
				syslog(LOG_ERR,
"WARNING: build_dir_entry_list: could not add offset to index table\n");
				continue;
			}
			/*
			 * add to cache
			 */
			if (rdcp->offtp == NULL)
				rdcp->offtp = offtp;
			else
				last->next = offtp;
			last = offtp;
		}
		offset++;
		inonum += 2;		/* use even numbers in daemon */
	}
	rdcp->full = 1;
}

mutex_t cleanup_lock;
cond_t cleanup_start_cv;
cond_t cleanup_done_cv;

/*
 * cache cleanup thread starting point
 */
void
cache_cleanup(void)
{
	timestruc_t reltime;
	struct autofs_rddir_cache *p, *next = NULL;
	int error;

	mutex_init(&cleanup_lock, USYNC_THREAD, NULL);
	cond_init(&cleanup_start_cv, USYNC_THREAD, NULL);
	cond_init(&cleanup_done_cv, USYNC_THREAD, NULL);

	mutex_lock(&cleanup_lock);
	for (;;) {
		reltime.tv_sec = RDDIR_CACHE_TIME/2;
		reltime.tv_nsec = 0;

		/*
		 * delay RDDIR_CACHE_TIME seconds, or until some other thread
		 * requests that I cleanup the caches
		 */
		if (error = cond_reltimedwait(
		    &cleanup_start_cv, &cleanup_lock, &reltime)) {
			if (error != ETIME) {
				if (trace > 1)
					trace_prt(1,
					"cleanup thread wakeup (%d)\n", error);
				continue;
			}
		}
		mutex_unlock(&cleanup_lock);

		/*
		 * Perform the cache cleanup
		 */
		rw_wrlock(&autofs_rddir_cache_lock);
		for (p = rddir_head; p != NULL; p = next) {
			next = p->next;
			if (p->in_use > 0) {
				/*
				 * cache entry busy, skip it
				 */
				if (trace > 1) {
					trace_prt(1,
					"%s cache in use\n", p->map);
				}
				continue;
			}
			/*
			 * Cache entry is not in use, and nobody can grab a
			 * new reference since I'm holding the
			 * autofs_rddir_cache_lock
			 */

			/*
			 * error will be zero if some thread signaled us asking
			 * that the caches be freed. In such case, free caches
			 * even if they're still valid and nobody is referencing
			 * them at this time. Otherwise, free caches only
			 * if their time to live (ttl) has expired.
			 */
			if (error == ETIME && (p->ttl > time((time_t *)NULL))) {
				/*
				 * Scheduled cache cleanup, if cache is still
				 * valid don't free.
				 */
				if (trace > 1) {
					trace_prt(1,
					"%s cache still valid\n", p->map);
				}
				continue;
			}
			if (trace > 1)
				trace_prt(1, "%s freeing cache\n", p->map);
			assert(!p->in_use);
			error = autofs_rddir_cache_delete(p);
			assert(!error);
		}
		rw_unlock(&autofs_rddir_cache_lock);

		/*
		 * wakeup the thread/threads waiting for the
		 * cleanup to finish
		 */
		mutex_lock(&cleanup_lock);
		cond_broadcast(&cleanup_done_cv);
	}
	/* NOTREACHED */
}
/*
 * 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
 */
/*
 * autod_xdr.c
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This file can not be automatically generated by rpcgen from
 * autofs_prot.x because of the xdr routines that provide readdir
 * support, and my own implementation of xdr_autofs_netbuf().
 */

#include <sys/vfs.h>
#include <sys/sysmacros.h>		/* includes roundup() */
#include <string.h>
#include <rpcsvc/autofs_prot.h>
#include <nfs/nfs4.h>
#include <rpcsvc/nfs4_prot.h>
#include <rpc/xdr.h>
#include <stdlib.h>
#include <strings.h>

bool_t
xdr_autofs_stat(register XDR *xdrs, autofs_stat *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_autofs_action(register XDR *xdrs, autofs_action *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_linka(register XDR *xdrs, linka *objp)
{
	if (!xdr_string(xdrs, &objp->dir, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->link, AUTOFS_MAXPATHLEN))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_autofs_netbuf(xdrs, objp)
	XDR *xdrs;
	struct netbuf *objp;
{
	bool_t dummy;

	if (!xdr_u_int(xdrs, &objp->maxlen)) {
		return (FALSE);
	}
	dummy = xdr_bytes(xdrs, (char **)&(objp->buf),
			(uint_t *)&(objp->len), objp->maxlen);
	return (dummy);
}

bool_t
xdr_autofs_args(register XDR *xdrs, autofs_args *objp)
{
	if (!xdr_autofs_netbuf(xdrs, &objp->addr))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->path, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->opts, AUTOFS_MAXOPTSLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->map, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->subdir, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->key, AUTOFS_MAXCOMPONENTLEN))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->mount_to))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->rpc_to))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->direct))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_mounta(register XDR *xdrs, struct mounta *objp)
{
	if (!xdr_string(xdrs, &objp->spec, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->dir, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->flags))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->fstype, AUTOFS_MAXCOMPONENTLEN))
		return (FALSE);
	if (!xdr_pointer(xdrs, (char **)&objp->dataptr, sizeof (autofs_args),
	    (xdrproc_t)xdr_autofs_args))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->datalen))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->optptr, AUTOFS_MAXOPTSLEN))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->optlen))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_action_list_entry(register XDR *xdrs, action_list_entry *objp)
{
	if (!xdr_autofs_action(xdrs, &objp->action))
		return (FALSE);
	switch (objp->action) {
	case AUTOFS_MOUNT_RQ:
		if (!xdr_mounta(xdrs, &objp->action_list_entry_u.mounta))
			return (FALSE);
		break;
	case AUTOFS_LINK_RQ:
		if (!xdr_linka(xdrs, &objp->action_list_entry_u.linka))
			return (FALSE);
		break;
	}
	return (TRUE);
}

bool_t
xdr_action_list(XDR *xdrs, action_list *objp)
{
	action_list *tmp_action_list;
	bool_t more_data = TRUE;
	bool_t first_objp = TRUE;

	if (xdrs->x_op == XDR_DECODE) {
		while (more_data) {
			if (!xdr_action_list_entry(xdrs, &objp->action))
				return (FALSE);
			if (!xdr_bool(xdrs, &more_data))
				return (FALSE);
			if (!more_data) {
				objp->next = NULL;
				break;
			}
			if (objp->next == NULL) {
				objp->next = (action_list *)
				    mem_alloc(sizeof (action_list));
				if (objp->next == NULL)
					return (FALSE);
				bzero(objp->next, sizeof (action_list));
			}
			objp = objp->next;
		}
	} else if (xdrs->x_op == XDR_ENCODE) {
		while (more_data) {
			if (!xdr_action_list_entry(xdrs, &objp->action))
				return (FALSE);
			objp = objp->next;
			if (objp == NULL)
				more_data = FALSE;
			if (!xdr_bool(xdrs, &more_data))
				return (FALSE);
		}
	} else {
		while (more_data) {
			if (!xdr_action_list_entry(xdrs, &objp->action))
				return (FALSE);
			tmp_action_list = objp;
			objp = objp->next;
			if (objp == NULL)
				more_data = FALSE;
			if (!first_objp)
				mem_free(tmp_action_list, sizeof (action_list));
			else
				first_objp = FALSE;
		}
	}
	return (TRUE);
}

bool_t
xdr_umntrequest(register XDR *xdrs, umntrequest *objp)
{
	if (!xdr_bool_t(xdrs, &objp->isdirect))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->mntresource, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->mntpnt, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->fstype, AUTOFS_MAXCOMPONENTLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->mntopts, AUTOFS_MAXOPTSLEN))
		return (FALSE);
	if (!xdr_pointer(xdrs, (char **)&objp->next, sizeof (umntrequest),
	    (xdrproc_t)xdr_umntrequest))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_umntres(register XDR *xdrs, umntres *objp)
{
	if (!xdr_int(xdrs, &objp->status))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_autofs_res(xdrs, objp)
	register XDR *xdrs;
	autofs_res *objp;
{
	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_autofs_lookupargs(xdrs, objp)
	register XDR *xdrs;
	autofs_lookupargs *objp;
{
	if (!xdr_string(xdrs, &objp->map, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->path, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->name, AUTOFS_MAXCOMPONENTLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->subdir, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_string(xdrs, &objp->opts, AUTOFS_MAXOPTSLEN))
		return (FALSE);
	if (!xdr_bool_t(xdrs, &objp->isdirect))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->uid))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_mount_result_type(xdrs, objp)
	register XDR *xdrs;
	mount_result_type *objp;
{
	if (!xdr_autofs_stat(xdrs, &objp->status))
		return (FALSE);
	switch (objp->status) {
	case AUTOFS_ACTION:
		if (!xdr_pointer(xdrs,
		    (char **)&objp->mount_result_type_u.list,
		    sizeof (action_list), (xdrproc_t)xdr_action_list))
			return (FALSE);
		break;
	case AUTOFS_DONE:
		if (!xdr_int(xdrs, &objp->mount_result_type_u.error))
			return (FALSE);
		break;
	}
	return (TRUE);
}

bool_t
xdr_autofs_mountres(xdrs, objp)
	register XDR *xdrs;
	autofs_mountres *objp;
{
	if (!xdr_mount_result_type(xdrs, &objp->mr_type))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->mr_verbose))
		return (FALSE);
	return (TRUE);
}
bool_t
xdr_lookup_result_type(xdrs, objp)
	register XDR *xdrs;
	lookup_result_type *objp;
{
	if (!xdr_autofs_action(xdrs, &objp->action))
		return (FALSE);
	switch (objp->action) {
	case AUTOFS_LINK_RQ:
		if (!xdr_linka(xdrs, &objp->lookup_result_type_u.lt_linka))
			return (FALSE);
		break;
	}
	return (TRUE);
}

bool_t
xdr_autofs_lookupres(xdrs, objp)
	register XDR *xdrs;
	autofs_lookupres *objp;
{
	if (!xdr_autofs_res(xdrs, &objp->lu_res))
		return (FALSE);
	if (!xdr_lookup_result_type(xdrs, &objp->lu_type))
		return (FALSE);
	if (!xdr_int(xdrs, &objp->lu_verbose))
		return (FALSE);
	return (TRUE);
}

/*
 * ******************************************************
 * Readdir XDR support
 * ******************************************************
 */

bool_t
xdr_autofs_rddirargs(xdrs, objp)
	register XDR *xdrs;
	autofs_rddirargs *objp;
{
	if (!xdr_string(xdrs, &objp->rda_map, AUTOFS_MAXPATHLEN))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->rda_offset))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->rda_count))
		return (FALSE);
	if (!xdr_u_int(xdrs, (uint_t *)&objp->uid))
		return (FALSE);
	return (TRUE);
}

/*
 * Directory read reply:
 * union (enum autofs_res) {
 *	AUTOFS_OK: entlist;
 *		 boolean eof;
 *	default:
 * }
 *
 * Directory entries
 *	struct  direct {
 *		off_t   d_off;			* offset of next entry *
 *		u_long  d_fileno;		* inode number of entry *
 *		u_short d_reclen;		* length of this record *
 *		u_short d_namlen;		* length of string in d_name *
 *		char    d_name[MAXNAMLEN + 1];	* name no longer than this *
 *	};
 * are on the wire as:
 * union entlist (boolean valid) {
 * 	TRUE:	struct otw_dirent;
 *		u_long nxtoffset;
 *		union entlist;
 *	FALSE:
 * }
 * where otw_dirent is:
 * 	struct dirent {
 *		u_long	de_fid;
 *		string	de_name<AUTOFS_MAXPATHLEN>;
 *	}
 */

#ifdef nextdp
#undef nextdp
#endif
#define	nextdp(dp)	((struct dirent64 *)((char *)(dp) + (dp)->d_reclen))

/*
 * ENCODE ONLY
 */
bool_t
xdr_autofs_putrddirres(xdrs, rddir, reqsize)
	XDR *xdrs;
	struct autofsrddir *rddir;
	uint_t reqsize;			/* requested size */
{
	struct dirent64 *dp;
	char *name;
	int size;
	uint_t namlen;
	bool_t true = TRUE;
	bool_t false = FALSE;
	int entrysz;
	int tofit;
	int bufsize;
	uint_t ino, off;

	bufsize = 1 * BYTES_PER_XDR_UNIT;
	for (size = rddir->rddir_size, dp = rddir->rddir_entries;
		size > 0;
		/* LINTED pointer alignment */
		size -= dp->d_reclen, dp = nextdp(dp)) {
		if (dp->d_reclen == 0 /* || DIRSIZ(dp) > dp->d_reclen */) {
			return (FALSE);
		}
		if (dp->d_ino == 0) {
			continue;
		}
		name = dp->d_name;
		namlen = strlen(name);
		ino = (uint_t)dp->d_ino;
		off = (uint_t)dp->d_off;
		entrysz = (1 + 1 + 1 + 1) * BYTES_PER_XDR_UNIT +
		    roundup(namlen, BYTES_PER_XDR_UNIT);
		tofit = entrysz + 2 * BYTES_PER_XDR_UNIT;
		if (bufsize + tofit > reqsize) {
			rddir->rddir_eof = FALSE;
			break;
		}
		if (!xdr_bool(xdrs, &true) ||
		    !xdr_u_int(xdrs, &ino) ||
		    !xdr_bytes(xdrs, &name, &namlen, AUTOFS_MAXPATHLEN) ||
		    !xdr_u_int(xdrs, &off)) {
			return (FALSE);
		}
		bufsize += entrysz;
	}
	if (!xdr_bool(xdrs, &false)) {
		return (FALSE);
	}
	if (!xdr_bool(xdrs, &rddir->rddir_eof)) {
		return (FALSE);
	}
	return (TRUE);
}

#define	DIRENT64_RECLEN(namelen)	\
	(((int)(((dirent64_t *)0)->d_name) + 1 + (namelen) + 7) & ~ 7)
#define	reclen(namlen)	DIRENT64_RECLEN((namlen))

/*
 * DECODE ONLY
 */
bool_t
xdr_autofs_getrddirres(xdrs, rddir)
	XDR *xdrs;
	struct autofsrddir *rddir;
{
	struct dirent64 *dp;
	uint_t namlen;
	int size;
	bool_t valid;
	int offset = -1;
	uint_t fileid;

	size = rddir->rddir_size;
	dp = rddir->rddir_entries;
	for (;;) {
		if (!xdr_bool(xdrs, &valid)) {
			return (FALSE);
		}
		if (!valid) {
			break;
		}
		if (!xdr_u_int(xdrs, &fileid) ||
		    !xdr_u_int(xdrs, &namlen)) {
			return (FALSE);
		}
		if (reclen(namlen) > size) {
			rddir->rddir_eof = FALSE;
			goto bufovflw;
		}
		if (!xdr_opaque(xdrs, dp->d_name, namlen)||
		    !xdr_int(xdrs, &offset)) {
			return (FALSE);
		}
		dp->d_ino = fileid;
		dp->d_reclen = reclen(namlen);
		dp->d_name[namlen] = '\0';
		dp->d_off = offset;
		size -= dp->d_reclen;
		/* LINTED pointer alignment */
		dp = nextdp(dp);
	}
	if (!xdr_bool(xdrs, &rddir->rddir_eof)) {
		return (FALSE);
	}
bufovflw:
	rddir->rddir_size = (char *)dp - (char *)(rddir->rddir_entries);
	rddir->rddir_offset = offset;
	return (TRUE);
}

bool_t
xdr_autofs_rddirres(register XDR *xdrs, autofs_rddirres *objp)
{
	if (!xdr_enum(xdrs, (enum_t *)&objp->rd_status))
		return (FALSE);
	if (objp->rd_status != AUTOFS_OK)
		return (TRUE);
	if (xdrs->x_op == XDR_ENCODE)
		return (xdr_autofs_putrddirres(
		    xdrs, (struct autofsrddir *)&objp->rd_rddir,
		    objp->rd_bufsize));
	else if (xdrs->x_op == XDR_DECODE)
		return (xdr_autofs_getrddirres(xdrs,
		    (struct autofsrddir *)&objp->rd_rddir));
	else return (FALSE);
}
#
# 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) 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Moved to SMF. Use sharectl(8) to manage AUTOFS properties.
#
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
    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) 2010, Oracle and/or its affiliates. All rights reserved.

    NOTE:  This service manifest is not editable; its contents will
    be overwritten by package or patch operations, including
    operating system upgrade.  Make customizations in a different
    file.

    Note: if this service is modified to consist of anything other
    than a single instance named 'default', you must make changes to
    $SRC/head/rpcsvc/daemon_utils.h and libnsl:open_daemon_lock().
-->

<service_bundle type='manifest' name='SUNWatfsr:autofs'>

<service
	name='system/filesystem/autofs'
	type='service'
	version='1'>

	<dependency
		name='fs'
		type='service'
		grouping='require_all'
		restart_on='none'>
		<service_fmri value='svc:/system/filesystem/local' />
	</dependency>

	<dependency
		name='name-service-milestone'
		type='service'
		grouping='require_all'
		restart_on='restart'>
		<service_fmri value='svc:/milestone/name-services' />
	</dependency>

	<dependency
		name='nfs'
		type='service'
		grouping='optional_all'
		restart_on='none'>
		<service_fmri value='svc:/network/nfs/client' />
	</dependency>

	<dependency
		name='rpcbind'
		type='service'
		grouping='require_all'
		restart_on='restart'>
		<service_fmri value='svc:/network/rpc/bind' />
	</dependency>

	<dependent
		name='autofs_multi-user'
		grouping='optional_all'
		restart_on='none'>
		<service_fmri value='svc:/milestone/multi-user' />
	</dependent>

	<exec_method
		type='method'
		name='start'
		exec='/lib/svc/method/svc-autofs %m'
		timeout_seconds='60'>
	</exec_method>

	<exec_method
		type='method'
		name='stop'
		exec='/lib/svc/method/svc-autofs %m %{restarter/contract}'
		timeout_seconds='60'>
	</exec_method>

	<property_group name='general' type='framework'>
		<!-- to start stop autofs daemon -->
		<propval name='action_authorization' type='astring'
			value='solaris.smf.manage.autofs' />
	</property_group>


	<property_group name='application' type='framework'>
		<stability value='Evolving' />
		<propval name='auto_enable' type='boolean' value='true' />
	</property_group>

	<instance name='default' enabled='false'>
	  <property_group name='autofs-props' type='com.oracle.autofs,props'>
	    <propval name='timeout' type='integer' value='600'/>
	    <propval name='automount_verbose' type='boolean' value='false'/>
	    <propval name='trace' type='integer' value='0'/>
	    <propval name='nobrowse' type='boolean' value='false'/>
	    <propval name='automountd_verbose' type='boolean' value='false'/>
	    <propval name='environment' type='astring' value=''/>
	  </property_group>
	</instance>

	<stability value='Stable' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
			automounter
			</loctext>
		</common_name>
		<documentation>
			<manpage title='automount' section='8'
				manpath='/usr/share/man' />
		</documentation>
	</template>
</service>

</service_bundle>
/*
 * 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
 */
/*
 *	automount.c
 *
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */


#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <locale.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#include <syslog.h>
#include <libshare.h>
#include <libscf.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/vfs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mnttab.h>
#include <sys/mntent.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/tiuser.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>
#include <nsswitch.h>
#include <deflt.h>
#include <rpcsvc/daemon_utils.h>
#include "automount.h"
#include "smfcfg.h"

static int mkdir_r(char *);
struct autodir *dir_head;
struct autodir *dir_tail;
static struct extmnttab *find_mount();
int verbose = 0;
int trace = 0;

static void usage();
static int compare_opts(char *, char *);
static void do_unmounts();

static int mount_timeout = AUTOFS_MOUNT_TIMEOUT;

static char	*service_list[] = { AUTOMOUNTD, NULL };

/*
 * XXX
 * The following are needed because they're used in auto_subr.c and
 * we link with it. Should avoid this.
 */
mutex_t cleanup_lock;
cond_t cleanup_start_cv;
cond_t cleanup_done_cv;

int
main(int argc, char *argv[])
{
	int c;
	struct autofs_args ai;
	struct utsname utsname;
	char autofs_addr[MAXADDRLEN];
	struct autodir *dir, *d;
	struct stat stbuf;
	char *master_map = "auto_master";
	int null;
	struct extmnttab mnt, *mntp;
	struct mnttab *omntp;
	char mntopts[MAX_MNTOPT_STR];
	int mntflgs;
	int count = 0;
	char *stack[STACKSIZ];
	char **stkptr;
	char *defval;
	struct sigaction sigintact;
	int ret = 0, bufsz = 0;
	char valbuf[6];

	/*
	 * protect this command from session termination when run in background
	 * we test background by whether SIGINT is ignored
	 */
	(void) sigaction(SIGINT, NULL, &sigintact);
	if (sigintact.sa_handler == SIG_IGN) {
		(void) signal(SIGHUP, SIG_IGN);
		(void) setsid();
	}

	/*
	 * Read in the values from SMF first before we check
	 * commandline options so the options override the SMF values.
	 */
	bufsz = 6;
	ret = autofs_smf_get_prop("timeout", valbuf, DEFAULT_INSTANCE,
	    SCF_TYPE_INTEGER, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK)
		/*
		 * Ignore errno.  In event of failure, mount_timeout is
		 * already initialized to the correct value.
		 */
		mount_timeout = strtol(valbuf, (char **)NULL, 10);

	bufsz = 6;
	ret = autofs_smf_get_prop("automount_verbose", valbuf, DEFAULT_INSTANCE,
	    SCF_TYPE_BOOLEAN, AUTOMOUNTD, &bufsz);
	if (ret == SA_OK) {
		if (strncasecmp("true", valbuf, 4) == 0)
			verbose = TRUE;
	}

	put_automountd_env();

	while ((c = getopt(argc, argv, "mM:D:f:t:v?")) != EOF) {
		switch (c) {
		case 'm':
			pr_msg("Warning: -m option not supported");
			break;
		case 'M':
			pr_msg("Warning: -M option not supported");
			break;
		case 'D':
			pr_msg("Warning: -D option not supported");
			break;
		case 'f':
			pr_msg("Error: -f option no longer supported");
			usage();
			break;
		case 't':
			if (strchr(optarg, '=')) {
				pr_msg("Error: invalid value for -t");
				usage();
			}
			mount_timeout = atoi(optarg);
			break;
		case 'v':
			verbose++;
			break;
		default:
			usage();
			break;
		}
	}

	if (optind < argc) {
		pr_msg("%s: command line mountpoints/maps "
		    "no longer supported", argv[optind]);
		usage();
	}

	current_mounts = getmntlist();
	if (current_mounts == NULL) {
		pr_msg("Couldn't establish current mounts");
		exit(1);
	}

	(void) umask(0);
	ns_setup(stack, &stkptr);

	openlog("automount", LOG_PID, LOG_DAEMON);
	(void) loadmaster_map(master_map, "", stack, &stkptr);
	if (dir_head != NULL) {
		/*
		 * automount maps found. enable services as needed.
		 */
		_check_services(service_list);
	}

	closelog();

	if (uname(&utsname) < 0) {
		pr_msg("uname: %m");
		exit(1);
	}
	(void) strcpy(autofs_addr, utsname.nodename);
	(void) strcat(autofs_addr, ".autofs");
	ai.addr.buf	= autofs_addr;
	ai.addr.len	= strlen(ai.addr.buf);
	ai.addr.maxlen	= ai.addr.len;

	ai.mount_to	= mount_timeout;
	ai.rpc_to	= AUTOFS_RPC_TIMEOUT;

	/*
	 * Mount the daemon at its mount points.
	 */
	for (dir = dir_head; dir; dir = dir->dir_next) {

		/*
		 * Skip null entries
		 */
		if (strcmp(dir->dir_map, "-null") == 0)
			continue;

		/*
		 * Skip null'ed entries
		 */
		null = 0;
		for (d = dir->dir_prev; d; d = d->dir_prev) {
			if (strcmp(dir->dir_name, d->dir_name) == 0)
				null = 1;
		}
		if (null)
			continue;

		/*
		 * Check whether there's already an entry
		 * in the mnttab for this mountpoint.
		 */
		if (mntp = find_mount(dir->dir_name, 1)) {
			/*
			 * If it's not an autofs mount - don't
			 * mount over it.
			 */
			if (strcmp(mntp->mnt_fstype, MNTTYPE_AUTOFS) != 0) {
				pr_msg("%s: already mounted",
				    mntp->mnt_mountp);
				continue;
			}

			/*
			 * Compare the mnttab entry with the master map
			 * entry.  If the map or mount options are
			 * different, then update this information
			 * with a remount.
			 */
			if (strcmp(mntp->mnt_special, dir->dir_map) == 0 &&
			    compare_opts(dir->dir_opts,
			    mntp->mnt_mntopts) == 0) {
				continue;	/* no change */
			}

			/*
			 * Check for an overlaid direct autofs mount.
			 * Cannot remount since it's inaccessible.
			 */
			omntp = (struct mnttab *)mntp;
			if (hasmntopt(omntp, "direct") != NULL) {
				mntp = find_mount(dir->dir_name, 0);
				omntp = (struct mnttab *)mntp;
				if (hasmntopt(omntp, "direct") == NULL) {
					if (verbose)
						pr_msg("%s: cannot remount",
						    dir->dir_name);
					continue;
				}
			}

			dir->dir_remount = 1;
		}

		/*
		 * Create a mount point if necessary
		 * If the path refers to an existing symbolic
		 * link, refuse to mount on it.  This avoids
		 * future problems.
		 */
		if (lstat(dir->dir_name, &stbuf) == 0) {
			if ((stbuf.st_mode & S_IFMT) != S_IFDIR) {
				pr_msg("%s: Not a directory", dir->dir_name);
				continue;
			}
		} else {
			if (mkdir_r(dir->dir_name)) {
				pr_msg("%s: %m", dir->dir_name);
				continue;
			}
		}

		ai.path		= dir->dir_name;
		ai.opts		= dir->dir_opts;
		ai.map		= dir->dir_map;
		ai.subdir	= "";
		ai.direct	= dir->dir_direct;
		if (dir->dir_direct)
			ai.key = dir->dir_name;
		else
			ai.key = "";

		(void) sprintf(mntopts, "ignore,%s",
		    dir->dir_direct  ? "direct" : "indirect");
		if (dir->dir_opts && *dir->dir_opts) {
			(void) strcat(mntopts, ",");
			(void) strcat(mntopts, dir->dir_opts);
		}
		mntflgs = MS_OPTIONSTR | (dir->dir_remount ? MS_REMOUNT : 0);
		if (mount(dir->dir_map, dir->dir_name, MS_DATA | mntflgs,
		    MNTTYPE_AUTOFS, &ai, sizeof (ai), mntopts,
		    MAX_MNTOPT_STR) < 0) {
			pr_msg("mount %s: %m", dir->dir_name);
			continue;
		}

		count++;

		if (verbose) {
			if (dir->dir_remount)
				pr_msg("%s remounted", dir->dir_name);
			else
				pr_msg("%s mounted", dir->dir_name);
		}
	}

	if (verbose && count == 0)
		pr_msg("no mounts");

	/*
	 * Now compare the /etc/mnttab with the master
	 * map.  Any autofs mounts in the /etc/mnttab
	 * that are not in the master map must be
	 * unmounted
	 */
	do_unmounts();

	return (0);
}

/*
 * Find a mount entry given
 * the mountpoint path.
 * Optionally return the first
 * or last entry.
 */
static struct extmnttab *
find_mount(mntpnt, first)
	char *mntpnt;
	int first;
{
	struct mntlist *mntl;
	struct extmnttab *found = NULL;

	for (mntl = current_mounts; mntl; mntl = mntl->mntl_next) {

		if (strcmp(mntpnt, mntl->mntl_mnt->mnt_mountp) == 0) {
			found = mntl->mntl_mnt;
			if (first)
				break;
		}
	}

	return (found);
}

static char *ignore_opts[] = {"ignore", "direct", "indirect", "dev", NULL};

/*
 * Compare mount options
 * ignoring "ignore", "direct", "indirect"
 * and "dev=".
 */
static int
compare_opts(opts, mntopts)
	char *opts, *mntopts;
{
	char optbuf1[MAX_MNTOPT_STR], *s = optbuf1;
	char optbuf2[MAX_MNTOPT_STR];
	char **opttbl1, **opttbl2;
	int nopts1, nopts2;
	char *ostart, *optr, *valp;
	int j, i, notsame;

	opttbl1 = opttbl2 = NULL;
	/*
	 * Parse the two option strings to split them both into
	 * lists of individual options.
	 */
	if (mntopts != NULL)
		(void) strcpy(s, mntopts);
	else
		*s = '\0';
	if (*s != '\0')
		nopts1 = 1;
	else
		nopts1 = 0;
	for (s = strchr(s, ','); s != NULL; s = strchr(s, ',')) {
		nopts1++;
		s++;
	}
	if (nopts1)
		if ((opttbl1 = memalign(sizeof (char *),
			nopts1 * sizeof (char *))) == NULL)
			return (1);
	nopts1 = 0;
	s = optbuf1;
	for (ostart = optr = s; *optr != '\0'; ostart = optr) {
		if (getsubopt(&optr, ignore_opts, &valp) == -1) {
			opttbl1[nopts1++] = ostart;
		}
	}
	s = optbuf2;
	if (opts != NULL)
		(void) strcpy(s, opts);
	else
		*s = '\0';
	if (*s != '\0')
		nopts2 = 1;
	else
		nopts2 = 0;
	for (s = strchr(s, ','); s != NULL; s = strchr(s, ',')) {
		nopts2++;
		s++;
	}
	if (nopts2)
		if ((opttbl2 = memalign(sizeof (char *),
			nopts2 * sizeof (char *))) == NULL) {
			notsame = 1;
			goto done;
		}
	nopts2 = 0;
	s = optbuf2;
	for (ostart = optr = s; *optr != '\0'; ostart = optr) {
		if (getsubopt(&optr, ignore_opts, &valp) == -1) {
			opttbl2[nopts2++] = ostart;
		}
	}
	if (nopts2 != nopts1) {
		notsame = 1;
		goto done;
	}
	notsame = 0;
	for (i = 0; i < nopts1; i++) {
		notsame = 1;
		for (j = 0; j < nopts2; j++) {
			if (strcmp(opttbl1[i], opttbl2[j]) == 0) {
				notsame = 0;
				break;
			}
		}
		if (notsame)
			break;
	}

done:
	if (opttbl1 != NULL)
		free(opttbl1);
	if (opttbl2 != NULL)
		free(opttbl2);
	return (notsame);
}

static void
usage()
{
	pr_msg("Usage: automount  [ -v ]  [ -t duration ]");
	exit(1);
	/* NOTREACHED */
}

/*
 * Unmount any autofs mounts that
 * aren't in the master map
 */
static void
do_unmounts()
{
	struct mntlist *mntl;
	struct extmnttab *mnt;
	struct mnttab *omnt;
	struct autodir *dir;
	int current;
	int count = 0;
	struct zone_summary *zsp;

	zsp = fs_get_zone_summaries();
	if (zsp == NULL) {
		pr_msg("Couldn't establish active zones");
		exit(1);
	}
	for (mntl = current_mounts; mntl; mntl = mntl->mntl_next) {
		mnt = mntl->mntl_mnt;
		omnt = (struct mnttab *)mnt;
		if (strcmp(mnt->mnt_fstype, MNTTYPE_AUTOFS) != 0)
			continue;
		if (fs_mount_in_other_zone(zsp, mnt->mnt_mountp))
			continue;
		/*
		 * Don't unmount autofs mounts done
		 * from the autofs mount command.
		 * How do we tell them apart ?
		 * Autofs mounts not eligible for auto-unmount
		 * have the "nest" pseudo-option.
		 */
		if (hasmntopt(omnt, "nest") != NULL)
			continue;

		current = 0;
		for (dir = dir_head; dir; dir = dir->dir_next) {
			if (strcmp(dir->dir_name, mnt->mnt_mountp) == 0) {
				current = strcmp(dir->dir_map, "-null");
				break;
			}
		}
		if (current)
			continue;


		if (umount(mnt->mnt_mountp) == 0) {
			if (verbose) {
				pr_msg("%s unmounted",
				    mnt->mnt_mountp);
			}
			count++;
		}
	}
	if (verbose && count == 0)
		pr_msg("no unmounts");
}

static int
mkdir_r(dir)
	char *dir;
{
	int err;
	char *slash;

	if (mkdir(dir, 0555) == 0 || errno == EEXIST)
		return (0);
	if (errno != ENOENT)
		return (-1);
	slash = strrchr(dir, '/');
	if (slash == NULL)
		return (-1);
	*slash = '\0';
	err = mkdir_r(dir);
	*slash++ = '/';
	if (err || !*slash)
		return (err);
	return (mkdir(dir, 0555));
}

/*
 * Print an error.
 * Works like printf (fmt string and variable args)
 * except that it will subsititute an error message
 * for a "%m" string (like syslog).
 */
/* VARARGS1 */
void
pr_msg(const char *fmt, ...)
{
	va_list ap;
	char buf[BUFSIZ], *p2;
	char *p1;
	char *nfmt;

	(void) strcpy(buf, "automount: ");
	p2 = buf + strlen(buf);

	nfmt = gettext(fmt);

	for (p1 = nfmt; *p1; p1++) {
		if (*p1 == '%' && *(p1+1) == 'm') {
			(void) strcpy(p2, strerror(errno));
			p2 += strlen(p2);
			p1++;
		} else {
			*p2++ = *p1;
		}
	}
	if (p2 > buf && *(p2-1) != '\n')
		*p2++ = '\n';
	*p2 = '\0';

	va_start(ap, fmt);
	(void) vfprintf(stderr, buf, ap);
	va_end(ap);
}
/*
 * 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 2015 Nexenta Systems, Inc.  All rights reserved.
 */

/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_AUTOMOUNT_H
#define	_AUTOMOUNT_H

#include <fslib.h>		/* needed for mntlist_t declaration */
#include <thread.h>
#include <sys/mntent.h>		/*    "    "  MNTTYPE_* declarations */
#include <synch.h>		/* needed for mutex_t declaration */
#include <sys/types.h>
#include <rpc/rpc.h>
#include <sys/fs/autofs.h>
#include <netinet/in.h>		/* needed for sockaddr_in declaration */
#include <door.h>

#ifdef MALLOC_DEBUG
#include <debug_alloc.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _REENTRANT
#define	fork1			vfork
#define	rpc_control(a, b)	1
#endif

#define	DOMOUNT_USER	1
#define	DOMOUNT_KERNEL	2

/*
 * Solaris autofs configuration file location
 */
#define	AUTOFSADMIN	"/etc/default/autofs"

#define	MXHOSTNAMELEN	64
#define	MAXNETNAMELEN   255
#define	MAXFILENAMELEN  255
#define	LINESZ		4096
#define	MAXADDRLEN	128		/* max autofs address length */
#define	MAXOPTSLEN	1024

#define	AUTOFS_MOUNT_TIMEOUT	600	/* default min time mount will */
					/* remain mounted (in seconds) */
#define	AUTOFS_RPC_TIMEOUT	60	/* secs autofs will wait for */
					/* automountd's reply before */
					/* retransmitting */
/* stack ops */
#define	ERASE		0
#define	PUSH		1
#define	POP		2
#define	INIT		3
#define	STACKSIZ	30

#define	DIST_SELF	1
#define	DIST_MYSUB	2
#define	DIST_MYNET	3
#define	DIST_OTHER	4

#define	MAXIFS		32

/*
 * Retry operation related definitions.
 */
#define	RET_OK		0
#define	RET_RETRY	32
#define	RET_ERR		33
#define	INITDELAY	5
#define	DELAY_BACKOFF	2
#define	MAXDELAY	120
#define	ARGV_MAX	16
#define	VFS_PATH	"/usr/lib/fs"
#define	DELAY(delay) { \
	(void) sleep(delay); \
	delay *= DELAY_BACKOFF; \
	if (delay > MAXDELAY) \
		delay = MAXDELAY; \
}

struct mapline {
	char linebuf[LINESZ];
	char lineqbuf[LINESZ];
};

/*
 * Structure describing a host/filesystem/dir tuple in a NIS map entry
 */
struct mapfs {
	struct mapfs *mfs_next;	/* next in entry */
	int	mfs_ignore;	/* ignore this entry */
	char	*mfs_host;	/* host name */
	char	*mfs_dir;	/* dir to mount */
	int	mfs_penalty;	/* mount penalty for this host */
	int	mfs_distance;	/* distance hint */
	struct nfs_args *mfs_args;	/* nfs_args */
	struct netconfig *mfs_nconf;
	rpcvers_t	mfs_version;	/* NFS version */

#define	MFS_ALLOC_DIR		0x1	/* mfs_dir now points to different */
					/* buffer */

#define	MFS_URL			0x2	/* is NFS url listed in this tuple. */
#define	MFS_FH_VIA_WEBNFS	0x4	/* got file handle during ping phase */

	uint_t	mfs_flags;
	uint_t	mfs_port;	/* port# in NFS url */
};

/*
 * NIS entry - lookup of name in DIR gets us this
 */
struct mapent {
	char	*map_fstype;	/* file system type e.g. "nfs" */
	char	*map_mounter;	/* base fs */
	char	*map_root;	/* path to mount root */
	char	*map_mntpnt;	/* path from mount root */
	char	*map_mntopts;	/* mount options */
	char    *map_fsw;	/* mount fs information */
	char    *map_fswq;	/* quoted mountfs information */
	int	map_mntlevel;	/* mapentry hierarchy level */
	bool_t	map_modified;	/* flags modified mapentries */
	bool_t	map_faked;	/* flags faked mapentries */
	int	map_err;	/* flags any bad entries in the map */
	struct mapfs *map_fs;	/* list of replicas for nfs */
	struct mapent *map_next;
};


/*
 * Descriptor for each directory served by the automounter
 */
struct autodir {
	char	*dir_name;		/* mount point */
	char	*dir_map;		/* name of map for dir */
	char	*dir_opts;		/* default mount options */
	int	dir_direct;		/* direct mountpoint ? */
	int	dir_remount;		/* a remount */
	struct autodir *dir_next;	/* next entry */
	struct autodir *dir_prev;	/* prev entry */
};

/*
 * This structure is used to build an array of
 * hostnames with associated penalties to be
 * passed to the nfs_cast procedure
 */
struct host_names {
	char *host;
	int  penalty;
};

/*
 * structure used to build list of contents for a map on
 * a readdir request
 */
struct dir_entry {
	char		*name;		/* name of entry */
	ino_t		nodeid;
	off_t		offset;
	struct dir_entry *next;
	struct dir_entry *left;		/* left element in binary tree */
	struct dir_entry *right;	/* right element in binary tree */
};

/*
 * offset index table
 */
struct off_tbl {
	off_t			offset;
	struct dir_entry	*first;
	struct off_tbl		*next;
};

#ifndef NO_RDDIR_CACHE
/*
 * directory cache for 'map'
 */
struct autofs_rddir_cache {
	char			*map;
	struct off_tbl		*offtp;
	ulong_t			bucket_size;
	time_t			ttl;
	struct dir_entry	*entp;
	mutex_t			lock;		/* protects 'in_use' field */
	int			in_use;		/* # threads referencing it */
	rwlock_t		rwlock;		/* protects 'full' and 'next' */
	int			full;		/* full == 1 when cache full */
	struct autofs_rddir_cache	*next;
};

#define	RDDIR_CACHE_TIME	300		/* in seconds */

#endif /* NO_RDDIR_CACHE */

/*
 * structure used to maintain address list for localhost
 */

struct myaddrs {
	struct sockaddr_in sin;
	struct myaddrs *myaddrs_next;
};

/*
 * structure used to pass commands to the door servers
 */

typedef struct command {
	char file[MAXPATHLEN];
	char argv[ARGV_MAX][MAXOPTSLEN];
	char key[MAXOPTSLEN];
	int console;
} command_t;

/*
 * globally visible door_server file descriptor
 */
extern int did_exec_map;
extern int did_fork_exec;

extern time_t timenow;	/* set at start of processing of each RPC call */
extern char self[];
extern int verbose;
extern int trace;
extern int automountd_nobrowse;
extern struct autodir *dir_head;
extern struct autodir *dir_tail;
extern struct mntlist *current_mounts;
struct mounta;			/* defined in sys/vfs.h */
extern struct myaddrs *myaddrs_head;

extern rwlock_t	cache_lock;
extern rwlock_t portmap_cache_lock;
extern rwlock_t autofs_rddir_cache_lock;

extern mutex_t cleanup_lock;
extern cond_t cleanup_start_cv;
extern cond_t cleanup_done_cv;

/*
 * mnttab handling routines
 */
extern void free_mapent(struct mapent *);
extern struct mntlist *getmntlist(void);
extern dev_t get_devid(struct extmnttab *);

/*
 * utilities
 */
extern struct mapent *parse_entry(char *, char *, char *, struct mapline *,
				char *, uint_t, bool_t);
extern int macro_expand(char *, char *, char *, int);
extern void unquote(char *, char *);
extern void unbracket(char **);
extern void trim(char *);
extern char *get_line(FILE *, char *, char *, int);
extern int getword(char *, char *, char **, char **, char, int);
extern int get_retry(char *);
extern int str_opt(struct mnttab *, char *, char **);
extern void put_automountd_env(void);
extern void dirinit(char *, char *, char *, int, char **, char ***);
extern void pr_msg(const char *, ...);
extern void trace_prt(int, char *, ...);
extern void free_autofs_args(autofs_args *);
extern void free_nfs_args(struct nfs_args *);
extern void free_mounta(struct mounta *);

extern int nopt(struct mnttab *, char *, int *);
extern int set_versrange(rpcvers_t, rpcvers_t *, rpcvers_t *);
extern enum clnt_stat pingnfs(char *, int, rpcvers_t *, rpcvers_t,
	ushort_t, bool_t, char *, char *);

extern void *autofs_get_buffer(size_t);
extern int self_check(char *);
extern int do_mount1(char *, char *, char *, char *, char *, uint_t, uid_t,
	action_list **, int);
extern int do_lookup1(char *, char *, char *, char *, char *, uint_t, uid_t,
	autofs_action_t *, struct linka *);
extern int do_unmount1(umntrequest *);
extern int do_readdir(autofs_rddirargs *, autofs_rddirres *);
extern int nfsunmount(struct mnttab *);
extern int loopbackmount(char *, char *, char *, int);
extern int mount_nfs(struct mapent *, char *, char *, int, uid_t,
	action_list **);
extern int mount_autofs(struct mapent *, char *, action_list *,
	char *rootp, char *subdir, char *key);
extern int mount_generic(char *, char *, char *, char *, int);
extern enum clnt_stat nfs_cast(struct mapfs *, struct mapfs **, int);

extern bool_t hasrestrictopt(char *);

#ifndef NO_RDDIR_CACHE
/*
 * readdir handling routines
 */
extern char *auto_rddir_malloc(unsigned);
extern char *auto_rddir_strdup(const char *);
extern struct dir_entry *btree_lookup(struct dir_entry *, char *);
extern void btree_enter(struct dir_entry **, struct dir_entry *);
extern int add_dir_entry(char *, struct dir_entry **, struct dir_entry **);
extern void cache_cleanup(void);
extern int autofs_rddir_cache_lookup(char *, struct autofs_rddir_cache **);
extern struct dir_entry *rddir_entry_lookup(char *, struct dir_entry *);
#endif /* NO_RDDIR_CACHE */

/*
 * generic interface to specific name service functions
 */
extern void ns_setup(char **, char ***);
extern int getmapent(char *, char *, struct mapline *, char **, char ***,
			bool_t *, bool_t);
extern int getmapkeys(char *, struct dir_entry **, int *, int *, char **,
			char ***, uid_t);
extern int loadmaster_map(char *, char *, char **, char ***);
extern int loaddirect_map(char *, char *, char *, char **, char ***);

/*
 * these name service specific functions should not be
 * accessed directly, use the generic functions.
 */
extern void init_files(char **, char ***);
extern int getmapent_files(char *, char *, struct mapline *, char **, char ***,
				bool_t *, bool_t);
extern int loadmaster_files(char *, char *, char **, char ***);
extern int loaddirect_files(char *, char *, char *, char **, char ***);
extern int getmapkeys_files(char *, struct dir_entry **, int *, int *,
	char **, char ***);
extern int stack_op(int, char *, char **, char ***);

extern void init_nis(char **, char ***);
extern int getmapent_nis(char *, char *, struct mapline *, char **, char ***,
				bool_t *, bool_t);
extern int loadmaster_nis(char *, char *, char **, char ***);
extern int loaddirect_nis(char *, char *, char *, char **, char ***);
extern int getmapkeys_nis(char *, struct dir_entry **, int *, int *,
	char **, char ***);

/* Hammerhead: ns_ldap.c removed (libsldap chain removal, Phase 1). */


/*
 * end of name service specific functions
 */

/*
 * not defined in any header file
 */
extern int __clnt_bindresvport(CLIENT *);
extern int getnetmaskbynet(const struct in_addr, struct in_addr *);

/*
 * Hidden rpc functions
 */
extern int __nis_reset_state();
extern int __rpc_negotiate_uid(int);

/*
 * door_server functions to handle fork activity within the automounter
 */
void automountd_do_fork_exec(void *, char *, size_t, door_desc_t *, uint_t);
void automountd_do_exec_map(void *, char *, size_t, door_desc_t *, uint_t);

#ifdef __cplusplus
}
#endif

#endif	/* _AUTOMOUNT_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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) 1998,2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifdef	MALLOC_DEBUG
#include <stdlib.h>
#include <stdio.h>
#include <thread.h>
#include <synch.h>
#include <string.h>
#include <stdio.h>
#include <syslog.h>
#include <netdb.h>
#include <netdir.h>
#include <rpc/nettype.h>

/*
 * To use debugging facility, compile with * -DMALLOC_DEBUG.
 * You can do this by setting the environment variable
 * MALLOC_DEBUG to "-DMALLOC_DEBUG"
 *
 * To make automountd dump trace records (i.e. make it call check_leaks),
 * run:
 * 	make malloc_dump
 */

struct alloc_list
{
	char type[20];
	void *addr;
	int size;
	char file[80];
	int line;
	struct alloc_list *next;
};

static struct alloc_list *halist = NULL;
static mutex_t alloc_list_lock = DEFAULTMUTEX;

int
add_alloc(char *type, void *addr, size_t size, const char *file, int line)
{
	struct alloc_list *alist = NULL;

	/* allocate the list item */
	alist = (struct alloc_list *)malloc(sizeof (*alist));
	if (alist == NULL) {
		syslog(LOG_ERR, "add_alloc: out of memory\n");
		return (-1);
	}
	strcpy(alist->type, type);
	alist->addr = addr;
	alist->size = size;
	strcpy(alist->file, file);
	alist->line = line;

	/* add it to the head of the list */
	if (halist == NULL)
		alist->next = NULL;
	else
		alist->next = halist;
	halist = alist;
	return (0);
}

int
drop_alloc(const char *type, void *addr, const char *file, int line)
{
	struct alloc_list *alist, *alist_prev;

	alist = halist;
	while (alist != NULL) {
		if (addr == alist->addr) {
			if (alist == halist)
				halist = halist->next;
			else
				alist_prev->next = alist->next;
			free(alist);
			break;
		}
		alist_prev = alist;
		alist = alist->next;
	}

	if (alist == NULL) {
		syslog(LOG_ERR, "*** POSSIBLE CORRUPTION ****\n");
		syslog(LOG_ERR, "\tduplicate free, type %s, at %p in %s/%d\n",
		    type, addr, file, line);
		return (-1);
	}
	return (0);
}

void *
my_malloc(size_t size, const char *file, int line)
{
	void *addr;

	addr = (void *)malloc(size);
	if (addr == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("MALLOC", addr, size, file, line);
	mutex_unlock(&alloc_list_lock);
	return (addr);
}

void *
my_realloc(void *addr, size_t size, const char *file, int line)
{
	void *ptr;

	ptr = (void *)realloc(addr, size);
	if (ptr == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	drop_alloc("MALLOC", addr, file, line);
	add_alloc("MALLOC", ptr, size, file, line);
	mutex_unlock(&alloc_list_lock);

	return (ptr);
}

void
my_free(void *addr, const char *file, int line)
{
	mutex_lock(&alloc_list_lock);
	drop_alloc("MALLOC", addr, file, line);
	mutex_unlock(&alloc_list_lock);
	free(addr);
}

char *
my_strdup(const char *straddr, const char *file, int line)
{
	void *addr;
	size_t size;

	addr = strdup(straddr);
	if (addr == NULL)
		return (NULL);
	size = strlen(straddr);
	mutex_lock(&alloc_list_lock);
	add_alloc("STRDUP", addr, size, file, line);
	mutex_unlock(&alloc_list_lock);

	return ((char *)addr);
}

int
my_sethostent(int stay, const char *file, int line)
{
	(void) sethostent(stay);
	mutex_lock(&alloc_list_lock);
	add_alloc("SETHOSTENT", NULL, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (0);
}

int
my_endhostent(const char *file, int line)
{
	int ret;

	ret = endhostent();
	if (ret != 0)
		return (ret);
	mutex_lock(&alloc_list_lock);
	drop_alloc("SETHOSTENT", NULL, file, line);
	mutex_unlock(&alloc_list_lock);
	return (ret);
}

void *
my_setnetconfig(const char *file, int line)
{
	void *nconf;

	nconf = setnetconfig();
	if (nconf == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("SETNETCONFIG", nconf, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (nconf);
}

int
my_endnetconfig(void *nconf, const char *file, int line)
{
	int res;

	res = endnetconfig(nconf);
	if (res != 0)
		return (res);
	mutex_lock(&alloc_list_lock);
	drop_alloc("SETNETCONFIG", nconf, file, line);
	mutex_unlock(&alloc_list_lock);
	return (0);
}

void *
my_setnetpath(const char *file, int line)
{
	void *npath;

	npath = setnetpath();
	if (npath == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("SETNETPATH", npath, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (npath);
}

int
my_endnetpath(void *npath, const char *file, int line)
{
	int res;

	res = endnetpath(npath);
	if (res != 0)
		return (res);
	mutex_lock(&alloc_list_lock);
	drop_alloc("SETNETPATH", npath, file, line);
	mutex_unlock(&alloc_list_lock);
	return (0);
}

int
my_netdir_getbyname(
	struct netconfig *tp,
	struct nd_hostserv *serv,
	struct nd_addrlist **addrs,
	const char *file,
	int line)
{
	int res;

	res = netdir_getbyname(tp, serv, addrs);
	if (res != 0)
		return (res);
	mutex_lock(&alloc_list_lock);
	add_alloc("NETDIR_GETBYNAME", *addrs, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (0);
}

void
my_netdir_free(void *ptr, int type, const char *file, int line)
{
	netdir_free(ptr, type);
	mutex_lock(&alloc_list_lock);
	drop_alloc("NETDIR_GETBYNAME", ptr, file, line);
	mutex_unlock(&alloc_list_lock);
}

struct hostent *
my_getipnodebyname(
	const char *name,
	int af,
	int flags,
	int *error_num,
	char *file,
	int line)
{
	struct hostent *res;

	res = getipnodebyname(name, af, flags, error_num);
	if (res == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("GETIPNODEBYNAME", res, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (res);
}

void
my_freehostent(struct hostent *hent, char *file, int line)
{
	freehostent(hent);
	mutex_lock(&alloc_list_lock);
	drop_alloc("GETIPNODEBYNAME", hent, file, line);
	mutex_unlock(&alloc_list_lock);
}

struct netconfig *
my_getnetconfigent(char *netid, char *file, int line)
{
	struct netconfig *res;

	res = getnetconfigent(netid);
	if (res == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("GETNETCONFIGENT", res, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (res);
}

void
my_freenetconfigent(struct netconfig *netp, char *file, int line)
{
	freenetconfigent(netp);
	mutex_lock(&alloc_list_lock);
	drop_alloc("GETNETCONFIGENT", netp, file, line);
	mutex_unlock(&alloc_list_lock);
}

void *
my__rpc_setconf(char *nettype, char *file, int line)
{
	void *res;

	res = __rpc_setconf(nettype);
	if (res == NULL)
		return (NULL);
	mutex_lock(&alloc_list_lock);
	add_alloc("RPC_SETCONF", res, 0, file, line);
	mutex_unlock(&alloc_list_lock);
	return (res);
}

void
my__rpc_endconf(void *vhandle, char *file, int line)
{
	__rpc_endconf(vhandle);
	mutex_lock(&alloc_list_lock);
	drop_alloc("RPC_SETCONF", vhandle, file, line);
	mutex_unlock(&alloc_list_lock);
}

extern void flush_caches();
void
_flush_caches()
{
}
#pragma weak    flush_caches = _flush_caches

void
check_leaks(char *filename)
{
	struct alloc_list *alist;

	FILE *fp;
	fp = fopen(filename, "a");
	if (fp == NULL) {
		syslog(LOG_ERR, "check_leaks, could not open file: %s",
			filename);
		return;
	}

	flush_caches();
	fprintf(fp, "*** POSSIBLE LEAKS ****\n");
	mutex_lock(&alloc_list_lock);
	alist = halist;
	while (alist != NULL) {
		fprintf(fp, "\t%s: %d bytes at %p in %s/%d\n",
			alist->type, alist->size, alist->addr,
			alist->file, alist->line);
		alist = alist->next;
	}
	mutex_unlock(&alloc_list_lock);

	(void) fclose(fp);
}
#else
/*
 * To prevent a compiler warning.
 */
static char filler;
#endif
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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) 1998,2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifndef	_MY_ALLOC_H
#define	_MY_ALLOC_H

#ifdef __cplusplus
extern "C" {
#endif

#include <netdb.h>
#include <netdir.h>
#include <rpc/nettype.h>

int add_alloc(char *, void *, size_t, const char *, int);
int drop_alloc(const char *, void *, const char *, int);

void *my_malloc(size_t, const char *, int);
void *my_realloc(void *, size_t, const char *, int);
void my_free(void *, const char *, int);
char *my_strdup(const char *, const char *, int);

int  my_sethostent(int, const char *, int);
int  my_endhostent(const char *, int);

void *my_setnetconfig(const char *, int);
int  my_endnetconfig(void *, const char *, int);

void *my_setnetpath(const char *, int);
int  my_endnetpath(void *, const char *, int);

int  my_netdir_getbyname(struct netconfig *, struct nd_hostserv *,
	struct nd_addrlist **, const char *, int);
int  my_netdir_free(void *, int, const char *, int);

struct hostent *my_getipnodebyname(const char *, int, int, int *, char *, int);
void my_freehostent(struct hostent *, char *, int);

struct netconfig *my_getnetconfigent(char *, char *, int);
void  my_freenetconfigent(struct netconfig *, char *, int);

void *my__rpc_setconf(char *, char *, int);
void my__rpc_endconf(void *, char *, int);

void check_leaks(char *);

#define	AUTOFS_DUMP_DEBUG	1000000
#define	free(a)			my_free(a, __FILE__, __LINE__)
#define	malloc(a)		my_malloc(a, __FILE__, __LINE__)
#define	realloc(a, s)		my_realloc(a, s, __FILE__, __LINE__)
#define	strdup(a)		my_strdup(a, __FILE__, __LINE__)

#define	sethostent(s)		my_sethostent(s, __FILE__, __LINE__)
#define	endhostent()		my_endhostent(__FILE__, __LINE__)

#define	setnetconfig()		my_setnetconfig(__FILE__, __LINE__)
#define	endnetconfig(v)		my_endnetconfig(v, __FILE__, __LINE__)

#define	setnetpath()		my_setnetpath(__FILE__, __LINE__)
#define	endnetpath(v)		my_endnetpath(v, __FILE__, __LINE__)

#define	netdir_getbyname(t, s, a)	\
	my_netdir_getbyname(t, s, a, __FILE__, __LINE__)
#define	netdir_free(a, t)	my_netdir_free(a, t, __FILE__, __LINE__)

#define	getipnodebyname(n, a, f, e)	\
	my_getipnodebyname(n, a, f, e, __FILE__, __LINE__)
#define	 freehostent(h)		my_freehostent(h, __FILE__, __LINE__)

#define	getnetconfigent(n)	my_getnetconfigent(n, __FILE__, __LINE__)
#define	freenetconfigent(n)	my_freenetconfigent(n, __FILE__, __LINE__)

#ifdef __cplusplus
}
#endif

#endif	/* _MY_ALLOC_H */
#!/usr/bin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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) 1999 by Sun Microsystems, Inc.
# All rights reserved.
#
#ident	"%Z%%M%	%I%	%E% SMI"

# dfshares is a server utility but autofs is a client
# filesystem, so dfshares for autofs will do nothing.
# This utility is needed because autofs is included in
# /etc/dfs/fstypes.

exit 0
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 *	autofs mount.c
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/tiuser.h>
#include <string.h>
#include <fslib.h>
#include <errno.h>
#include <rpcsvc/daemon_utils.h>
#include "automount.h"

#define	MNTTAB_OPTS	"ignore,nest"

static void usage();
static void process_opts(char *options, int *directp);
static char *concat_opts(const char *opts1, const char *opts2);
static int  ro_given(char *options);

/*
 * list of support services needed
 */
static char	*service_list[] = { AUTOMOUNTD, NULL };

int
main(int argc, char *argv[])
{
	int error;
	int c;
	int mntflags = 0;
	int nmflg = 0;
	int roflg = 0;
	char *mntpnt, *mapname;
	struct utsname utsname;
	char autofs_addr[MAXADDRLEN];
	struct autofs_args fni;
	char *options = "";
	int mount_timeout = AUTOFS_MOUNT_TIMEOUT;
	char obuf[MAX_MNTOPT_STR];

	while ((c = getopt(argc, argv, "o:mrq")) != EOF) {
		switch (c) {
		case '?':
			usage();
			exit(1);
			/* NOTREACHED */

		case 'o':
			options = optarg;
			break;

		case 'm':
			nmflg++;
			break;
		case 'r':	/* converted to -o ro always */
			roflg++;
			break;
		/*
		 *  The "quiet" flag can be ignored, since this
		 *  program never complains about invalid -o options
		 *  anyway.
		 */
		case 'q':
			break;

		default:
			usage();
		}
	}
	if (argc - optind != 2)
		usage();

	mapname = argv[optind];
	mntpnt  = argv[optind + 1];

	if (strcmp(mntpnt, "/-") == 0) {
		(void) fprintf(stderr, "invalid mountpoint: /-\n");
		exit(1);
	}

	if (uname(&utsname) < 0) {
		perror("uname");
		exit(1);
	}
	(void) strcpy(autofs_addr, utsname.nodename);
	(void) strcat(autofs_addr, ".autofs");

	process_opts(options, &fni.direct);

	if (roflg && !ro_given(options))
		options = concat_opts(options, "ro");

	fni.addr.buf	= autofs_addr;
	fni.addr.len	= strlen(fni.addr.buf);
	fni.addr.maxlen	= fni.addr.len;
	fni.path	= mntpnt;
	fni.opts	= options;
	fni.map		= mapname;
	fni.subdir	= "";
	if (fni.direct)
		fni.key = mntpnt;
	else
		fni.key	= "";
	fni.mount_to	= mount_timeout;
	fni.rpc_to	= AUTOFS_RPC_TIMEOUT;

	strcpy(obuf, options);
	if (*obuf != '\0')
		strcat(obuf, ",");
	strcat(obuf,
		fni.direct ? MNTTAB_OPTS ",direct" : MNTTAB_OPTS ",indirect");

	/*
	 * enable services as needed.
	 */
	_check_services(service_list);

	error = mount(fni.map, mntpnt, mntflags | MS_DATA | MS_OPTIONSTR,
		MNTTYPE_AUTOFS, &fni, sizeof (fni), obuf, MAX_MNTOPT_STR);
	if (error < 0) {
		perror("autofs mount");
		exit(1);
	}
	return (0);
}

static void
usage()
{
	(void) fprintf(stderr,
	    "Usage: autofs mount [-r] [-o opts]  map  dir\n");
	exit(1);
}

/*
 * Remove pseudo-options "direct", "indirect", "nest", and "ignore" from
 * option list.  Set *directp to 1 if "direct" is found, and 0 otherwise
 * (mounts are indirect by default).  If both "direct" and "indirect" are
 * found, the last one wins.
 */
static void
process_opts(char *options, int *directp)
{
	char *opt;
	char *opts;

	if ((opts = strdup(options)) == NULL) {
		(void) fprintf(stderr,
				"autofs mount: memory allocation failed\n");
		exit(1);
	}
	options[0] = '\0';
	*directp = 0;

	while ((opt = strtok(opts, ",")) != NULL) {
		opts = NULL;
		while (isspace(*opt)) {
			opt++;
		}
		if (strcmp(opt, "direct") == 0) {
			*directp = 1;
		} else if (strcmp(opt, "indirect") == 0) {
			*directp = 0;
		} else if ((strcmp(opt, "nest") != 0) &&
				(strcmp(opt, "ignore") != 0)) {
			if (options[0] != '\0') {
				(void) strcat(options, ",");
			}
			(void) strcat(options, opt);
		}
	};
}

/*
 * Concatenate two options strings, with a comma between them.
 */
static char *
concat_opts(const char *opts1, const char *opts2)
{
	char *opts = malloc(strlen(opts1) + strlen(opts2) + 2);
	if (opts == NULL) {
		(void) fprintf(stderr,
			"autofs mount: memory allocation failed\n");
		exit(1);
	}
	strcpy(opts, opts1);
	if (opts1[0] != '\0' && opts2[0] != '\0') {
		strcat(opts, ",");
	}
	return (strcat(opts, opts2));
}

/*
 * check the options string for 'ro' options
 * if present returns 1 otherwise return 0;
 */

static int
ro_given(char *options)
{
	char	*op = options;

	if (!*op)
		return (0);

	while (op != 0) {
		if (*op == 'r' && *(op+1) == 'o' &&
			(*(op+2) == ',' || *(op+2) == '\0'))
			return (1);

		if ((op = strchr(op, ',')) != NULL)
			op++;
	}


	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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
 */
/*
 *	nfs_cast.c : broadcast to a specific group of NFS servers
 *
 *      Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 *      Use is subject to license terms.
 */

#include <stdio.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdlib.h>
#include <rpc/rpc.h>
#include <rpc/clnt_soc.h>
#include <rpc/nettype.h>
#include <rpc/pmap_prot.h>
#include <netconfig.h>
#include <netdir.h>
#include <nfs/nfs.h>
#define	NFSCLIENT
#include <locale.h>
#include "automount.h"

#define	PENALTY_WEIGHT    100000

struct tstamps {
	struct tstamps	*ts_next;
	int		ts_penalty;
	int		ts_inx;
	int		ts_rcvd;
	struct timeval	ts_timeval;
};

/* A list of addresses - all belonging to the same transport */

struct addrs {
	struct addrs		*addr_next;
	struct mapfs		*addr_mfs;
	struct nd_addrlist	*addr_addrs;
	struct tstamps		*addr_if_tstamps;
};

/* A list of connectionless transports */

struct transp {
	struct transp		*tr_next;
	int			tr_fd;
	char			*tr_device;
	struct t_bind		*tr_taddr;
	struct addrs		*tr_addrs;
};

/* A list of map entries and their roundtrip times, for sorting */

struct sm {
	struct mapfs *mfs;
	struct timeval timeval;
};

static void free_transports(struct transp *);
static void calc_resp_time(struct timeval *);
static struct mapfs *sort_responses(struct transp *);
static int host_sm(const void *, const void *b);
static int time_sm(const void *, const void *b);
extern struct mapfs *add_mfs(struct mapfs *, int, struct mapfs **,
	struct mapfs **);

/*
 * This routine is designed to be able to "ping"
 * a list of hosts and create a list of responding
 * hosts sorted by response time.
 * This must be done without any prior
 * contact with the host - therefore the "ping"
 * must be to a "well-known" address.  The outstanding
 * candidate here is the address of "rpcbind".
 *
 * A response to a ping is no guarantee that the host
 * is running NFS, has a mount daemon, or exports
 * the required filesystem.  If the subsequent
 * mount attempt fails then the host will be marked
 * "ignore" and the host list will be re-pinged
 * (sans the bad host). This process continues
 * until a successful mount is achieved or until
 * there are no hosts left to try.
 */
enum clnt_stat
nfs_cast(struct mapfs *mfs_in, struct mapfs **mfs_out, int timeout)
{
	enum clnt_stat stat;
	AUTH *sys_auth = authsys_create_default();
	XDR xdr_stream;
	register XDR *xdrs = &xdr_stream;
	int outlen;
	int if_inx;
	int tsec;
	int flag;
	int sent, addr_cnt, rcvd, if_cnt;
	fd_set readfds, mask;
	register ulong_t xid;		/* xid - unique per addr */
	register int i;
	struct rpc_msg msg;
	struct timeval t, rcv_timeout;
	char outbuf[UDPMSGSIZE], inbuf[UDPMSGSIZE];
	struct t_unitdata t_udata, t_rdata;
	struct nd_hostserv hs;
	struct nd_addrlist *retaddrs;
	struct transp *tr_head;
	struct transp *trans, *prev_trans;
	struct addrs *a, *prev_addr;
	struct tstamps *ts, *prev_ts;
	NCONF_HANDLE *nc = NULL;
	struct netconfig *nconf;
	struct rlimit rl;
	int dtbsize;
	struct mapfs *mfs;

	/*
	 * For each connectionless transport get a list of
	 * host addresses.  Any single host may have
	 * addresses on several transports.
	 */
	addr_cnt = sent = rcvd = 0;
	tr_head = NULL;
	FD_ZERO(&mask);

	/*
	 * Set the default select size to be the maximum FD_SETSIZE, unless
	 * the current rlimit is lower.
	 */
	dtbsize = FD_SETSIZE;
	if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
		if (rl.rlim_cur < FD_SETSIZE)
			dtbsize = rl.rlim_cur;
	}

	prev_trans = NULL;
	prev_addr = NULL;
	prev_ts = NULL;
	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {

		if (trace > 2)
			trace_prt(1, "nfs_cast: host=%s\n", mfs->mfs_host);

		nc = setnetconfig();
		if (nc == NULL) {
			stat = RPC_CANTSEND;
			goto done_broad;
		}
		while (nconf = getnetconfig(nc)) {
			if (!(nconf->nc_flag & NC_VISIBLE) ||
			    nconf->nc_semantics != NC_TPI_CLTS ||
			    (strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0))
				continue;
			trans = (struct transp *)malloc(sizeof (*trans));
			if (trans == NULL) {
				syslog(LOG_ERR, "no memory");
				stat = RPC_CANTSEND;
				goto done_broad;
			}
			(void) memset(trans, 0, sizeof (*trans));
			if (tr_head == NULL)
				tr_head = trans;
			else
				prev_trans->tr_next = trans;
			prev_trans = trans;

			trans->tr_fd = t_open(nconf->nc_device, O_RDWR, NULL);
			if (trans->tr_fd < 0) {
				syslog(LOG_ERR, "nfscast: t_open: %s:%m",
					nconf->nc_device);
				stat = RPC_CANTSEND;
				goto done_broad;
			}
			if (t_bind(trans->tr_fd, (struct t_bind *)NULL,
				(struct t_bind *)NULL) < 0) {
				syslog(LOG_ERR, "nfscast: t_bind: %m");
				stat = RPC_CANTSEND;
				goto done_broad;
			}
			trans->tr_taddr =
				/* LINTED pointer alignment */
			(struct t_bind *)t_alloc(trans->tr_fd, T_BIND, T_ADDR);
			if (trans->tr_taddr == (struct t_bind *)NULL) {
				syslog(LOG_ERR, "nfscast: t_alloc: %m");
				stat = RPC_SYSTEMERROR;
				goto done_broad;
			}

			trans->tr_device = nconf->nc_device;
			FD_SET(trans->tr_fd, &mask);

			if_inx = 0;
			hs.h_host = mfs->mfs_host;
			hs.h_serv = "rpcbind";
			if (netdir_getbyname(nconf, &hs, &retaddrs) == ND_OK) {

				/*
				 * If mfs->ignore is previously set for
				 * this map, clear it. Because a host can
				 * have either v6 or v4 address
				 */
				if (mfs->mfs_ignore == 1)
					mfs->mfs_ignore = 0;

				a = (struct addrs *)malloc(sizeof (*a));
				if (a == NULL) {
					syslog(LOG_ERR, "no memory");
					stat = RPC_CANTSEND;
					goto done_broad;
				}
				(void) memset(a, 0, sizeof (*a));
				if (trans->tr_addrs == NULL)
					trans->tr_addrs = a;
				else
					prev_addr->addr_next = a;
				prev_addr = a;
				a->addr_if_tstamps = NULL;
				a->addr_mfs = mfs;
				a->addr_addrs = retaddrs;
				if_cnt = retaddrs->n_cnt;
				while (if_cnt--) {
					ts = (struct tstamps *)
						malloc(sizeof (*ts));
					if (ts == NULL) {
						syslog(LOG_ERR, "no memory");
						stat = RPC_CANTSEND;
						goto done_broad;
					}
					(void) memset(ts, 0, sizeof (*ts));
					ts->ts_penalty = mfs->mfs_penalty;
					if (a->addr_if_tstamps == NULL)
						a->addr_if_tstamps = ts;
					else
						prev_ts->ts_next = ts;
					prev_ts = ts;
					ts->ts_inx = if_inx++;
					addr_cnt++;
				}
				break;
			} else {
				mfs->mfs_ignore = 1;
				if (verbose)
					syslog(LOG_ERR,
				"%s:%s address not known",
				mfs->mfs_host,
				strcmp(nconf->nc_proto, NC_INET)?"IPv6":"IPv4");
			}
		} /* while */

		endnetconfig(nc);
		nc = NULL;
	} /* for */
	if (addr_cnt == 0) {
		syslog(LOG_ERR, "nfscast: couldn't find addresses");
		stat = RPC_CANTSEND;
		goto done_broad;
	}

	(void) gettimeofday(&t, (struct timezone *)0);
	xid = (getpid() ^ t.tv_sec ^ t.tv_usec) & ~0xFF;
	t.tv_usec = 0;

	/* serialize the RPC header */

	msg.rm_direction = CALL;
	msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
	msg.rm_call.cb_prog = RPCBPROG;
	/*
	 * we can not use RPCBVERS here since it doesn't exist in 4.X,
	 * the fix to bug 1139883 has made the 4.X portmapper silent to
	 * version mismatches. This causes the RPC call to the remote
	 * portmapper to simply be ignored if it's not Version 2.
	 */
	msg.rm_call.cb_vers = PMAPVERS;
	msg.rm_call.cb_proc = NULLPROC;
	if (sys_auth == (AUTH *)NULL) {
		stat = RPC_SYSTEMERROR;
		goto done_broad;
	}
	msg.rm_call.cb_cred = sys_auth->ah_cred;
	msg.rm_call.cb_verf = sys_auth->ah_verf;
	xdrmem_create(xdrs, outbuf, sizeof (outbuf), XDR_ENCODE);
	if (! xdr_callmsg(xdrs, &msg)) {
		stat = RPC_CANTENCODEARGS;
		goto done_broad;
	}
	outlen = (int)xdr_getpos(xdrs);
	xdr_destroy(xdrs);

	t_udata.opt.len = 0;
	t_udata.udata.buf = outbuf;
	t_udata.udata.len = outlen;

	/*
	 * Basic loop: send packet to all hosts and wait for response(s).
	 * The response timeout grows larger per iteration.
	 * A unique xid is assigned to each address in order to
	 * correctly match the replies.
	 */
	for (tsec = 4; timeout > 0; tsec *= 2) {

		timeout -= tsec;
		if (timeout <= 0)
			tsec += timeout;

		rcv_timeout.tv_sec = tsec;
		rcv_timeout.tv_usec = 0;

		sent = 0;
		for (trans = tr_head; trans; trans = trans->tr_next) {
			for (a = trans->tr_addrs; a; a = a->addr_next) {
				struct netbuf *if_netbuf =
					a->addr_addrs->n_addrs;
				ts = a->addr_if_tstamps;
				if_cnt = a->addr_addrs->n_cnt;
				while (if_cnt--) {

					/*
					 * xid is the first thing in
					 * preserialized buffer
					 */
					/* LINTED pointer alignment */
					*((ulong_t *)outbuf) =
						htonl(xid + ts->ts_inx);
					(void) gettimeofday(&(ts->ts_timeval),
						(struct timezone *)0);
					/*
					 * Check if already received
					 * from a previous iteration.
					 */
					if (ts->ts_rcvd) {
						sent++;
						ts = ts->ts_next;
						continue;
					}

					t_udata.addr = *if_netbuf++;

					if (t_sndudata(trans->tr_fd,
							&t_udata) == 0) {
						sent++;
					}

					ts = ts->ts_next;
				}
			}
		}
		if (sent == 0) {		/* no packets sent ? */
			stat = RPC_CANTSEND;
			goto done_broad;
		}

		/*
		 * Have sent all the packets.  Now collect the responses...
		 */
		rcvd = 0;
	recv_again:
		msg.acpted_rply.ar_verf = _null_auth;
		msg.acpted_rply.ar_results.proc = xdr_void;
		readfds = mask;

		switch (select(dtbsize, &readfds,
			(fd_set *)NULL, (fd_set *)NULL, &rcv_timeout)) {

		case 0: /* Timed out */
			/*
			 * If we got at least one response in the
			 * last interval, then don't wait for any
			 * more.  In theory we should wait for
			 * the max weighting (penalty) value so
			 * that a very slow server has a chance to
			 * respond but this could take a long time
			 * if the admin has set a high weighting
			 * value.
			 */
			if (rcvd > 0)
				goto done_broad;

			stat = RPC_TIMEDOUT;
			continue;

		case -1:  /* some kind of error */
			if (errno == EINTR)
				goto recv_again;
			syslog(LOG_ERR, "nfscast: select: %m");
			if (rcvd == 0)
				stat = RPC_CANTRECV;
			goto done_broad;

		}  /* end of select results switch */

		for (trans = tr_head; trans; trans = trans->tr_next) {
			if (FD_ISSET(trans->tr_fd, &readfds))
				break;
		}
		if (trans == NULL)
			goto recv_again;

	try_again:
		t_rdata.addr = trans->tr_taddr->addr;
		t_rdata.udata.buf = inbuf;
		t_rdata.udata.maxlen = sizeof (inbuf);
		t_rdata.udata.len = 0;
		t_rdata.opt.len = 0;
		if (t_rcvudata(trans->tr_fd, &t_rdata, &flag) < 0) {
			if (errno == EINTR)
				goto try_again;
			syslog(LOG_ERR, "nfscast: t_rcvudata: %s:%m",
				trans->tr_device);
			stat = RPC_CANTRECV;
			continue;
		}
		if (t_rdata.udata.len < sizeof (ulong_t))
			goto recv_again;
		if (flag & T_MORE) {
			syslog(LOG_ERR,
				"nfscast: t_rcvudata: %s: buffer overflow",
				trans->tr_device);
			goto recv_again;
		}

		/*
		 * see if reply transaction id matches sent id.
		 * If so, decode the results.
		 * Note: received addr is ignored, it could be
		 * different from the send addr if the host has
		 * more than one addr.
		 */
		xdrmem_create(xdrs, inbuf, (uint_t)t_rdata.udata.len,
								XDR_DECODE);
		if (xdr_replymsg(xdrs, &msg)) {
		    if (msg.rm_reply.rp_stat == MSG_ACCEPTED &&
			(msg.rm_xid & ~0xFF) == xid) {
			struct addrs *curr_addr;

			i = msg.rm_xid & 0xFF;
			for (curr_addr = trans->tr_addrs; curr_addr;
			    curr_addr = curr_addr->addr_next) {
			    for (ts = curr_addr->addr_if_tstamps; ts;
				ts = ts->ts_next)
				if (ts->ts_inx == i && !ts->ts_rcvd) {
					ts->ts_rcvd = 1;
					calc_resp_time(&ts->ts_timeval);
					stat = RPC_SUCCESS;
					rcvd++;
					break;
				}
			}
		    } /* otherwise, we just ignore the errors ... */
		}
		xdrs->x_op = XDR_FREE;
		msg.acpted_rply.ar_results.proc = xdr_void;
		(void) xdr_replymsg(xdrs, &msg);
		XDR_DESTROY(xdrs);
		if (rcvd == sent)
			goto done_broad;
		else
			goto recv_again;
	}
	if (!rcvd)
		stat = RPC_TIMEDOUT;

done_broad:
	if (rcvd) {
		*mfs_out = sort_responses(tr_head);
		stat = RPC_SUCCESS;
	}
	if (nc)
		endnetconfig(nc);
	free_transports(tr_head);
	AUTH_DESTROY(sys_auth);
	return (stat);
}

/*
 * Go through all the responses and sort fastest to slowest.
 * Note that any penalty is added to the response time - so the
 * fastest response isn't necessarily the one that arrived first.
 */
static struct mapfs *
sort_responses(trans)
	struct transp *trans;
{
	struct transp *t;
	struct addrs *a;
	struct tstamps *ti;
	int i, size = 0, allocsize = 10;
	struct mapfs *p, *mfs_head = NULL, *mfs_tail = NULL;
	struct sm *buffer;

	buffer = (struct sm *)malloc(allocsize * sizeof (struct sm));
	if (!buffer) {
		syslog(LOG_ERR, "sort_responses: malloc error.\n");
		return (NULL);
	}

	for (t = trans; t; t = t->tr_next) {
		for (a = t->tr_addrs; a; a = a->addr_next) {
			for (ti = a->addr_if_tstamps;
				ti; ti = ti->ts_next) {
				if (!ti->ts_rcvd)
					continue;
				ti->ts_timeval.tv_usec +=
					(ti->ts_penalty * PENALTY_WEIGHT);
				if (ti->ts_timeval.tv_usec >= 1000000) {
					ti->ts_timeval.tv_sec +=
					(ti->ts_timeval.tv_usec / 1000000);
					ti->ts_timeval.tv_usec =
					(ti->ts_timeval.tv_usec % 1000000);
				}

				if (size >= allocsize) {
					allocsize += 10;
					buffer = (struct sm *)realloc(buffer,
					    allocsize * sizeof (struct sm));
					if (!buffer) {
						syslog(LOG_ERR,
					    "sort_responses: malloc error.\n");
						return (NULL);
					}
				}
				buffer[size].timeval = ti->ts_timeval;
				buffer[size].mfs = a->addr_mfs;
				size++;
			}
		}
	}

#ifdef DEBUG
	if (trace > 3) {
		trace_prt(1, "  sort_responses: before host sort:\n");
		for (i = 0; i < size; i++)
			trace_prt(1, "    %s %d.%d\n", buffer[i].mfs->mfs_host,
			buffer[i].timeval.tv_sec, buffer[i].timeval.tv_usec);
		trace_prt(0, "\n");
	}
#endif

	qsort((void *)buffer, size, sizeof (struct sm), host_sm);

	/*
	 * Cope with multiply listed hosts  by choosing first time
	 */
	for (i = 1; i < size; i++) {
#ifdef DEBUG
		if (trace > 3) {
			trace_prt(1, "  sort_responses: comparing %s and %s\n",
				buffer[i-1].mfs->mfs_host,
				buffer[i].mfs->mfs_host);
		}
#endif
		if (strcmp(buffer[i-1].mfs->mfs_host,
		    buffer[i].mfs->mfs_host) == 0)
			memcpy(&buffer[i].timeval, &buffer[i-1].timeval,
				sizeof (struct timeval));
	}
	if (trace > 3)
		trace_prt(0, "\n");

#ifdef DEBUG
	if (trace > 3) {
		trace_prt(1, "  sort_responses: before time sort:\n");
		for (i = 0; i < size; i++)
			trace_prt(1, "    %s %d.%d\n", buffer[i].mfs->mfs_host,
			buffer[i].timeval.tv_sec, buffer[i].timeval.tv_usec);
		trace_prt(0, "\n");
	}
#endif

	qsort((void *)buffer, size, sizeof (struct sm), time_sm);

#ifdef DEBUG
	if (trace > 3) {
		trace_prt(1, "  sort_responses: after sort:\n");
		for (i = 0; i < size; i++)
			trace_prt(1, "    %s %d.%d\n", buffer[i].mfs->mfs_host,
			buffer[i].timeval.tv_sec, buffer[i].timeval.tv_usec);
		trace_prt(0, "\n");
	}
#endif

	for (i = 0; i < size; i++) {
#ifdef DEBUG
		if (trace > 3) {
			trace_prt(1, "  sort_responses: adding %s\n",
				buffer[i].mfs->mfs_host);
		}
#endif
		p = add_mfs(buffer[i].mfs, 0, &mfs_head, &mfs_tail);
		if (!p)
			return (NULL);
	}
	free(buffer);

	return (mfs_head);
}


/*
 * Comparison routines called by qsort(3).
 */
static int host_sm(const void *a, const void *b)
{
	return (strcmp(((struct sm *)a)->mfs->mfs_host,
			((struct sm *)b)->mfs->mfs_host));
}

static int time_sm(const void *a, const void *b)
{
	if (timercmp(&(((struct sm *)a)->timeval),
	    &(((struct sm *)b)->timeval), < /* cstyle */))
		return (-1);
	else if (timercmp(&(((struct sm *)a)->timeval),
	    &(((struct sm *)b)->timeval), > /* cstyle */))
		return (1);
	else
		return (0);
}

/*
 * Given send_time which is the time a request
 * was transmitted to a server, subtract it
 * from the time "now" thereby converting it
 * to an elapsed time.
 */
static void
calc_resp_time(send_time)
struct timeval *send_time;
{
	struct timeval time_now;

	(void) gettimeofday(&time_now, (struct timezone *)0);
	if (time_now.tv_usec <  send_time->tv_usec) {
		time_now.tv_sec--;
		time_now.tv_usec += 1000000;
	}
	send_time->tv_sec = time_now.tv_sec - send_time->tv_sec;
	send_time->tv_usec = time_now.tv_usec - send_time->tv_usec;
}

static void
free_transports(trans)
	struct transp *trans;
{
	struct transp *t, *tmpt = NULL;
	struct addrs *a, *tmpa = NULL;
	struct tstamps *ts, *tmpts = NULL;

	for (t = trans; t; t = tmpt) {
		if (t->tr_taddr)
			(void) t_free((char *)t->tr_taddr, T_BIND);
		if (t->tr_fd > 0)
			(void) t_close(t->tr_fd);
		for (a = t->tr_addrs; a; a = tmpa) {
			for (ts = a->addr_if_tstamps; ts; ts = tmpts) {
				tmpts = ts->ts_next;
				free(ts);
			}
			(void) netdir_free((char *)a->addr_addrs, ND_ADDRLIST);
			tmpa = a->addr_next;
			free(a);
		}
		tmpt = t->tr_next;
		free(t);
	}
}
/*
 * 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
 */
/*
 *	ns_files.c
 *
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <string.h>
#include <ctype.h>
#include <nsswitch.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>
#include <thread.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <synch.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <strings.h>
#include "automount.h"

int did_exec_map;
static int read_execout(char *, char **, char *, char *, int);
static int call_read_execout(char *, char *, char *, int);
static FILE *file_open(char *, char *, char **, char ***);

/*
 * Initialize the stack
 */
void
init_files(char **stack, char ***stkptr)
{
	/*
	 * The call is bogus for automountd since the stack is
	 * is more appropriately initialized in the thread-private
	 * routines
	 */
	if (stack == NULL && stkptr == NULL)
		return;
	(void) stack_op(INIT, NULL, stack, stkptr);
}

int
getmapent_files(char *key, char *mapname, struct mapline *ml,
    char **stack, char ***stkptr, bool_t *iswildcard, bool_t isrestricted)
{
	int nserr;
	FILE *fp;
	char word[MAXPATHLEN+1], wordq[MAXPATHLEN+1];
	char linebuf[LINESZ], lineqbuf[LINESZ];
	char *lp, *lq;
	struct stat stbuf;
	char fname[MAXFILENAMELEN]; /* /etc prepended to mapname if reqd */
	int syntaxok = 1;

	if (iswildcard)
		*iswildcard = FALSE;
	if ((fp = file_open(mapname, fname, stack, stkptr)) == NULL) {
		nserr = __NSW_UNAVAIL;
		goto done;
	}

	if (stat(fname, &stbuf) < 0) {
		nserr = __NSW_UNAVAIL;
		goto done;
	}

	/*
	 * If the file has its execute bit on then
	 * assume it's an executable map.
	 * Execute it and pass the key as an argument.
	 * Expect to get a map entry on the stdout.
	 * Ignore the "x" bit on restricted maps.
	 */
	if (!isrestricted && (stbuf.st_mode & S_IXUSR)) {
		int rc;

		if (trace > 1) {
			trace_prt(1, "\tExecutable map: map=%s key=%s\n",
			    fname, key);
		}

		rc = call_read_execout(key, fname, ml->linebuf, LINESZ);

		if (rc != 0) {
			nserr = __NSW_UNAVAIL;
			goto done;
		}

		if (strlen(ml->linebuf) == 0) {
			nserr = __NSW_NOTFOUND;
			goto done;
		}

		unquote(ml->linebuf, ml->lineqbuf);
		nserr = __NSW_SUCCESS;
		goto done;
	}


	/*
	 * It's just a normal map file.
	 * Search for the entry with the required key.
	 */
	for (;;) {
		lp = get_line(fp, fname, linebuf, sizeof (linebuf));
		if (lp == NULL) {
			nserr = __NSW_NOTFOUND;
			goto done;
		}
		if (verbose && syntaxok && isspace(*(uchar_t *)lp)) {
			syntaxok = 0;
			syslog(LOG_ERR,
			    "leading space in map entry \"%s\" in %s",
			    lp, mapname);
		}
		lq = lineqbuf;
		unquote(lp, lq);
		if ((getword(word, wordq, &lp, &lq, ' ', sizeof (word))
		    == -1) || (word[0] == '\0'))
			continue;
		if (strcmp(word, key) == 0)
			break;
		if (word[0] == '*' && word[1] == '\0') {
			if (iswildcard)
				*iswildcard = TRUE;
			break;
		}
		if (word[0] == '+') {
			nserr = getmapent(key, word+1, ml, stack, stkptr,
			    iswildcard, isrestricted);
			if (nserr == __NSW_SUCCESS)
				goto done;
			continue;
		}

		/*
		 * sanity check each map entry key against
		 * the lookup key as the map is searched.
		 */
		if (verbose && syntaxok) { /* sanity check entry */
			if (*key == '/') {
				if (*word != '/') {
					syntaxok = 0;
					syslog(LOG_ERR, "bad key \"%s\" in "
					    "direct map %s\n", word, mapname);
				}
			} else {
				if (strchr(word, '/')) {
					syntaxok = 0;
					syslog(LOG_ERR, "bad key \"%s\" in "
					    "indirect map %s\n", word, mapname);
				}
			}
		}
	}

	(void) strcpy(ml->linebuf, lp);
	(void) strcpy(ml->lineqbuf, lq);
	nserr = __NSW_SUCCESS;
done:
	if (fp) {
		(void) stack_op(POP, (char *)NULL, stack, stkptr);
		(void) fclose(fp);
	}


	return (nserr);
}

int
getmapkeys_files(char *mapname, struct dir_entry **list, int *error,
    int *cache_time, char **stack, char ***stkptr)
{
	FILE *fp = NULL;
	char word[MAXPATHLEN+1], wordq[MAXPATHLEN+1];
	char linebuf[LINESZ], lineqbuf[LINESZ];
	char *lp, *lq;
	struct stat stbuf;
	char fname[MAXFILENAMELEN]; /* /etc prepended to mapname if reqd */
	int syntaxok = 1;
	int nserr;
	struct dir_entry *last = NULL;

	if (trace > 1)
		trace_prt(1, "getmapkeys_files %s\n", mapname);

	*cache_time = RDDIR_CACHE_TIME;
	if ((fp = file_open(mapname, fname, stack, stkptr)) == NULL) {
		*error = ENOENT;
		nserr = __NSW_UNAVAIL;
		goto done;
	}
	if (fseek(fp, 0L, SEEK_SET) == -1) {
		*error = ENOENT;
		nserr = __NSW_UNAVAIL;
		goto done;
	}

	if (stat(fname, &stbuf) < 0) {
		*error = ENOENT;
		nserr = __NSW_UNAVAIL;
		goto done;
	}

	/*
	 * If the file has its execute bit on then
	 * assume it's an executable map.
	 * I don't know how to list executable maps, return
	 * an empty map.
	 */
	if (stbuf.st_mode & S_IXUSR) {
		*error = 0;
		nserr = __NSW_SUCCESS;
		goto done;
	}
	/*
	 * It's just a normal map file.
	 * List entries one line at a time.
	 */
	for (;;) {
		lp = get_line(fp, fname, linebuf, sizeof (linebuf));
		if (lp == NULL) {
			nserr = __NSW_SUCCESS;
			goto done;
		}
		if (syntaxok && isspace(*(uchar_t *)lp)) {
			syntaxok = 0;
			syslog(LOG_ERR,
			    "leading space in map entry \"%s\" in %s",
			    lp, mapname);
		}
		lq = lineqbuf;
		unquote(lp, lq);
		if ((getword(word, wordq, &lp, &lq, ' ', MAXFILENAMELEN)
		    == -1) || (word[0] == '\0'))
			continue;
		/*
		 * Wildcard entries should be ignored and this should be
		 * the last entry read to corroborate the search through
		 * files, i.e., search for key until a wildcard is reached.
		 */
		if (word[0] == '*' && word[1] == '\0')
			break;
		if (word[0] == '+') {
			/*
			 * Name switch here
			 */
			getmapkeys(word+1, list, error, cache_time,
			    stack, stkptr, 0);
			/*
			 * the list may have been updated, therefore
			 * our 'last' may no longer be valid
			 */
			last = NULL;
			continue;
		}

		if (add_dir_entry(word, list, &last) != 0) {
			*error = ENOMEM;
			goto done;
		}
		assert(last != NULL);
	}

	nserr = __NSW_SUCCESS;
done:
	if (fp) {
		(void) stack_op(POP, (char *)NULL, stack, stkptr);
		(void) fclose(fp);
	}

	if (*list != NULL) {
		/*
		 * list of entries found
		 */
		*error = 0;
	}
	return (nserr);
}

int
loadmaster_files(char *mastermap, char *defopts, char **stack, char ***stkptr)
{
	FILE *fp;
	int done = 0;
	char *line, *dir, *map, *opts;
	char linebuf[LINESZ];
	char lineq[LINESZ];
	char fname[MAXFILENAMELEN]; /* /etc prepended to mapname if reqd */


	if ((fp = file_open(mastermap, fname, stack, stkptr)) == NULL)
		return (__NSW_UNAVAIL);

	while ((line = get_line(fp, fname, linebuf,
	    sizeof (linebuf))) != NULL) {
		unquote(line, lineq);
		if (macro_expand("", line, lineq, LINESZ)) {
			syslog(LOG_ERR, "map %s: line too long (max %d chars)",
			    mastermap, LINESZ - 1);
			continue;
		}
		dir = line;
		while (*dir && isspace(*dir))
			dir++;
		if (*dir == '\0')
			continue;
		map = dir;

		while (*map && !isspace(*map)) map++;
		if (*map)
			*map++ = '\0';

		if (*dir == '+') {
			opts = map;
			while (*opts && isspace(*opts))
				opts++;
			if (*opts != '-')
				opts = defopts;
			else
				opts++;
			/*
			 * Check for no embedded blanks.
			 */
			if (strcspn(opts, " \t") == strlen(opts)) {
				dir++;
				(void) loadmaster_map(dir, opts, stack, stkptr);
			} else {
pr_msg("Warning: invalid entry for %s in %s ignored.\n", dir, fname);
				continue;
			}

		} else {
			while (*map && isspace(*map))
				map++;
			if (*map == '\0')
				continue;
			opts = map;
			while (*opts && !isspace(*opts))
				opts++;
			if (*opts) {
				*opts++ = '\0';
				while (*opts && isspace(*opts))
					opts++;
			}
			if (*opts != '-')
				opts = defopts;
			else
				opts++;
			/*
			 * Check for no embedded blanks.
			 */
			if (strcspn(opts, " \t") == strlen(opts)) {
				dirinit(dir, map, opts, 0, stack, stkptr);
			} else {
pr_msg("Warning: invalid entry for %s in %s ignored.\n", dir, fname);
				continue;
			}
		}
		done++;
	}

	(void) stack_op(POP, (char *)NULL, stack, stkptr);
	(void) fclose(fp);

	return (done ? __NSW_SUCCESS : __NSW_NOTFOUND);
}

int
loaddirect_files(char *map, char *local_map, char *opts,
    char **stack, char ***stkptr)
{
	FILE *fp;
	int done = 0;
	char *line, *p1, *p2;
	char linebuf[LINESZ];
	char fname[MAXFILENAMELEN]; /* /etc prepended to mapname if reqd */

	if ((fp = file_open(map, fname, stack, stkptr)) == NULL)
		return (__NSW_UNAVAIL);

	while ((line = get_line(fp, fname, linebuf,
	    sizeof (linebuf))) != NULL) {
		p1 = line;
		while (*p1 && isspace(*p1))
			p1++;
		if (*p1 == '\0')
			continue;
		p2 = p1;
		while (*p2 && !isspace(*p2))
			p2++;
		*p2 = '\0';
		if (*p1 == '+') {
			p1++;
			(void) loaddirect_map(p1, local_map, opts, stack,
			    stkptr);
		} else {
			dirinit(p1, local_map, opts, 1, stack, stkptr);
		}
		done++;
	}

	(void) stack_op(POP, (char *)NULL, stack, stkptr);
	(void) fclose(fp);

	return (done ? __NSW_SUCCESS : __NSW_NOTFOUND);
}

/*
 * This procedure opens the file and pushes it onto the
 * the stack. Only if a file is opened successfully, is
 * it pushed onto the stack
 */
static FILE *
file_open(char *map, char *fname, char **stack, char ***stkptr)
{
	FILE *fp;

	if (*map != '/') {
		/* prepend an "/etc" */
		(void) strcpy(fname, "/etc/");
		(void) strcat(fname, map);
	} else {
		(void) strcpy(fname, map);
	}

	fp = fopen(fname, "r");

	if (fp != NULL) {
		if (!stack_op(PUSH, fname, stack, stkptr)) {
			(void) fclose(fp);
			return (NULL);
		}
	}
	return (fp);
}

/*
 * reimplemnted to be MT-HOT.
 */
int
stack_op(int op, char *name, char **stack, char ***stkptr)
{
	char **ptr = NULL;
	char **stk_top = &stack[STACKSIZ - 1];

	/*
	 * the stackptr points to the next empty slot
	 * for PUSH: put the element and increment stkptr
	 * for POP: decrement stkptr and free
	 */

	switch (op) {
	case INIT:
		for (ptr = stack; ptr != stk_top; ptr++)
			*ptr = (char *)NULL;
		*stkptr = stack;
		return (1);
	case ERASE:
		for (ptr = stack; ptr != stk_top; ptr++)
			if (*ptr) {
				if (trace > 1)
					trace_prt(1, "  ERASE %s\n", *ptr);
				free (*ptr);
				*ptr = (char *)NULL;
			}
		*stkptr = stack;
		return (1);
	case PUSH:
		if (*stkptr == stk_top)
			return (0);
		for (ptr = stack; ptr != *stkptr; ptr++)
			if (*ptr && (strcmp(*ptr, name) == 0)) {
				return (0);
			}
		if (trace > 1)
			trace_prt(1, "  PUSH %s\n", name);
		if ((**stkptr = strdup(name)) == NULL) {
			syslog(LOG_ERR, "stack_op: Memory alloc failed : %m");
			return (0);
		}
		(*stkptr)++;
		return (1);
	case POP:
		if (*stkptr != stack)
			(*stkptr)--;
		else
			syslog(LOG_ERR, "Attempt to pop empty stack\n");

		if (*stkptr && **stkptr) {
			if (trace > 1)
				trace_prt(1, "  POP %s\n", **stkptr);
			free (**stkptr);
			**stkptr = (char *)NULL;
		}
		return (1);
	default:
		return (0);
	}
}

#define	READ_EXECOUT_ARGS 3

/*
 * read_execout(char *key, char **lp, char *fname, char *line, int linesz)
 * A simpler, multithreaded implementation of popen(). Used due to
 * non multithreaded implementation of popen() (it calls vfork()) and a
 * significant bug in execl().
 * Returns 0 on OK or -1 on error.
 */
static int
read_execout(char *key, char **lp, char *fname, char *line, int linesz)
{
	int p[2];
	int status = 0;
	int child_pid;
	char *args[READ_EXECOUT_ARGS];
	FILE *fp0;

	if (pipe(p) < 0) {
		syslog(LOG_ERR, "read_execout: Cannot create pipe");
		return (-1);
	}

	/* setup args for execv */
	if (((args[0] = strdup(fname)) == NULL) ||
	    ((args[1] = strdup(key)) == NULL)) {
		if (args[0] != NULL)
			free(args[0]);
		syslog(LOG_ERR, "read_execout: Memory allocation failed");
		return (-1);
	}
	args[2] = NULL;

	if (trace > 3)
		trace_prt(1, "\tread_execout: forking .....\n");

	switch ((child_pid = fork1())) {
	case -1:
		syslog(LOG_ERR, "read_execout: Cannot fork");
		return (-1);
	case 0:
		/*
		 * Child
		 */
		close(p[0]);
		close(1);
		if (fcntl(p[1], F_DUPFD, 1) != 1) {
			syslog(LOG_ERR,
			"read_execout: dup of stdout failed");
			_exit(-1);
		}
		close(p[1]);
		execv(fname, &args[0]);
		_exit(-1);
	default:
		/*
		 * Parent
		 */
		close(p[1]);

		/*
		 * wait for child to complete. Note we read after the
		 * child exits to guarantee a full pipe.
		 */
		while (waitpid(child_pid, &status, 0) < 0) {
			/* if waitpid fails with EINTR, restart */
			if (errno != EINTR) {
				status = -1;
				break;
			}
		}
		if (status != -1) {
			if ((fp0 = fdopen(p[0], "r")) != NULL) {
				*lp = get_line(fp0, fname, line, linesz);
				fclose(fp0);
			} else {
				close(p[0]);
				status = -1;
			}
		} else {
			close(p[0]);
		}

		/* free args */
		free(args[0]);
		free(args[1]);

		if (trace > 3) {
			trace_prt(1, "\tread_execout: map=%s key=%s line=%s\n",
			    fname, key, line);
		}

		return (status);
	}
}

void
automountd_do_exec_map(void *cookie, char *argp, size_t arg_size,
    door_desc_t *dfd, uint_t n_desc)
{
	command_t	*command;
	char	line[LINESZ];
	char	*lp;
	int	rc;

	command = (command_t *)argp;

	if (sizeof (*command) != arg_size) {
		rc = 0;
		syslog(LOG_ERR, "read_execout: invalid door arguments");
		door_return((char *)&rc, sizeof (rc), NULL, 0);
	}

	rc = read_execout(command->key, &lp, command->file, line, LINESZ);

	if (rc != 0) {
		/*
		 * read_execout returned an error, return 0 to the door_client
		 * to indicate failure
		 */
		rc = 0;
		door_return((char *)&rc, sizeof (rc), NULL, 0);
	} else {
		door_return((char *)line, LINESZ, NULL, 0);
	}
	trace_prt(1, "automountd_do_exec_map, door return failed %s, %s\n",
	    command->file, strerror(errno));
	door_return(NULL, 0, NULL, 0);
}

static int
call_read_execout(char *key, char *fname, char *line, int linesz)
{
	command_t command;
	door_arg_t darg;
	int ret;

	bzero(&command, sizeof (command));
	(void) strlcpy(command.file, fname, MAXPATHLEN);
	(void) strlcpy(command.key, key, MAXOPTSLEN);

	if (trace >= 1)
		trace_prt(1, "call_read_execout %s %s\n", fname, key);
	darg.data_ptr = (char *)&command;
	darg.data_size = sizeof (command);
	darg.desc_ptr = NULL;
	darg.desc_num = 0;
	darg.rbuf = line;
	darg.rsize = linesz;

	ret = door_call(did_exec_map, &darg);

	return (ret);
}
/*
 * 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
 */
/*
 * ns_fnmount.c
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <syslog.h>
#include <rpc/rpc.h>
#include <rpcsvc/nis.h>
#include <xfn/xfn.h>
#include "automount.h"
#include "ns_fnutils.h"


/*
 * The maximum sizes of map names, key names, composite names, and status
 * descriptions, including the trailing '\0'.
 */
#define	MAPNAMESZ	(size_t)(AUTOFS_MAXCOMPONENTLEN + 1)
#define	KEYNAMESZ	(size_t)(AUTOFS_MAXCOMPONENTLEN + 1)
#define	COMPNAMESZ	(size_t)(MAPNAMESZ - FNPREFIXLEN + KEYNAMESZ - 2)
#define	DESCSZ		(size_t)512

typedef struct mapent	mapent;
typedef struct mapline	mapline;


/*
 * The name of an attribute.
 */
static const FN_identifier_t attr_exported = {FN_ID_STRING, 8, "exported"};


/*
 * Given a request by a particular user to mount the name "key" under
 * map/context "map", and a set of default mount options, return (in
 * "res") either a list of mapents giving the mounts that need to be
 * performed, or a symbolic link to be created for a user-relative
 * context.  If "shallow" is true return, in place of the list of
 * mapents, a single mapent representing an indirect mount point.
 *
 *	void
 *	getmapent_fn(char *key, char *map, char *opts, uid_t uid,
 *	      bool_t shallow, getmapent_fn_res *res);
 */

/*
 * Given a reference, its composite name, default mount options, and a
 * mapent root, return a list of mapents to mount.  If "shallow" is
 * true return, in place of the list of mapents, a single mapent
 * representing an indirect mount point.  The map and key strings are
 * pieces of the composite name such that:
 * "FNPREFIX/cname" == "map/key".
 */
static mapent *
process_ref(const FN_ref_t *ref, const char *cname, char *map, char *key,
    char *opts, char *root, bool_t shallow, FN_status_t *status);

/*
 * Traverse the namespace to find a frontier below ref along which
 * future mounts may need to be triggered.  Add to mapents the
 * corresponding direct autofs mount points.
 *     map:	map name for ref
 *     maplen:	strlen(map)
 *     mntpnt:	suffix of map where the current mount request begins
 *		(starts off as "", and grows as we traverse the namespace)
 *     opts:	default mount options
 *     status:	passed from above to avoid having to allocate one on each call
 * Works by calling frontier_aux() on each name bound under ref.
 * Return the new mapents, or free mapents and return NULL on failure.
 */
static mapent *
frontier(mapent *mapents, const FN_ref_t *ref, char *map, size_t maplen,
    char *mntpnt, char *opts, FN_status_t *status);

/*
 * Called by frontier(), once for each "name" that it finds.  map is
 * passed unchanged from frontier().  ref is the reference named by
 * "map/name".  If ref is found to be along the frontier, add the
 * corresponding direct autofs mount point to mapents.  Otherwise
 * continue traversing the namespace to find the frontier.  Other
 * arguments and the return value are as for frontier().
 */
static mapent *
frontier_aux(mapent *mapents, const FN_ref_t *ref, char *map, size_t maplen,
    char *mntpnt, const char *name, char *opts, FN_status_t *status);

/*
 * Given a reference with an address type of ADDR_HOST and its
 * composite name, check the attr_exported attribute to determine if
 * the corresponding directory is exported.  Return FALSE on error.
 */
static bool_t
exported(const FN_ref_t *ref, const char *cname, FN_status_t *status);

/*
 * Find a reference's address type and, if "data" is not NULL, its
 * data string.  If there is no address of a known type, set *typep to
 * NUM_ADDRTYPES; if there are several, stop after finding the first.
 * Return 0 on success.
 */
static int
addr_from_ref(const FN_ref_t *ref, const char *cname, addrtype_t *typep,
    char *data, size_t datasz);

/*
 * Decode an address's data into a string.  Return 0 on success.
 */
static int
str_from_addr(const char *cname, const FN_ref_addr_t *addr, char str[],
    size_t strsz);

/*
 * Given a map name and its current length, append "/name".  Return
 * the new length.  On error, syslog a warning and return 0.
 */
static size_t
append_mapname(char *map, size_t maplen, const char *name);

/*
 * Concatenate two strings using the given separator.  The result is a
 * newly-allocated string, or NULL on error.
 */
static char *
concat(const char *s1, char sep, const char *s2);

/*
 * Add the "nosuid" option to a mapent.  Also check for a sneaky
 * hacker trying to override this option by manually inserting a
 * multiple mount entry into the XFN namespace.  Return FALSE on error.
 */
static bool_t
safe_mapent(mapent *me);

/*
 * Append "nosuid" to a list of options.  The result is a
 * newly-allocated string, or NULL on error.
 */
static char *
safe_opts(const char *opts);

/*
 * Trim comments and trailing whitespace from ml->linebuf, then
 * unquote it and leave the result in ml.  Return 0 on success.
 */
static int
trim_line(mapline *ml);

/*
 * Determine whether ml contains an option string (such as "-ro") and
 * nothing else.
 */
static bool_t
opts_only(const mapline *ml);

/*
 * Allocate a new mapent structure.  The arguments must have been
 * malloc'ed, and are owned by the mapent; they are freed if
 * new_mapent() fails.  If any argument is NULL, the call fails and a
 * memory allocation failure is logged.  A root argument of 'noroot'
 * indicates that the map_root field does not need to be set (it's
 * only needed in the first of a list of mapents).
 */
static char *noroot = "[no root]";
static mapent *
new_mapent(char *root, char *mntpnt, char *fstype, char *mntopts, char *host,
    char *dir);

/*
 * Determine whether cname is a user-relative binding -- such as "myself" --
 * in the initial context.
 */
static bool_t
is_user_relative(const char *cname);

/*
 * Given the name of a user-relative binding, return an equivalent
 * name that is not user-relative.
 */
static char *
equiv_name(FN_ctx_t *, const char *cname, FN_status_t *);

void
getmapent_fn(char *key, char *map, char *opts, uid_t uid, bool_t shallow,
    getmapent_fn_res *res)
{
	size_t			maplen;
	FN_status_t		*status;
	FN_ctx_t		*init_ctx = NULL;
	int			statcode;
	char			cname[COMPNAMESZ];
	FN_composite_name_t	*compname;
	FN_ref_t		*ref;
	char			mapname[MAPNAMESZ];
	char			*root;

	res->type = FN_NONE;
	res->m_or_l.mapents = NULL;

	if (init_fn() != 0) {
		return;
	}

	/*
	 * For direct mounts, the key is the entire path, and the map
	 * name already has the final key component appended.  Split
	 * apart the map name and key.  The "root" of the mapent is
	 * "/key" for indirect mounts, and "" for direct mounts.
	 */
	strcpy(mapname, map);
	if (key[0] == '/') {
		key = strrchr(key, '/') + 1;
		*strrchr(mapname, '/') = '\0';
		root = strdup("");
	} else {
		root = concat("", '/', key);
	}
	map = mapname;
	maplen = strlen(map);

	if ((maplen - FNPREFIXLEN + strlen(key)) >= COMPNAMESZ) {
		if (verbose) {
			syslog(LOG_ERR, "name %s/%s too long", map, key);
		}
		return;
	}
	if (maplen == FNPREFIXLEN) {
		strcpy(cname, key);
	} else {
		sprintf(cname, "%s/%s", map + FNPREFIXLEN + 1, key);
	}

	status = fn_status_create();
	if (status == NULL) {
		if (verbose) {
			syslog(LOG_ERR, "Could not create FNS status object");
		}
		return;
	}
	init_ctx = _fn_ctx_handle_from_initial_with_uid(uid, 0, status);
	if (init_ctx == NULL) {
		logstat(status, "", "No initial context");
		goto done;
	}

#ifndef XFN1ENV
	if (is_user_relative(cname)) {
		res->type = FN_SYMLINK;
		res->m_or_l.symlink = equiv_name(init_ctx, cname, status);
		goto done;
	}
#endif

	if ((compname = new_cname(cname)) == NULL) {
		goto done;
	}
	ref = fn_ctx_lookup(init_ctx, compname, status);
	statcode = fn_status_code(status);
	fn_composite_name_destroy(compname);

	if (trace > 1 && !shallow) {
		trace_prt(1, "  FNS traversal: %s\n", cname);
	}

	if (ref == NULL) {
		if ((statcode != FN_E_NAME_NOT_FOUND) &&
		    (statcode != FN_E_NOT_A_CONTEXT)) {
			logstat(status, "lookup failed on", cname);
		}
		goto done;
	}

	res->type = FN_MAPENTS;
	res->m_or_l.mapents =
	    process_ref(ref, cname, map, key, opts, root, shallow, status);
	fn_ref_destroy(ref);
done:
	fn_ctx_handle_destroy(init_ctx);
	fn_status_destroy(status);
}


static mapent *
process_ref(const FN_ref_t *ref, const char *cname, char *map, char *key,
    char *opts, char *root, bool_t shallow, FN_status_t *status)
{
	addrtype_t	addrtype;
	mapline		ml;
	char		*addrdata = ml.linebuf;
	mapent		*mapents;
	bool_t		self;
	char		*homedir;
	size_t		maplen;
	char		*colon;
	char		*nfshost;
	char		*nfsdir;

	if ((reftype(ref) < NUM_REFTYPES) &&
	    (addr_from_ref(ref, cname, &addrtype, addrdata, LINESZ) == 0)) {

		switch (addrtype) {
		case ADDR_MOUNT:
			if (trim_line(&ml) != 0) {
				return (NULL);
			}
			if (opts_only(&ml)) {
				/* parse_entry() can't handle such lines */
				if (macro_expand("&", ml.linebuf,
				    ml.lineqbuf, LINESZ)) {
					syslog(LOG_ERR,
					"%s/%s: opts too long (max %d chars)",
					    FNPREFIX, cname, LINESZ - 1);
					return (NULL);
				}
				opts = ml.linebuf + 1;	/* skip '-' */
				goto indirect;
			}
			mapents = parse_entry(key, map, opts, &ml, NULL, 0,
			    TRUE);
			if (mapents == NULL || !safe_mapent(mapents)) {
				free_mapent(mapents);
				return (NULL);
			}
			free(mapents->map_root);
			mapents->map_root = root;
			break;

		case ADDR_HOST:
			/*
			 * Address is of the form "host:dir".
			 * If "dir" is not supplied, it defaults to "/".
			 */
			colon = strchr(addrdata, ':');
			if (colon == NULL || colon[1] == '\0') {
				nfsdir = strdup("/");
			} else {
				*colon = '\0';
				nfsdir = strdup(colon + 1);
			}
			nfshost = strdup(addrdata);
			/*
			 * If nfshost is the local host, the NFS mount
			 * request will be converted to a loopback
			 * mount.  Otherwise check that the file system
			 * is exported.
			 */
			if (nfshost != NULL) {
				self = self_check(nfshost);
				if (!self && !exported(ref, cname, status)) {
					if (transient(status)) {
						return (NULL);
					} else {
						goto indirect;
					}
				}
			}
			mapents = new_mapent(root, strdup(""), strdup("nfs"),
			    safe_opts(opts), nfshost, nfsdir);
			if (self && !shallow) {
				return (mapents);
			}
			break;

		case ADDR_USER:
			homedir = strdup(addrdata);
			homedir[strcspn(homedir, " \t\r\n")] = '\0';
			mapents = new_mapent(root, strdup(""), strdup("lofs"),
			    strdup(opts), strdup(""), homedir);
			break;
		}

		if (mapents == NULL) {
			return (NULL);
		}
		if (shallow) {
			mapents->map_root = NULL;	/* don't free "root" */
			free_mapent(mapents);
			goto indirect;
		}

		/* "map" => "map/key" */
		if ((maplen = append_mapname(map, strlen(map), key)) == 0) {
			return (mapents);
		}
		return (frontier(mapents, ref, map, maplen, map + maplen,
		    opts, status));
	}

	/* Ref type wasn't recognized. */

indirect:
	/* Install an indirect autofs mount point. */
	return (new_mapent(root, strdup(""), strdup("autofs"), strdup(opts),
	    strdup(""), concat(map, '/', key)));
}


/*
 * All that this function really does is call frontier_aux() on every
 * name bound under ref.  The rest is error checking(!)
 *
 * The error handling strategy is to reject the entire mount request
 * (by freeing mapents) if any (potentially) transient error occurs,
 * and to treat nontransient errors as holes in the affected portions
 * of the namespace.
 */
static mapent *
frontier(mapent *mapents, const FN_ref_t *ref, char *map, size_t maplen,
    char *mntpnt, char *opts, FN_status_t *status)
{
	FN_ctx_t		*ctx;
	FN_bindinglist_t	*bindings = NULL;
	FN_ref_t		*child_ref;
	FN_string_t		*child_s;
	const char		*child;
	unsigned int		statcode;

	ctx = fn_ctx_handle_from_ref(ref, XFN2(0) status);
	if (ctx == NULL) {
		if (fn_status_code(status) != FN_E_NO_SUPPORTED_ADDRESS) {
			logstat(status, "from_ref failed for", map);
		}
		goto checkerr_return;
	}

	bindings = fn_ctx_list_bindings(ctx, empty_cname, status);
	fn_ctx_handle_destroy(ctx);
	if (bindings == NULL) {
		logstat(status, "list_bindings failed for", map);
		goto checkerr_return;
	}

	while ((child_s = fn_bindinglist_next(bindings, &child_ref, status))
	    != NULL) {
		child = (const char *)fn_string_str(child_s, &statcode);
		if (child == NULL) {
			if (verbose) {
				syslog(LOG_ERR,
				    "FNS string error listing %s", map);
			}
			fn_string_destroy(child_s);
			goto err_return;
		}
		mapents = frontier_aux(mapents, child_ref, map, maplen,
		    mntpnt, child, opts, status);
		fn_string_destroy(child_s);
		fn_ref_destroy(child_ref);
		if (mapents == NULL) {
			goto noerr_return;
		}
	}
	if (fn_status_is_success(status)) {
		goto noerr_return;
	} else {
		logstat(status, "error while listing", map);
		/* Fall through to checkerr_return. */
	}

checkerr_return:
	if (!transient(status)) {
		goto noerr_return;
	}
err_return:
	free_mapent(mapents);
	mapents = NULL;
noerr_return:
	fn_bindinglist_destroy(bindings XFN1(status));
	return (mapents);
}


static mapent *
frontier_aux(mapent *mapents, const FN_ref_t *ref, char *map, size_t maplen,
    char *mntpnt, const char *name, char *opts, FN_status_t *status)
{
	addrtype_t	addrtype;
	bool_t		at_frontier;
	mapent		*me;
	size_t		maplen_save = maplen;
	char		*cname = map + FNPREFIXLEN + 1;	/* for error msgs */

	if (reftype(ref) >= NUM_REFTYPES) {
		/*
		 * We could instead install an indirect autofs mount point
		 * here.  That would allow, for example, a user to be bound
		 * beneath a file system.
		 */
		return (mapents);
	}

	/* "map" => "map/name" */
	if ((maplen = append_mapname(map, maplen, name)) == 0) {
		return (mapents);
	}
	if (trace > 1) {
		trace_prt(1, "  FNS traversal: %s/\n", cname);
	}

	/*
	 * If this is an address type that we know how to mount, then
	 * we have reached the frontier.
	 */
	at_frontier = (addr_from_ref(ref, cname, &addrtype, NULL, 0) == 0);
	/*
	 * For an ADDR_HOST address, treat a non-exported directory as
	 * if the address type were not known:  continue searching for
	 * exported subdirectories.
	 */
	if (at_frontier && (addrtype == ADDR_HOST)) {
		if (!exported(ref, cname, status)) {
			if (transient(status)) {
				free_mapent(mapents);
				return (NULL);
			} else {
				at_frontier = FALSE;
			}
		}
	}
	/*
	 * If we have reached the frontier, install a direct autofs
	 * mount point (which will trigger the actual mount if the
	 * user steps on it later).  Otherwise, continue traversing
	 * the namespace looking for known address types.
	 */
	if (at_frontier) {
		opts = (opts[0] != '\0')
		    ? concat(opts, ',', "direct")
		    : strdup("direct");
		me = new_mapent(noroot, strdup(mntpnt), strdup("autofs"), opts,
		    strdup(""), strdup(map));
		if (me != NULL) {
			/* Link new mapent into list (not at the head). */
			me->map_next = mapents->map_next;
			mapents->map_next = me;
		} else {
			free_mapent(mapents);
			mapents = NULL;
		}
	} else {
		mapents =
		    frontier(mapents, ref, map, maplen, mntpnt, opts, status);
	}
	map[maplen_save] = '\0';	/* "map/name" => "map" */
	return (mapents);
}


static bool_t
exported(const FN_ref_t *ref, const char *cname, FN_status_t *status)
{
	FN_ctx_t		*ctx;
	FN_attribute_t		*attr;

	ctx = fn_ctx_handle_from_ref(ref, XFN2(0) status);
	if (ctx == NULL) {
		logstat(status, "from_ref failed for", cname);
		return (FALSE);
	}
	attr = fn_attr_get(ctx, empty_cname, &attr_exported, XFN2(1) status);
	fn_ctx_handle_destroy(ctx);

	switch (fn_status_code(status)) {
	case FN_SUCCESS:
		fn_attribute_destroy(attr);
		break;
	case FN_E_NO_SUCH_ATTRIBUTE:
		break;
	default:
		logstat(status, "could not get attributes for", cname);
	}
	return (attr != NULL);
}


static int
addr_from_ref(const FN_ref_t *ref, const char *cname, addrtype_t *typep,
    char *data, size_t datasz)
{
	const FN_ref_addr_t	*addr;
	void			*iter_pos;

	addr = fn_ref_first(ref, &iter_pos);
	if (addr == NULL) {
		if (verbose) {
			syslog(LOG_ERR, "FNS ref with no address: %s", cname);
		}
		return (-1);
	}
	while (addr != NULL) {
		*typep = addrtype(addr);
		if (*typep < NUM_ADDRTYPES) {
			return ((data != NULL)
			    ? str_from_addr(cname, addr, data, datasz)
			    : 0);
		}
		addr = fn_ref_next(ref, &iter_pos);
	}
	return (-1);
}


static int
str_from_addr(const char *cname, const FN_ref_addr_t *addr, char str[],
    size_t strsz)
{
	XDR	xdr;
	int	res;

	xdrmem_create(&xdr, (caddr_t)fn_ref_addr_data(addr),
	    fn_ref_addr_length(addr), XDR_DECODE);
	if (!xdr_string(&xdr, &str, strsz)) {
		if (verbose) {
			syslog(LOG_ERR,
			    "Could not decode FNS address for %s", cname);
		}
		res = -1;
	} else {
		res = 0;
	}
	xdr_destroy(&xdr);
	return (res);
}

static size_t
append_mapname(char *map, size_t maplen, const char *name)
{
	size_t namelen = strlen(name);

	if (maplen + 1 + namelen >= MAPNAMESZ) {
		if (verbose) {
			syslog(LOG_ERR, "FNS name %s/%s too long",
			    map + FNPREFIXLEN + 1, name);
		}
		return (0);
	}
	sprintf(map + maplen, "/%s", name);
	return (maplen + 1 + namelen);
}


static char *
concat(const char *s1, char sep, const char *s2)
{
	char *s = malloc(strlen(s1) + 1 + strlen(s2) + 1);

	if (s != NULL) {
		sprintf(s, "%s%c%s", s1, sep, s2);
	}
	return (s);
}


static bool_t
safe_mapent(mapent *me)
{
	char	*opts;

	if (me->map_next != NULL) {
		/* Multiple mounts don't belong in XFN namespace. */
		return (NULL);
	}
	opts = me->map_mntopts;
	me->map_mntopts = safe_opts(opts);
	free(opts);
	return (me->map_mntopts != NULL);
}


static char *
safe_opts(const char *opts)
{
	char	*start;
	size_t	len;

	if (opts[0] == '\0') {
		return (strdup(MNTOPT_NOSUID));
	}

	/* A quick-and-dirty check to see if "nosuid" is already there. */
	start = strstr(opts, MNTOPT_NOSUID);
	len = sizeof (MNTOPT_NOSUID) - 1;	/* "-1" for trailing '\0' */
	if (start != NULL) {
		while (start > opts && isspace(*(start - 1))) {
			start--;
		}
		if ((start == opts || *(start - 1) == ',') &&
		    opts[len] == ',' || opts[len] == '\0') {
			return (strdup(opts));
		}
	}
	return (concat(opts, ',', MNTOPT_NOSUID));
}


static int
trim_line(mapline *ml)
{
	char	*end;	/* pointer to '\0' at end of linebuf */

	end = ml->linebuf + strcspn(ml->linebuf, "#");
	while ((end > ml->linebuf) && isspace(end[-1])) {
		end--;
	}
	if (end <= ml->linebuf) {
		return (-1);
	}
	*end = '\0';
	unquote(ml->linebuf, ml->lineqbuf);
	return (0);
}


static bool_t
opts_only(const mapline *ml)
{
	const char *s = ml->linebuf;
	const char *q = ml->lineqbuf;

	if (*s != '-') {
		return (FALSE);
	}
	for (; *s != '\0'; s++, q++) {
		if (isspace(*s) && (*q == ' ')) {
			return (FALSE);
		}
	}
	return (TRUE);
}


static mapent *
new_mapent(char *root, char *mntpnt, char *fstype, char *mntopts, char *host,
    char *dir)
{
	mapent		*me;
	struct mapfs	*mfs;
	char		*mounter = NULL;

	me = calloc(1, sizeof (*me));
	mfs = calloc(1, sizeof (*mfs));
	if (fstype != NULL) {
		mounter = strdup(fstype);
	}
	if ((mntpnt == NULL) || (fstype == NULL) || (mntopts == NULL) ||
	    (host == NULL) || (dir == NULL) || (me == NULL) || (mfs == NULL) ||
	    (mounter == NULL) || (root == NULL)) {
		log_mem_failure();
		free(me);
		free(mfs);
		free(mounter);
		free(root);
		free(mntpnt);
		free(fstype);
		free(mntopts);
		free(host);
		free(dir);
		return (NULL);
	}
	me->map_root	= (root != noroot) ? root : NULL;
	me->map_fstype	= fstype;
	me->map_mounter	= mounter;
	me->map_mntpnt	= mntpnt;
	me->map_mntopts	= mntopts;
	me->map_fsw	= NULL;
	me->map_fswq    = NULL;
	me->map_fs	= mfs;
	mfs->mfs_host	= host;
	mfs->mfs_dir	= dir;
	me->map_mntlevel = -1;
	me->map_modified = FALSE;
	me->map_faked = FALSE;
	me->map_err = 0;		/* MAPENT_NOERR */
	return (me);
}


#ifndef XFN1ENV

/*
 * User-relative bindings in the initial context, and the leading components
 * of their non-user-relative equivalents.  Leading components are listed in
 * the order in which they should be tried.  Each list is NULL-terminated
 * (the compiler generously does this for us).
 * For "myorgunit", for example, we first check if it is equivalent to
 * "thisorgunit".  If not, we translate it into "org/<something>".
 */
#define	MAX_LEADS 3

static struct {
	const char	*binding;
	const char	*leads[MAX_LEADS + 1];
} user_rel[] = {
	{"thisuser",	{"user", "thisorgunit", "org"}},
	{"myself",	{"user", "thisorgunit", "org"}},
	{"_myself",	{"_user", "_thisorgunit", "_orgunit"}},
	{"myorgunit",	{"thisorgunit", "org"}},
	{"_myorgunit",	{"_thisorgunit", "_orgunit"}},
	{"myens",	{"thisens"}},
	{"_myens",	{"_thisens"}}
};


static bool_t
is_user_relative(const char *cname)
{
	int	i;

	for (i = 0; i < sizeof (user_rel) / sizeof (user_rel[0]); i++) {
		if (strcmp(cname, user_rel[i].binding) == 0) {
			return (TRUE);
		}
	}
	return (FALSE);
}


static char *
equiv_name(FN_ctx_t *ctx, const char *cname, FN_status_t *status)
{
	FN_composite_name_t	*name;
	FN_string_t		*leading_name;
	FN_composite_name_t	*equiv;
	FN_string_t		*equiv_string;
	const char		*equiv_str;
	char			*equiv_str_dup;
	const char		**leads;
	unsigned int		stat;
	int			i;

	for (i = 0; i < sizeof (user_rel) / sizeof (user_rel[0]); i++) {
		if (strcmp(cname, user_rel[i].binding) == 0) {
			break;
		}
	}
	if ((name = new_cname(cname)) == NULL) {
		return (NULL);
	}
	leads = user_rel[i].leads;	/* array of leading names to try */
	do {
		leading_name = fn_string_from_str((unsigned char *)*leads);
		if (leading_name == NULL) {
			log_mem_failure();
			fn_composite_name_destroy(name);
			return (NULL);
		}
		equiv = prelim_fn_ctx_equivalent_name(ctx, name, leading_name,
		    status);
		fn_string_destroy(leading_name);
	} while (equiv == NULL && *++leads != NULL);

	fn_composite_name_destroy(name);

	if (equiv == NULL) {
		if (transient(status)) {
			logstat(status, "could not find equivalent of", cname);
		}
		return (NULL);
	}
	equiv_string = fn_string_from_composite_name(equiv, &stat);
	fn_composite_name_destroy(equiv);
	if (equiv_string == NULL) {
		log_mem_failure();
		return (NULL);
	}
	equiv_str = (const char *)fn_string_str(equiv_string, &stat);
	if (equiv_str == NULL ||
	    (equiv_str_dup = strdup(equiv_str)) == NULL) {
		log_mem_failure();
		fn_string_destroy(equiv_string);
		return (NULL);
	}
	fn_string_destroy(equiv_string);
	return (equiv_str_dup);
}

#endif	/* XFN1ENV */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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
 */
/*
 * ns_fnreaddir.c
 *
 * Copyright (c) 1995 - 1996, by Sun Microsystems, Inc.
 * All rights reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <rpc/rpc.h>
#include <xfn/xfn.h>
#include "automount.h"
#include "ns_fnutils.h"


/*
 * Given the name of an XFN map, create a list of the map entries for a
 * given user.  Set error to zero on success.
 *
 *	extern void
 *	getmapkeys_fn(const char *map, struct dir_entry **, int *error,
 *	    int *cache_time, uid_t);
 */

/*
 * Given a multi-component composite name, construct the corresponding
 * context handle and the context handle of its prefix.  The prefix is
 * that part of the name up to (and possibly including) the last slash
 * in the name.  Return zero on success.
 *
 * eg:	user/jane/service  =>  user/jane + service
 *	org/ssi.eng/user   =>  org/ssi.eng/ + user
 */
static int
get_contexts(const FN_composite_name_t *, FN_ctx_t **ctxp,
    FN_ctx_t **prefix_ctxp, FN_ctx_t *init_ctx, FN_status_t *);

/*
 * Split a multi-component composite name into its last component and
 * its other components.  Return zero on success.
 */
static int
split_cname(const FN_composite_name_t *name, FN_composite_name_t **last,
    FN_composite_name_t **lead);

/*
 * Given a context and its prefix context (defined above), determine
 * whether the context, its NNS context, or both should be listed.
 * (The syntaxes of the contexts are used to help make this
 * determination.)  Add the subdirectories of the appropriate
 * context(s) to the dir_entry list.  Return zero on success.
 *
 * eg:	"ls /xfn/user		=>  list context only
 *	"ls /xfn/org/ssi.eng"	=>  list NNS only
 *	"ls /xfn/.../c=us"	=>  list context and NNS
 */
static int
list_ctx_and_or_nns(FN_ctx_t *ctx, FN_ctx_t *prefix_ctx, struct dir_entry **,
    FN_status_t *);

/*
 * Given a context and its prefix context (defined above), return true
 * if the NNS of the context should be listed but the context itself
 * should not.
 */
static bool_t
need_nns_only(FN_ctx_t *ctx, FN_ctx_t *prefix_ctx, FN_status_t *);

/*
 * Return true if both the given context and its NNS should be listed.
 */
static bool_t
need_ctx_and_nns(FN_ctx_t *, FN_status_t *);

/*
 * Add the subdirectories of a context to the dir_entry list.  Return
 * zero on success.
 */
static int
list_ctx(FN_ctx_t *, struct dir_entry **, FN_status_t *);

/*
 * Given a context and its name relative to the root of its rightmost
 * naming system, add the context's subdirectories to the dir_entry
 * list.  If syntax is non-NULL recursively list names until a context
 * with a different syntax is encountered, otherwise list one level
 * only.  May modify "name".  Return zero on success.
 *
 * eg:  For the context org/eng with syntax "dot-separated, right-to-left",
 * the compound name "eng" would be passed in, and the following might
 * be added to the dir_entry list:
 * 	ssi.eng
 *	feds.ssi.eng
 * 	ste.eng
 */
static int
list_ctx_aux(FN_ctx_t *, FN_compound_name_t *name, const FN_attrset_t *syntax,
    struct dir_entry **, FN_status_t *);

/*
 * Add a name to a dir_entry list.  Return zero on success.
 */
static int
add_name_to_dirlist(const FN_compound_name_t *, struct dir_entry **);

/*
 * Return true if a set of syntax attributes correspond to a
 * hierarchical namespace with a slash separator.  Return false on
 * error.
 */
static bool_t
slash_hierarchy(const FN_attrset_t *syntax);

/*
 * Return true if a set of syntax attributes correspond to a
 * hierarchical namespace with a separator other than a slash.
 * Return false on error.
 */
static bool_t
non_slash_hierarchy(const FN_attrset_t *syntax);

/*
 * Return true if two syntax attribute sets are equal.
 */
static bool_t
syntax_attrs_equal(const FN_attrset_t *, const FN_attrset_t *);

/*
 * Return a value of a given attribute in an attribute set, or NULL
 * on error.
 */
static const FN_attrvalue_t *
get_attrval(const FN_attrset_t *, const FN_identifier_t *attr_id);

/*
 * Lookup a name and return the corresponding context handle.  On
 * error return NULL and, if "log" is true or the error is transient,
 * log an error message.
 */
static FN_ctx_t *
lookup_ctx(FN_ctx_t *, const FN_composite_name_t *, bool_t log, FN_status_t *);


/*
 * Unlike during a lookup or mount, transient errors are tolerated.  A
 * potentially transient error during a readdir() (such as no response
 * from an X.500 server) could result in an incomplete listing, but at
 * least readdir() will return everything that it can.  Note that it
 * is still possible to mount a directory that for some reason did not
 * show up in a prior readdir().
 */
void
getmapkeys_fn(const char *map, struct dir_entry **entries_p, int *error,
    int *cache_time, uid_t uid)
{
	FN_composite_name_t	*name;
	FN_status_t		*status;
	FN_ctx_t		*init_ctx;
	FN_ctx_t		*ctx;
	FN_ctx_t		*prefix_ctx;
	struct dir_entry	*p;

	*cache_time = RDDIR_CACHE_TIME;

	if ((init_fn() != 0) || (status = fn_status_create()) == NULL) {
		log_mem_failure();
		*error = -1;
		return;
	}
	init_ctx = _fn_ctx_handle_from_initial_with_uid(uid, 0, status);
	if (init_ctx == NULL) {
		logstat(status, "", "No initial context");
		fn_status_destroy(status);
		return;
	}

	if (strcmp(map, FNPREFIX) == 0) {
		/*
		 * List the initial context.
		 * Contents of initial ctx is user-relative
		 */
		*cache_time = 0;
		*error = list_ctx(init_ctx, entries_p, status);
	} else if (strcmp(map, FNPREFIX "/_dns") == 0) {
		/* Cannot list DNS; report success but no entries. */
		*cache_time = 1000000;	/* no sense trying again */
		*error = 0;
	} else {
		if (strcmp(map, FNPREFIX "/...") == 0) {
			/* List X.500 but not DNS. */
			name = new_cname("_x500");
		} else {
			name = new_cname(map + FNPREFIXLEN + 1);
		}
		if (name == NULL) {
			*error = -1;
		} else if (fn_composite_name_count(name) == 1) {

			/* List an atomic name. */
			ctx = lookup_ctx(init_ctx, name, TRUE, status);
			if (ctx != NULL) {
				*error = list_ctx_and_or_nns(ctx, init_ctx,
				    entries_p, status);
				fn_ctx_handle_destroy(ctx);
			} else {
				*error = -1;
			}
		} else {

			/* List a multi-component name. */
			*error = get_contexts(name, &ctx, &prefix_ctx,
			    init_ctx, status);
			if (*error == 0) {
				*error = list_ctx_and_or_nns(ctx, prefix_ctx,
				    entries_p, status);
				fn_ctx_handle_destroy(ctx);
				fn_ctx_handle_destroy(prefix_ctx);
			}
		}
		fn_composite_name_destroy(name);
	}
	fn_status_destroy(status);
	fn_ctx_handle_destroy(init_ctx);

	if (*error == 0) {
		/*
		 * create the binary tree of entries
		 */
		for (p = *entries_p; p != NULL; p = p->next)
			btree_enter(entries_p, p);
	}
}


static int
get_contexts(const FN_composite_name_t *name, FN_ctx_t **ctxp,
    FN_ctx_t **prefix_ctxp, FN_ctx_t *init_ctx, FN_status_t *status)
{
	FN_composite_name_t	*prefix = NULL;
	FN_composite_name_t	*suffix = NULL;
	FN_ctx_t		*nns_ctx;

	/*
	 * Break a name such as "pre/fix/suffix" into "pre/fix/" and
	 * "suffix".  If that fails, try "pre/fix" and "suffix".  This
	 * can be more efficient than doing it the reverse order.
	 */
	if (split_cname(name, &suffix, &prefix) != 0) {
		return (-1);
	}
	*ctxp = NULL;
	*prefix_ctxp = lookup_ctx(init_ctx, prefix, TRUE, status);
	fn_composite_name_destroy(prefix);

	if (*prefix_ctxp != NULL) {
		nns_ctx = lookup_ctx(*prefix_ctxp, slash_cname, FALSE, status);
		if (nns_ctx != NULL) {
			*ctxp = lookup_ctx(nns_ctx, suffix, FALSE, status);
			if (*ctxp != NULL) {
				fn_ctx_handle_destroy(*prefix_ctxp);
				*prefix_ctxp = nns_ctx;
			} else {
				fn_ctx_handle_destroy(nns_ctx);
			}
		}
		if (*ctxp == NULL) {
			*ctxp =
			    lookup_ctx(*prefix_ctxp, suffix, FALSE, status);
		}
	}
	fn_composite_name_destroy(suffix);
	return (*ctxp != NULL ? 0 : -1);
}


static int
split_cname(const FN_composite_name_t *name, FN_composite_name_t **last,
    FN_composite_name_t **lead)
{
	void	*iter;

	(void) fn_composite_name_last(name, &iter);
	*last = fn_composite_name_suffix(name, iter);
	*lead = fn_composite_name_prefix(name, iter);
	if (*last == NULL || *lead == NULL) {
		log_mem_failure();
		fn_composite_name_destroy(*last);
		fn_composite_name_destroy(*lead);
		return (-1);
	}
	return (0);
}


static int
list_ctx_and_or_nns(FN_ctx_t *ctx, FN_ctx_t *prefix_ctx,
    struct dir_entry **entries_p, FN_status_t *status)
{
	FN_ctx_t	*nns_ctx;
	int		rc;

	if (!need_nns_only(ctx, prefix_ctx, status)) {
		if (list_ctx(ctx, entries_p, status) != 0) {
			return (-1);
		}
		if (!need_ctx_and_nns(ctx, status)) {
			return (0);
		}
	}
	nns_ctx = lookup_ctx(ctx, slash_cname, FALSE, status);
	if (nns_ctx == NULL) {
		return (0);
	}
	rc = list_ctx(nns_ctx, entries_p, status);
	fn_ctx_handle_destroy(nns_ctx);
	return (rc);
}


/*
 * True if ctx has a hierarchical syntax with a non-slash separator
 * and prefix_ctx either has the same syntax or does not provide any
 * syntax ("..." should be the only example of the latter condition).
 */
static bool_t
need_nns_only(FN_ctx_t *ctx, FN_ctx_t *prefix_ctx, FN_status_t *status)
{
	FN_attrset_t	*syn;
	FN_attrset_t	*prefix_syn;
	bool_t		retval;

	syn = fn_ctx_get_syntax_attrs(ctx, empty_cname, status);
	if (syn == NULL || !non_slash_hierarchy(syn)) {
		fn_attrset_destroy(syn);
		return (FALSE);
	}
	/*
	 * ctx is hierarchical and not slash-separated.  How about prefix_ctx?
	 */
	prefix_syn = fn_ctx_get_syntax_attrs(prefix_ctx, empty_cname, status);
	retval = (prefix_syn == NULL) || syntax_attrs_equal(syn, prefix_syn);

	fn_attrset_destroy(syn);
	fn_attrset_destroy(prefix_syn);
	return (retval);
}


/*
 * True if ctx has a slash-separated hierarchical syntax.
 */
static bool_t
need_ctx_and_nns(FN_ctx_t *ctx, FN_status_t *status)
{
	FN_attrset_t	*syn;
	bool_t		retval;

	syn = fn_ctx_get_syntax_attrs(ctx, empty_cname, status);
	if (syn == NULL) {
		return (FALSE);
	}
	retval = slash_hierarchy(syn);
	fn_attrset_destroy(syn);
	return (retval);
}


static int
list_ctx(FN_ctx_t *ctx, struct dir_entry **entries_p, FN_status_t *status)
{
	FN_attrset_t		*syntax;
	FN_compound_name_t	*name;
	int			retval;

	syntax = fn_ctx_get_syntax_attrs(ctx, empty_cname, status);
	if (syntax == NULL) {
		logstat(status, "", "bad syntax attributes");
		return (-1);
	}
	name =
	    fn_compound_name_from_syntax_attrs(syntax, empty_string, status);
	if (name == NULL) {
		logstat(status, "", "could not create compound name");
		fn_attrset_destroy(syntax);
		return (-1);
	}
	if (!non_slash_hierarchy(syntax)) {
		fn_attrset_destroy(syntax);
		syntax = NULL;
	}
	retval = list_ctx_aux(ctx, name, syntax, entries_p, status);
	fn_attrset_destroy(syntax);
	fn_compound_name_destroy(name);
	return (retval);
}


static int
list_ctx_aux(FN_ctx_t *ctx, FN_compound_name_t *name,
    const FN_attrset_t *syntax, struct dir_entry **entries_p,
    FN_status_t *status)
{
	FN_bindinglist_t	*bindings;
	FN_string_t		*child;
	FN_ref_t		*ref;
	unsigned int		stat;
	int			rc = 0;
	void			*iter;

	bindings = fn_ctx_list_bindings(ctx, empty_cname, status);
	if (bindings == NULL) {
		return (0);
	}
	while ((child = fn_bindinglist_next(bindings, &ref, status)) != NULL) {
		if (fn_compound_name_append_comp(name, child, &stat) == 0) {
			rc = -1;
			break;
		}
		if (add_name_to_dirlist(name, entries_p) != 0) {
			rc = -1;
			break;
		}
		if (syntax != NULL) {
			/* Traverse hierarchy. */
			ctx = fn_ctx_handle_from_ref(ref, XFN2(0) status);
			if (ctx != NULL) {
				rc = list_ctx_aux(ctx, name, syntax, entries_p,
				    status);
				fn_ctx_handle_destroy(ctx);
				if (rc != 0) {
					break;
				}
			}
		}
		fn_ref_destroy(ref);
		fn_string_destroy(child);
		(void) fn_compound_name_last(name, &iter);
		(void) fn_compound_name_next(name, &iter);
		(void) fn_compound_name_delete_comp(name, &iter);
	}
	fn_string_destroy(child);
	fn_bindinglist_destroy(bindings XFN1(status));
	return (rc);
}


static int
add_name_to_dirlist(const FN_compound_name_t *name,
    struct dir_entry **entries_p)
{
	FN_string_t		*string;
	char			*str;
	unsigned int		stat;
	struct dir_entry	*entry;

	string = fn_string_from_compound_name(name);
	if (string == NULL) {
		log_mem_failure();
		return (-1);
	}
	str = (char *)fn_string_str(string, &stat);
	if (str != NULL) {
		str = auto_rddir_strdup(str);
	}
	fn_string_destroy(string);
	if (str == NULL) {
		log_mem_failure();
		return (-1);
	}

	/* LINTED pointer alignment */
	entry = (struct dir_entry *)
		auto_rddir_malloc(sizeof (*entry));
	if (entry == NULL) {
		log_mem_failure();
		free(str);
		return (-1);
	}
	(void) memset((char *)entry, 0, sizeof (*entry));
	entry->name = str;
	entry->next = *entries_p;
	*entries_p = entry;
	return (0);
}


/*
 * Identifiers of syntax attributes for direction and separator.
 */

static const FN_identifier_t syntax_direction = {
	FN_ID_STRING,
	sizeof ("fn_std_syntax_direction") - 1,
	"fn_std_syntax_direction"
};

static const FN_identifier_t syntax_separator = {
	FN_ID_STRING,
	sizeof ("fn_std_syntax_separator") - 1,
	"fn_std_syntax_separator"
};


static bool_t
slash_hierarchy(const FN_attrset_t *syntax)
{
	const FN_attrvalue_t	*dir = get_attrval(syntax, &syntax_direction);
	const FN_attrvalue_t	*sep = get_attrval(syntax, &syntax_separator);

	return (dir != NULL &&
	    memcmp("flat", dir->contents, dir->length) != 0 &&
	    sep != NULL &&
	    memcmp("/", sep->contents, sep->length) == 0);
}


static bool_t
non_slash_hierarchy(const FN_attrset_t *syntax)
{
	const FN_attrvalue_t	*dir = get_attrval(syntax, &syntax_direction);
	const FN_attrvalue_t	*sep = get_attrval(syntax, &syntax_separator);

	return (dir != NULL &&
	    memcmp("flat", dir->contents, dir->length) != 0 &&
	    sep != NULL &&
	    memcmp("/", sep->contents, sep->length) != 0);
}


static bool_t
syntax_attrs_equal(const FN_attrset_t *syn1, const FN_attrset_t *syn2)
{
	const FN_attribute_t	*attr;
	const FN_attrvalue_t	*val1;
	const FN_attrvalue_t	*val2;
	void			*iter1;
	void			*iter2;

	if (fn_attrset_count(syn1) != fn_attrset_count(syn2)) {
		return (FALSE);
	}
	for (attr = fn_attrset_first(syn1, &iter1);
	    attr != NULL;
	    attr = fn_attrset_next(syn1, &iter1)) {
		val1 = fn_attribute_first(attr, &iter2);
		val2 = get_attrval(syn2, fn_attribute_identifier(attr));
		if ((val1 == NULL && val2 != NULL) ||
		    (val1 != NULL && val2 == NULL)) {
			return (FALSE);
		}
		if (val1 != NULL && val2 != NULL) {
			if (val1->length != val2->length ||
			    memcmp(val1->contents, val2->contents,
				    val1->length) != 0) {
				return (FALSE);
			}
		}
	}
	return (TRUE);
}


static const FN_attrvalue_t *
get_attrval(const FN_attrset_t *attrs, const FN_identifier_t *attr_id)
{
	const FN_attribute_t	*attr;
	void			*iter;

	attr = fn_attrset_get(attrs, attr_id);
	if (attr != NULL) {
		return (fn_attribute_first(attr, &iter));
	} else {
		return (NULL);
	}
}


static FN_ctx_t *
lookup_ctx(FN_ctx_t *ctx, const FN_composite_name_t *name, bool_t log,
    FN_status_t *status)
{
	FN_ref_t	*ref;
	char		*msg;

	ref = fn_ctx_lookup(ctx, name, status);
	if (ref == NULL) {
		ctx = NULL;
		msg = "lookup failed";
	} else {
		ctx = fn_ctx_handle_from_ref(ref, XFN2(0) status);
		fn_ref_destroy(ref);
		if (ctx == NULL) {
			msg = "could not construct context handle";
		}
	}
	if (ctx == NULL && verbose && (log || transient(status))) {
		logstat(status, "", msg);
	}
	return (ctx);
}
/*
 * 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
 */
/*
 * ns_fnutils.c
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <synch.h>
#include <rpc/rpc.h>
#include <xfn/xfn.h>
#include "automount.h"
#include "ns_fnutils.h"


/*
 * FNS file system reference and address types.  Each array is indexed
 * using the corresponding enumeration (reftype_t or addrtype_t).
 */
const char *reftypes[] = {
	"onc_fn_fs",
};

const char *addrtypes[] = {
	"onc_fn_fs_mount",
	"onc_fn_fs_host",
	"onc_fn_fs_user",
};


FN_string_t		*empty_string = NULL;
FN_composite_name_t	*empty_cname = NULL;
FN_composite_name_t	*slash_cname = NULL;


int
init_fn(void)
{
	static mutex_t	init_lock = DEFAULTMUTEX;

	if (slash_cname != NULL) {
		return (0);
	}

	mutex_lock(&init_lock);

	if (empty_string == NULL) {
		if ((empty_string = fn_string_create()) == NULL) {
			log_mem_failure();
			goto unlock;
		}
	}
	if (empty_cname == NULL) {
		if ((empty_cname = new_cname("")) == NULL) {
			goto unlock;
		}
	}
	if (slash_cname == NULL) {
		if ((slash_cname = new_cname("/")) == NULL) {
			goto unlock;
		}
	}
unlock:
	mutex_unlock(&init_lock);
	return ((slash_cname != NULL) ? 0 : -1);
}


FN_composite_name_t *
new_cname(const char *str)
{
	FN_string_t		*string;
	FN_composite_name_t	*cname;

	string = fn_string_from_str((unsigned char *)str);
	if (string == NULL) {
		if (verbose) {
			syslog(LOG_ERR, "Could not create FNS string object");
		}
		return (NULL);
	}
	cname = fn_composite_name_from_string(string);
	fn_string_destroy(string);
	if ((cname == NULL) && verbose) {
		syslog(LOG_ERR, "Could not create FNS composite name object");
	}
	return (cname);
}


reftype_t
reftype(const FN_ref_t *ref)
{
	reftype_t	rtype;

	for (rtype = 0; rtype < NUM_REFTYPES; rtype++) {
		if (ident_str_equal(fn_ref_type(ref), reftypes[rtype])) {
			break;
		}
	}
	return (rtype);
}


addrtype_t
addrtype(const FN_ref_addr_t *addr)
{
	addrtype_t		atype;
	const FN_identifier_t	*ident = fn_ref_addr_type(addr);

	for (atype = 0; atype < NUM_ADDRTYPES; atype++) {
		if (ident_str_equal(ident, addrtypes[atype])) {
			break;
		}
	}
	return (atype);
}


bool_t
ident_equal(const FN_identifier_t *id1, const FN_identifier_t *id2)
{
	return ((id1->format == id2->format) &&
	    (id1->length == id2->length) &&
	    (memcmp(id1->contents, id2->contents, id1->length) == 0));
}


bool_t
ident_str_equal(const FN_identifier_t *id, const char *str)
{
	return ((id->format == FN_ID_STRING) &&
	    (id->length == strlen(str)) &&
	    (strncmp(str, id->contents, id->length) == 0));
}


void
logstat(const FN_status_t *status, const char *msg1, const char *msg2)
{
	FN_string_t	*desc_string;
	const char	*desc = NULL;

	if (verbose) {
		desc_string = fn_status_description(status, DETAIL, NULL);
		if (desc_string != NULL) {
			desc = (const char *)fn_string_str(desc_string, NULL);
		}
		if (desc == NULL) {
			desc = "(no status description)";
		}
		syslog(LOG_ERR, "FNS %s %s: %s (%u)",
		    msg1, msg2, desc, fn_status_code(status));
		fn_string_destroy(desc_string);
	}
}


bool_t
transient(const FN_status_t *status)
{
	unsigned int statcode;

	statcode = fn_status_code(status);
	if (statcode == FN_E_LINK_ERROR) {
		statcode = fn_status_link_code(status);
	}
	switch (statcode) {
	case FN_E_COMMUNICATION_FAILURE:
	case FN_E_CTX_UNAVAILABLE:
	case FN_E_INSUFFICIENT_RESOURCES:
	case FN_E_INVALID_ENUM_HANDLE:
	case FN_E_PARTIAL_RESULT:
	case FN_E_UNSPECIFIED_ERROR:
		return (TRUE);
	default:
		return (FALSE);
	}
}


void
log_mem_failure(void)
{
	if (verbose) {
		syslog(LOG_ERR, "Memory allocation failed");
	}
}
/*
 * 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
 */
/*
 * ns_fnutils.h
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _NS_FNUTILS_H
#define	_NS_FNUTILS_H

#include <rpc/rpc.h>
#include <xfn/xfn.h>

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Enable compilation for either XFN1 (pre-2.6) or XFN2 environment.
 */
#ifdef	XFN1ENV
#define	XFN1(x) /* cstyle */, x
#define	XFN2(x)
#define	_fn_ctx_handle_from_initial_with_uid(uid, auth, status) \
	    fn_ctx_handle_from_initial(status)
#else
#define	XFN1(x)
#define	XFN2(x) x,
#endif

/*
 * FNS file system reference and address types.  Each (char *) array is indexed
 * using the corresponding enumeration.
 */
extern const char *reftypes[];

typedef enum {
	REF_FN_FS,
	NUM_REFTYPES	/* Not a ref type, but rather a count of them */
} reftype_t;

extern const char *addrtypes[];

typedef enum {
	ADDR_MOUNT,
	ADDR_HOST,
	ADDR_USER,
	NUM_ADDRTYPES	/* Not an addr type, but rather a count of them */
} addrtype_t;


/*
 * Initialization for FNS.  Return 0 on success.
 */
extern int
init_fn(void);

/*
 * Allocate a new composite name.  On error, log an error message and
 * return NULL.
 */
extern FN_composite_name_t *
new_cname(const char *);

/*
 * Return the type of a reference, or NUM_REFTYPES if the type is unknown.
 */
extern reftype_t
reftype(const FN_ref_t *);

/*
 * Return the type of an address, or NUM_ADDRTYPES if the type is unknown.
 */
extern addrtype_t
addrtype(const FN_ref_addr_t *);

/*
 * Determine whether two identifiers match.
 */
extern bool_t
ident_equal(const FN_identifier_t *, const FN_identifier_t *);

/*
 * Determine whether an identifier and a string match.
 */
extern bool_t
ident_str_equal(const FN_identifier_t *, const char *);

/*
 * Syslog an error message and status info (with detail level DETAIL)
 * if "verbose" is set.
 */
#define	DETAIL	0
extern void
logstat(const FN_status_t *, const char *msg1, const char *msg2);

/*
 * Determine whether an error is potentially transient.
 */
extern bool_t
transient(const FN_status_t *);

/*
 * Log a memory allocation failure if "verbose" is true.
 */
extern void
log_mem_failure(void);

extern FN_ctx_t *
_fn_ctx_handle_from_initial_with_uid(uid_t, unsigned int, FN_status_t *);

extern FN_string_t		*empty_string;
extern FN_composite_name_t	*empty_cname;
extern FN_composite_name_t	*slash_cname;	/* "/" */


#ifdef	__cplusplus
}
#endif

#endif	/* _NS_FNUTILS_H */
/*
 * 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
 */
/*
 *	ns_generic.c
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <stdlib.h>
#include <nsswitch.h>
#include <sys/param.h>
#include <netdb.h>
#include <errno.h>
#include <assert.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>
#include "automount.h"

/*
 * Each name service is represented by a ns_info structure.
 */
struct ns_info {
	char	*ns_name;		/* service name */
	void	(*ns_init)();		/* initialization routine */
	int	(*ns_getmapent)();	/* get map entry given key */
	int	(*ns_loadmaster)();	/* load master map */
	int	(*ns_loaddirect)();	/* load direct map */
	int	(*ns_getmapkeys)();	/* readdir */
};

static struct ns_info ns_info[] = {

	"files",   init_files,  getmapent_files,
	loadmaster_files, loaddirect_files,
	getmapkeys_files,

	/* Hammerhead: "ldap" backend removed (libsldap chain removal). */

	"nis",	   init_nis,	getmapent_nis,
	loadmaster_nis,   loaddirect_nis,
	getmapkeys_nis,

	NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

static struct ns_info *get_next_ns(struct __nsw_lookup **, int);

void
ns_setup(char **stack, char ***stkptr)
{
	struct ns_info *nsp;

	for (nsp = ns_info; nsp->ns_name; nsp++) {
		nsp->ns_init(stack, stkptr);
	}
}

static struct ns_info *
get_next_ns(curr_ns, curr_nserr)
	struct __nsw_lookup **curr_ns;
	int curr_nserr;
{
	static struct __nsw_switchconfig *conf = NULL;
	enum __nsw_parse_err pserr;
	struct __nsw_lookup *lkp;
	struct ns_info *nsp;

	if (conf == NULL) {
		/* __nsw_getconfig() is protected by a lock */
		conf = __nsw_getconfig("automount", &pserr);
		if (conf == NULL) {
			return (NULL);
		}
	}

	if (*curr_ns == NULL)
		/* first time */
		lkp = conf->lookups;
	else {
		lkp = *curr_ns;
		/* __NSW_ACTION is MT-Safe */
		if (__NSW_ACTION(lkp, curr_nserr) == __NSW_RETURN)
			return (NULL);
		lkp = lkp->next;
	}

	for (; lkp; lkp = lkp->next) {
		for (nsp = ns_info; nsp->ns_name; nsp++) {
			if (strcmp(lkp->service_name, nsp->ns_name) == 0) {
				*curr_ns = lkp;
				return (nsp);
			}
		}
		/*
		 * Note: if we get here then we've found
		 * an unsupported name service.
		 */
	}

	return (NULL);
}

int
getmapent(key, mapname, ml, stack, stkptr, iswildcard, isrestricted)
	char *key, *mapname;
	struct mapline *ml;
	char **stack, ***stkptr;
	bool_t *iswildcard;
	bool_t isrestricted;
{
	struct __nsw_lookup *curr_ns = NULL;
	int ns_err = __NSW_SUCCESS;
	struct ns_info *nsp;

	if (strcmp(mapname, "-hosts") == 0) {
		(void) strcpy(ml->linebuf, "-hosts");
		return (__NSW_SUCCESS);
	}

	if (*mapname == '/') 		/* must be a file */
		return (getmapent_files(key, mapname, ml, stack, stkptr,
					iswildcard, isrestricted));

	while ((nsp = get_next_ns(&curr_ns, ns_err)) != NULL) {
		ns_err = nsp->ns_getmapent(key, mapname, ml, stack, stkptr,
						iswildcard, isrestricted);
		if (ns_err == __NSW_SUCCESS)
			return (__NSW_SUCCESS);
	}

	return (__NSW_UNAVAIL);
}

int
loadmaster_map(mapname, defopts, stack, stkptr)
	char *mapname, *defopts;
	char **stack, ***stkptr;
{
	struct __nsw_lookup *curr_ns = NULL;
	int ns_err = __NSW_SUCCESS;
	struct ns_info *nsp;

	if (*mapname == '/')		/* must be a file */
		return (loadmaster_files(mapname, defopts, stack, stkptr));

	while ((nsp = get_next_ns(&curr_ns, ns_err)) != NULL) {
		ns_err = nsp->ns_loadmaster(mapname, defopts, stack, stkptr);
		if (ns_err == __NSW_SUCCESS)
			return (__NSW_SUCCESS);
	}

	return (__NSW_UNAVAIL);
}

int
loaddirect_map(mapname, localmap, defopts, stack, stkptr)
	char *mapname, *localmap, *defopts;
	char **stack, ***stkptr;
{
	struct __nsw_lookup *curr_ns = NULL;
	int ns_err = __NSW_SUCCESS;
	struct ns_info *nsp;

	if (*mapname == '/')		/* must be a file */
		return (loaddirect_files(mapname, localmap, defopts,
				stack, stkptr));

	while ((nsp = get_next_ns(&curr_ns, ns_err)) != NULL) {
		ns_err = nsp->ns_loaddirect(mapname, localmap, defopts, stack,
					stkptr);
		if (ns_err == __NSW_SUCCESS)
			return (__NSW_SUCCESS);
	}

	return (__NSW_UNAVAIL);
}

int
gethostkeys(mapname, list, error, cache_time)
	char *mapname;
	struct dir_entry **list;
	int *error;
	int *cache_time;
{
	char *buffer, **p;
	int bufferlen = 1000;
	struct dir_entry *last = NULL;
	struct hostent ent;

#ifdef lint
	mapname = mapname;
#endif

	*cache_time = RDDIR_CACHE_TIME * 2;
	*error = 0;
	if (trace  > 1)
		trace_prt(1, "gethostkeys called\n");

	if (sethostent(1)) {
		syslog(LOG_ERR, "gethostkeys: sethostent failed");
		*error = EIO;
		return (__NSW_UNAVAIL);
	}

	buffer = (char *)malloc(bufferlen);
	if (buffer == NULL) {
		syslog(LOG_ERR, "gethostkeys: malloc of buffer failed");
		*error = ENOMEM;
		return (__NSW_UNAVAIL);
	}

	while (gethostent_r(&ent, buffer, bufferlen, error)) {
		/*
		 * add canonical name
		 */
		if (add_dir_entry(ent.h_name, list, &last)) {
			*error = ENOMEM;
			goto done;
		}
		if (ent.h_aliases == NULL)
			goto done;	/* no aliases */
		for (p = ent.h_aliases; *p != 0; p++) {
			if (strcmp(*p, ent.h_name) != 0) {
				/*
				 * add alias only if different
				 * from canonical name
				 */
				if (add_dir_entry(*p, list, &last)) {
					*error = ENOMEM;
					goto done;
				}
			}
		}
		assert(last != NULL);
	}
done:	if (*list != NULL) {
		/*
		 * list of entries found
		 */
		*error = 0;
	}
	endhostent();

	return (__NSW_SUCCESS);
}

/*
 * enumerate all entries in the map in the various name services.
 */
int
getmapkeys(mapname, list, error, cache_time, stack, stkptr, uid)
	char *mapname;
	struct dir_entry **list;
	int *error;
	int *cache_time;
	char **stack, ***stkptr;
	uid_t uid;

{
	struct __nsw_lookup *curr_ns = NULL;
	int ns_err = __NSW_SUCCESS;
	int success = 0;
	struct ns_info *nsp;

	if (*mapname == '/') 		/* must be a file */
		return (getmapkeys_files(mapname, list, error, cache_time,
				stack, stkptr));
	if (strcmp(mapname, "-hosts") == 0) {
		return (gethostkeys(mapname, list, error, cache_time));
	}

	while ((nsp = get_next_ns(&curr_ns, ns_err)) != NULL) {
		ns_err = nsp->ns_getmapkeys(mapname, list, error,
				cache_time, stack, stkptr);
		if (*error == 0) {
			/*
			 * return success if listing was successful
			 * for at least one name service
			 */
			success++;
		}

		/*
		 * XXX force next name service
		 */
		if (ns_err != __NSW_UNAVAIL)
			ns_err = __NSW_NOTFOUND;
	}
	if (success) {
		/*
		 * if succeeded at least once, return error=0
		 */
		*error = 0;
	};

	return (success ? __NSW_SUCCESS : __NSW_NOTFOUND);
}
/*
 * 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
 */
/*
 *	ns_nis.c
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <ctype.h>
#include <nsswitch.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/systeminfo.h>
#include <rpc/rpc.h>
#include <rpcsvc/nfs_prot.h>
#include <rpcsvc/ypclnt.h>
#include <rpcsvc/yp_prot.h>
#include <sys/errno.h>
#include "automount.h"

#define	KEY		0
#define	CONTENTS	1

static int replace_undscr_by_dot(char *);
static int nis_err(int);

static char nis_mydomain[YPMAXDOMAIN];

struct dir_cbdata {
	struct dir_entry **list;
	struct dir_entry *last;
	int error;
};

static int readdir_callback(int, char *, int, const char *,
				int, struct dir_cbdata *);

void
init_nis(char **stack, char ***stkptr)
{
#ifdef lint
	stack = stack;
	stkptr = stkptr;
#endif /* lint */

	(void) sysinfo(SI_SRPC_DOMAIN, nis_mydomain, sizeof (nis_mydomain));
}

/*ARGSUSED*/
int
getmapent_nis(key, map, ml, stack, stkptr, iswildcard, isrestricted)
	char *key, *map;
	struct mapline *ml;
	char **stack;
	char ***stkptr;
	bool_t *iswildcard;
	bool_t isrestricted;
{
	char *nisline = NULL;
	char *my_map = NULL;
	char *lp, *lq;
	int nislen, len;
	int nserr;

	if (iswildcard)
		*iswildcard = FALSE;
	nserr = yp_match(nis_mydomain, map, key, strlen(key),
						&nisline, &nislen);
	if (nserr == YPERR_MAP) {
		my_map = strdup(map);
		if (my_map == NULL) {
			syslog(LOG_ERR,
				"getmapent_nis: memory alloc failed: %m");
			return (__NSW_UNAVAIL);
		}
		if (replace_undscr_by_dot(my_map))
			nserr = yp_match(nis_mydomain, my_map, key,
					strlen(key), &nisline, &nislen);
	}

	if (nserr) {
		if (nserr == YPERR_KEY) {
			/*
			 * Try the default entry "*"
			 */
			if (my_map == NULL)
				nserr = yp_match(nis_mydomain, map, "*", 1,
						&nisline, &nislen);
			else
				nserr = yp_match(nis_mydomain, my_map, "*", 1,
						&nisline, &nislen);
			if (!nserr && iswildcard)
				*iswildcard = TRUE;
		} else {
			if (verbose)
				syslog(LOG_ERR, "%s: %s",
					map, yperr_string(nserr));
			nserr = 1;
		}
	}
	if (my_map != NULL)
		free(my_map);

	nserr = nis_err(nserr);
	if (nserr)
		goto done;

	/*
	 * at this point we are sure that yp_match succeeded
	 * so massage the entry by
	 * 1. ignoring # and beyond
	 * 2. trim the trailing whitespace
	 */
	if (lp = strchr(nisline, '#'))
		*lp = '\0';
	len = strlen(nisline);
	if (len == 0) {
		nserr = __NSW_NOTFOUND;
		goto done;
	}
	lp = &nisline[len - 1];
	while (lp > nisline && isspace(*lp))
		*lp-- = '\0';
	if (lp == nisline) {
		nserr = __NSW_NOTFOUND;
		goto done;
	}
	(void) strcpy(ml->linebuf, nisline);
	lp = ml->linebuf;
	lq = ml->lineqbuf;
	unquote(lp, lq);
	/* now we have the correct line */

	nserr = __NSW_SUCCESS;
done:
	if (nisline)
		free((char *)nisline);
	return (nserr);

}

int
loadmaster_nis(mapname, defopts, stack, stkptr)
	char *mapname, *defopts;
	char **stack;
	char ***stkptr;
{
	int first, err;
	char *key, *nkey, *val;
	int kl, nkl, vl;
	char dir[256], map[256], qbuff[256];
	char *pmap, *opts, *my_mapname;
	int count = 0;

	first = 1;
	key  = NULL; kl  = 0;
	nkey = NULL; nkl = 0;
	val  = NULL; vl  = 0;

	/*
	 * need a private copy of mapname, because we may change
	 * the underscores by dots. We however do not want the
	 * orignal to be changed, as we may want to use the
	 * original name in some other name service
	 */
	my_mapname = strdup(mapname);
	if (my_mapname == NULL) {
		syslog(LOG_ERR, "loadmaster_yp: memory alloc failed: %m");
		/* not the name svc's fault but ... */
		return (__NSW_UNAVAIL);
	}
	for (;;) {
		if (first) {
			first = 0;
			err = yp_first(nis_mydomain, my_mapname,
				&nkey, &nkl, &val, &vl);

			if ((err == YPERR_MAP) &&
			    (replace_undscr_by_dot(my_mapname)))
				err = yp_first(nis_mydomain, my_mapname,
					&nkey, &nkl, &val, &vl);

			if ((err == YPERR_DOMAIN) || (err == YPERR_YPBIND)) {
				syslog(LOG_ERR,
					"can't read nis map %s: %s - retrying",
					my_mapname, yperr_string(err));
				while ((err == YPERR_DOMAIN) ||
					(err == YPERR_YPBIND)) {
					(void) sleep(20);
					err = yp_first(nis_mydomain, my_mapname,
						&nkey, &nkl, &val, &vl);
				}
				syslog(LOG_ERR,
					"nis map %s: read OK.", my_mapname);
			}
		} else {
			err = yp_next(nis_mydomain, my_mapname, key, kl,
				&nkey, &nkl, &val, &vl);
		}
		if (err) {
			if (err != YPERR_NOMORE && err != YPERR_MAP)
				if (verbose)
					syslog(LOG_ERR, "%s: %s",
					my_mapname, yperr_string(err));
			break;
		}
		if (key)
			free(key);
		key = nkey;
		kl = nkl;


		if (kl >= 256 || vl >= 256)
			break;
		if (kl < 2 || vl < 1)
			break;
		if (isspace(*key) || *key == '#')
			break;
		(void) strncpy(dir, key, kl);
		dir[kl] = '\0';
		if (macro_expand("", dir, qbuff, sizeof (dir))) {
			syslog(LOG_ERR,
			    "%s in NIS map %s: entry too long (max %d chars)",
			    dir, my_mapname, sizeof (dir) - 1);
			break;
		}
		(void) strncpy(map, val, vl);
		map[vl] = '\0';
		if (macro_expand(dir, map, qbuff, sizeof (map))) {
			syslog(LOG_ERR,
			    "%s in NIS map %s: entry too long (max %d chars)",
			    map, my_mapname, sizeof (map) - 1);
			break;
		}
		pmap = map;
		while (*pmap && isspace(*pmap))
			pmap++;		/* skip blanks in front of map */
		opts = pmap;
		while (*opts && !isspace(*opts))
			opts++;
		if (*opts) {
			*opts++ = '\0';
			while (*opts && isspace(*opts))
				opts++;
			if (*opts == '-')
				opts++;
			else
				opts = defopts;
		}
		free(val);

		/*
		 * Check for no embedded blanks.
		 */
		if (strcspn(opts, " 	") == strlen(opts)) {
			dirinit(dir, pmap, opts, 0, stack, stkptr);
			count++;
		} else {
pr_msg("Warning: invalid entry for %s in NIS map %s ignored.\n", dir, mapname);
		}

	}
	if (my_mapname)
		free(my_mapname);

	/*
	 * In the context of a master map, if no entry is
	 * found, it is like NOTFOUND
	 */
	if (count > 0 && err == YPERR_NOMORE)
		return (__NSW_SUCCESS);
	else {
		if (err)
			return (nis_err(err));
		else
			/*
			 * This case will happen if map is empty
			 *  or none of the entries is valid
			 */
			return (__NSW_NOTFOUND);
	}
}

int
loaddirect_nis(nismap, localmap, opts, stack, stkptr)
	char *nismap, *localmap, *opts;
	char **stack;
	char ***stkptr;
{
	int first, err, count;
	char *key, *nkey, *val, *my_nismap;
	int kl, nkl, vl;
	char dir[100];

	first = 1;
	key  = NULL; kl  = 0;
	nkey = NULL; nkl = 0;
	val  = NULL; vl  = 0;
	count = 0;
	my_nismap = NULL;

	my_nismap = strdup(nismap);
	if (my_nismap == NULL) {
		syslog(LOG_ERR, "loadmaster_yp: memory alloc failed: %m");
		return (__NSW_UNAVAIL);
	}
	for (;;) {
		if (first) {
			first = 0;
			err = yp_first(nis_mydomain, my_nismap, &nkey, &nkl,
					&val, &vl);

			if ((err == YPERR_MAP) &&
			    (replace_undscr_by_dot(my_nismap)))
				err = yp_first(nis_mydomain, my_nismap,
						&nkey, &nkl, &val, &vl);

			if ((err == YPERR_DOMAIN) || (err == YPERR_YPBIND)) {
				syslog(LOG_ERR,
					"can't read nis map %s: %s - retrying",
					my_nismap, yperr_string(err));
				while ((err == YPERR_DOMAIN) ||
					(err == YPERR_YPBIND)) {
					(void) sleep(20);
					err = yp_first(nis_mydomain, my_nismap,
						&nkey, &nkl, &val, &vl);
				}
				syslog(LOG_ERR,
					"nis map %s: read OK.", my_nismap);
			}
		} else {
			err = yp_next(nis_mydomain, my_nismap, key, kl,
					&nkey, &nkl, &val, &vl);
		}
		if (err) {
			if (err != YPERR_NOMORE && err != YPERR_MAP)
				syslog(LOG_ERR, "%s: %s",
					my_nismap, yperr_string(err));
			break;
		}
		if (key)
			free(key);
		key = nkey;
		kl = nkl;

		if (kl < 2 || kl >= 100)
			continue;
		if (isspace(*key) || *key == '#')
			continue;
		(void) strncpy(dir, key, kl);
		dir[kl] = '\0';

		dirinit(dir, localmap, opts, 1, stack, stkptr);
		count++;
		free(val);
	}

	if (my_nismap)
		free(my_nismap);

	if (count > 0 && err == YPERR_NOMORE)
			return (__NSW_SUCCESS);
	else
		return (nis_err(err));

}

static int
replace_undscr_by_dot(map)
	char *map;
{
	int ret_val = 0;

	while (*map) {
		if (*map == '_') {
			ret_val = 1;
			*map = '.';
		}
		map++;
	}
	return (ret_val);
}

static int
nis_err(err)
	int err;
{
	switch (err) {
	case 0:
		return (__NSW_SUCCESS);
	case YPERR_KEY:
		return (__NSW_NOTFOUND);
	case YPERR_MAP:
		return (__NSW_UNAVAIL);
	default:
		return (__NSW_UNAVAIL);
	}
}

int
getmapkeys_nis(nsmap, list, error, cache_time, stack, stkptr)
	char *nsmap;
	struct dir_entry **list;
	int *error;
	int *cache_time;
	char **stack;
	char ***stkptr;
{
	int nserr;
	struct dir_cbdata readdir_cbdata;
	struct ypall_callback cback;
	char *my_map = NULL;

	char *key = NULL, *val = NULL;
	int nkl, vl;

#ifdef lint
	stack = stack;
	stkptr = stkptr;
#endif /* lint */

	*cache_time = RDDIR_CACHE_TIME;

	/*
	 * XXX Hack to determine if we need to replace '_' with '.'
	 * Have to use yp_first() since yp_all() simply fails if
	 * the map is not present
	 */
	my_map = strdup(nsmap);
	if (my_map == NULL) {
		syslog(LOG_ERR,
			"getmapkeys_nis: memory alloc failed: %m");
		*error = ENOMEM;
		return (__NSW_UNAVAIL);
	}
	nserr = yp_first(nis_mydomain, my_map, &key, &nkl, &val, &vl);
	if (nserr == YPERR_MAP) {
		if (replace_undscr_by_dot(my_map)) {
			nserr = yp_first(nis_mydomain, my_map,
					&key, &nkl, &val, &vl);
		}
		if (nserr == YPERR_MAP) {
			/*
			 * map not found
			 */
			*error = 0;	/* return an empty list */
			if (verbose) {
				syslog(LOG_ERR, "%s: %s",
					nsmap, yperr_string(nserr));
			}
			free(my_map);
			return (nis_err(nserr));
		}
	}
	if (key)
		free(key);
	if (val)
		free(val);

	readdir_cbdata.list = list;
	readdir_cbdata.last = NULL;
	readdir_cbdata.error = 0;

	cback.foreach = readdir_callback;
	cback.data = (char *)&readdir_cbdata;

	/*
	 * after all this song and dance we finally
	 * ask for the list of entries
	 */
	nserr = yp_all(nis_mydomain, my_map, &cback);

	free(my_map);
	*error = readdir_cbdata.error;
	if (nserr) {
		if (verbose)
			syslog(LOG_ERR, "%s: %s", nsmap, yperr_string(nserr));
		nserr = 1;
		if (*error == 0)
			*error = ENOENT;

		return (nis_err(nserr));
	}

	return (__NSW_SUCCESS);
}

static int
readdir_callback(instatus, inkey, inkeylen, inval, invallen, indata)
	int instatus;
	char *inkey;
	int inkeylen;
	const char *inval;
	int invallen;
	struct dir_cbdata *indata;
{
	struct dir_entry **list = indata->list;
	struct dir_entry *last = indata->last;
	char key[MAXPATHLEN];

#ifdef lint
	inval = inval;
	invallen = invallen;
#endif

	if (instatus != YP_TRUE)
		return (0);	/* next entry. yp_all may decide otherwise... */

	if (inkeylen == 0 || isspace(*inkey) || *inkey == '#')
		return (0);

	/*
	 * yp_all allocates inkey with two extra bytes which contain
	 * NEWLINE and null but these two bytes are not reflected in
	 * inkeylen.
	 */
	strncpy(key, inkey, inkeylen);
	key[inkeylen] = '\0';

	/*
	 * Wildcard entry should be ignored - following entries should continue
	 * to be read to corroborate with the way we search for entries in yp,
	 * i.e., first for an exact key match and then a wildcard, if there's
	 * no exact key match.
	 */
	if (key[0] == '*' && key[1] == '\0')
		return (0);

	if (add_dir_entry(key, list, &last)) {
		indata->error = ENOMEM;
		return (1);	/* get no more entries */
	}

	indata->last = last;
	indata->error = 0;

	return (0);
}
#!/bin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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) 2000 by Sun Microsystems, Inc.
# All rights reserved.
#
#ident	"%Z%%M%	%I%	%E% SMI"

echo_file usr/src/lib/libsldap/common/ns_sldap.h
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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) 1999,2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

/*
 * autofs share - dummy utility to accomodate autofs inclusion in
 * /etc/dfs/fstypes
 */
#include <stdio.h>
#include <libintl.h>

int
main(int argc, char **argv)
{
	fprintf(stderr, gettext("autofs share is not supported.\n"));
	return (1);
}
#!/sbin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"

. /lib/svc/share/smf_include.sh

case "$1" in
'start')
	/usr/lib/autofs/automountd
	/usr/sbin/automount &
	;;

'stop')
	/sbin/umountall -F autofs

	# Need to kill the entire service contract in case automount is hung
	# do to a misconfiguration, such as yp not up or responding.
	smf_kill_contract $2 TERM 1
	[ $? -ne 0 ] && exit 1
	;;

*)
	echo "Usage: $0 { start | stop }"
	;;
esac
exit 0
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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) 1999,2001 by Sun Microsystems, Inc.
 * All rights reserved.
 */

/*
 * autofs unshare - dummy utility to accomodate autofs inclusion in
 * /etc/dfs/fstypes
 */
#include <stdio.h>
#include <libintl.h>

int
main(int argc, char **argv)
{
	fprintf(stderr, gettext("autofs unshare is not supported.\n"));
	return (1);
}
/*
 * Please do not edit this file.
 * It was generated using rpcgen.
 */

#ifndef _AUTOFS_WEBNFS_H_RPCGEN
#define	_AUTOFS_WEBNFS_H_RPCGEN

#include <rpc/rpc.h>
#ifndef _KERNEL
#include <synch.h>
#include <thread.h>
#endif /* !_KERNEL */

#ifdef __cplusplus
extern "C" {
#endif

#define	WNL_PORT 2049
#define	WNL_MAXDATA 8192
#define	WNL_MAXNAMLEN 255
#define	WNL_FHSIZE 32
#define	WNL_FIFO_DEV -1
#define	WNL_NATIVEPATH 0x80
#define	WNL_SEC_NEGO 0x81
#define	WNLMODE_FMT 0170000
#define	WNLMODE_DIR 0040000
#define	WNLMODE_CHR 0020000
#define	WNLMODE_BLK 0060000
#define	WNLMODE_REG 0100000
#define	WNLMODE_LNK 0120000
#define	WNLMODE_SOCK 0140000
#define	WNLMODE_FIFO 0010000

enum wnl_stat {
	WNL_OK = 0,
	WNLERR_PERM = 1,
	WNLERR_NOENT = 2,
	WNLERR_IO = 5,
	WNLERR_NXIO = 6,
	WNLERR_ACCES = 13,
	WNLERR_EXIST = 17,
	WNLERR_XDEV = 18,
	WNLERR_NODEV = 19,
	WNLERR_NOTDIR = 20,
	WNLERR_ISDIR = 21,
	WNLERR_INVAL = 22,
	WNLERR_FBIG = 27,
	WNLERR_NOSPC = 28,
	WNLERR_ROFS = 30,
	WNLERR_OPNOTSUPP = 45,
	WNLERR_NAMETOOLONG = 63,
	WNLERR_NOTEMPTY = 66,
	WNLERR_DQUOT = 69,
	WNLERR_STALE = 70,
	WNLERR_REMOTE = 71,
	WNLERR_WFLUSH = 72
};
typedef enum wnl_stat wnl_stat;

enum wnl_ftype {
	WNL_NON = 0,
	WNL_REG = 1,
	WNL_DIR = 2,
	WNL_BLK = 3,
	WNL_CHR = 4,
	WNL_LNK = 5,
	WNL_SOCK = 6,
	WNL_BAD = 7,
	WNL_FIFO = 8
};
typedef enum wnl_ftype wnl_ftype;

struct wnl_fh {
	char data[WNL_FHSIZE];
};
typedef struct wnl_fh wnl_fh;

struct wnl_time {
	u_int seconds;
	u_int useconds;
};
typedef struct wnl_time wnl_time;

struct wnl_fattr {
	wnl_ftype type;
	u_int mode;
	u_int nlink;
	u_int uid;
	u_int gid;
	u_int size;
	u_int blocksize;
	u_int rdev;
	u_int blocks;
	u_int fsid;
	u_int fileid;
	wnl_time atime;
	wnl_time mtime;
	wnl_time ctime;
};
typedef struct wnl_fattr wnl_fattr;

typedef char *wnl_filename;

struct wnl_diropargs {
	wnl_fh dir;
	wnl_filename name;
};
typedef struct wnl_diropargs wnl_diropargs;

struct wnl_diropokres {
	wnl_fh file;
	wnl_fattr attributes;
};
typedef struct wnl_diropokres wnl_diropokres;

struct wnl_diropres {
	wnl_stat status;
	union {
		wnl_diropokres wnl_diropres;
	} wnl_diropres_u;
};
typedef struct wnl_diropres wnl_diropres;
#define	WNL3_FHSIZE 64

typedef u_longlong_t wnl_uint64;

typedef longlong_t wnl_int64;

typedef u_int wnl_uint32;

typedef char *wnl_filename3;

typedef wnl_uint64 wnl_fileid3;

typedef wnl_uint32 wnl_uid3;

typedef wnl_uint32 wnl_gid3;

typedef wnl_uint64 wnl_size3;

typedef wnl_uint32 wnl_mode3;

enum wnl_stat3 {
	WNL3_OK = 0,
	WNL3ERR_PERM = 1,
	WNL3ERR_NOENT = 2,
	WNL3ERR_IO = 5,
	WNL3ERR_NXIO = 6,
	WNL3ERR_ACCES = 13,
	WNL3ERR_EXIST = 17,
	WNL3ERR_XDEV = 18,
	WNL3ERR_NODEV = 19,
	WNL3ERR_NOTDIR = 20,
	WNL3ERR_ISDIR = 21,
	WNL3ERR_INVAL = 22,
	WNL3ERR_FBIG = 27,
	WNL3ERR_NOSPC = 28,
	WNL3ERR_ROFS = 30,
	WNL3ERR_MLINK = 31,
	WNL3ERR_NAMETOOLONG = 63,
	WNL3ERR_NOTEMPTY = 66,
	WNL3ERR_DQUOT = 69,
	WNL3ERR_STALE = 70,
	WNL3ERR_REMOTE = 71,
	WNL3ERR_BADHANDLE = 10001,
	WNL3ERR_NOT_SYNC = 10002,
	WNL3ERR_BAD_COOKIE = 10003,
	WNL3ERR_NOTSUPP = 10004,
	WNL3ERR_TOOSMALL = 10005,
	WNL3ERR_SERVERFAULT = 10006,
	WNL3ERR_BADTYPE = 10007,
	WNL3ERR_JUKEBOX = 10008
};
typedef enum wnl_stat3 wnl_stat3;

enum wnl_ftype3 {
	WNL_3REG = 1,
	WNL_3DIR = 2,
	WNL_3BLK = 3,
	WNL_3CHR = 4,
	WNL_3LNK = 5,
	WNL_3SOCK = 6,
	WNL_3FIFO = 7
};
typedef enum wnl_ftype3 wnl_ftype3;

struct wnl_specdata3 {
	wnl_uint32 specdata1;
	wnl_uint32 specdata2;
};
typedef struct wnl_specdata3 wnl_specdata3;

struct wnl_fh3 {
	struct {
		u_int data_len;
		char *data_val;
	} data;
};
typedef struct wnl_fh3 wnl_fh3;

struct wnl_time3 {
	wnl_uint32 seconds;
	wnl_uint32 nseconds;
};
typedef struct wnl_time3 wnl_time3;

struct wnl_fattr3 {
	wnl_ftype3 type;
	wnl_mode3 mode;
	wnl_uint32 nlink;
	wnl_uid3 uid;
	wnl_gid3 gid;
	wnl_size3 size;
	wnl_size3 used;
	wnl_specdata3 rdev;
	wnl_uint64 fsid;
	wnl_fileid3 fileid;
	wnl_time3 atime;
	wnl_time3 mtime;
	wnl_time3 ctime;
};
typedef struct wnl_fattr3 wnl_fattr3;

struct wnl_post_op_attr {
	bool_t attributes_follow;
	union {
		wnl_fattr3 attributes;
	} wnl_post_op_attr_u;
};
typedef struct wnl_post_op_attr wnl_post_op_attr;

struct wln_post_op_fh3 {
	bool_t handle_follows;
	union {
		wnl_fh3 handle;
	} wln_post_op_fh3_u;
};
typedef struct wln_post_op_fh3 wln_post_op_fh3;

struct wnl_diropargs3 {
	wnl_fh3 dir;
	wnl_filename3 name;
};
typedef struct wnl_diropargs3 wnl_diropargs3;

struct WNL_LOOKUP3args {
	wnl_diropargs3 what;
};
typedef struct WNL_LOOKUP3args WNL_LOOKUP3args;

struct WNL_LOOKUP3resok {
	wnl_fh3 object;
	wnl_post_op_attr obj_attributes;
	wnl_post_op_attr dir_attributes;
};
typedef struct WNL_LOOKUP3resok WNL_LOOKUP3resok;

struct WNL_LOOKUP3resfail {
	wnl_post_op_attr dir_attributes;
};
typedef struct WNL_LOOKUP3resfail WNL_LOOKUP3resfail;

struct WNL_LOOKUP3res {
	wnl_stat3 status;
	union {
		WNL_LOOKUP3resok res_ok;
		WNL_LOOKUP3resfail res_fail;
	} WNL_LOOKUP3res_u;
};
typedef struct WNL_LOOKUP3res WNL_LOOKUP3res;
#define	MAX_FLAVORS 128

struct snego_t {
	int cnt;
	int array[MAX_FLAVORS];
};
typedef struct snego_t snego_t;

enum snego_stat {
	SNEGO_SUCCESS = 0,
	SNEGO_DEF_VALID = 1,
	SNEGO_ARRAY_TOO_SMALL = 2,
	SNEGO_FAILURE = 3
};
typedef enum snego_stat snego_stat;

#define	WNL_PROGRAM	100003
#define	WNL_V2	2

#if defined(__STDC__) || defined(__cplusplus)
#define	WNLPROC_NULL	0
extern  enum clnt_stat wnlproc_null_2(void *, void *, CLIENT *);
extern  bool_t wnlproc_null_2_svc(void *, void *, struct svc_req *);
#define	WNLPROC_LOOKUP	4
extern  enum clnt_stat wnlproc_lookup_2(wnl_diropargs *, wnl_diropres *, CLIENT *);
extern  bool_t wnlproc_lookup_2_svc(wnl_diropargs *, wnl_diropres *, struct svc_req *);
extern int wnl_program_2_freeresult(SVCXPRT *, xdrproc_t, caddr_t);

#else /* K&R C */
#define	WNLPROC_NULL	0
extern  enum clnt_stat wnlproc_null_2();
extern  bool_t wnlproc_null_2_svc();
#define	WNLPROC_LOOKUP	4
extern  enum clnt_stat wnlproc_lookup_2();
extern  bool_t wnlproc_lookup_2_svc();
extern int wnl_program_2_freeresult();
#endif /* K&R C */
#define	WNL_V3	3

#if defined(__STDC__) || defined(__cplusplus)
#define	WNLPROC3_NULL	0
extern  enum clnt_stat wnlproc3_null_3(void *, void *, CLIENT *);
extern  bool_t wnlproc3_null_3_svc(void *, void *, struct svc_req *);
#define	WNLPROC3_LOOKUP	3
extern  enum clnt_stat wnlproc3_lookup_3(WNL_LOOKUP3args *, WNL_LOOKUP3res *, CLIENT *);
extern  bool_t wnlproc3_lookup_3_svc(WNL_LOOKUP3args *, WNL_LOOKUP3res *, struct svc_req *);
extern int wnl_program_3_freeresult(SVCXPRT *, xdrproc_t, caddr_t);

#else /* K&R C */
#define	WNLPROC3_NULL	0
extern  enum clnt_stat wnlproc3_null_3();
extern  bool_t wnlproc3_null_3_svc();
#define	WNLPROC3_LOOKUP	3
extern  enum clnt_stat wnlproc3_lookup_3();
extern  bool_t wnlproc3_lookup_3_svc();
extern int wnl_program_3_freeresult();
#endif /* K&R C */
#define	WNL_V4	4

#if defined(__STDC__) || defined(__cplusplus)
#define	WNLPROC4_NULL	0
extern  enum clnt_stat wnlproc4_null_4(void *, void *, CLIENT *);
extern  bool_t wnlproc4_null_4_svc(void *, void *, struct svc_req *);
extern int wnl_program_4_freeresult(SVCXPRT *, xdrproc_t, caddr_t);

#else /* K&R C */
#define	WNLPROC4_NULL	0
extern  enum clnt_stat wnlproc4_null_4();
extern  bool_t wnlproc4_null_4_svc();
extern int wnl_program_4_freeresult();
#endif /* K&R C */

/* the xdr functions */

#if defined(__STDC__) || defined(__cplusplus)
extern  bool_t xdr_wnl_stat(XDR *, wnl_stat*);
extern  bool_t xdr_wnl_ftype(XDR *, wnl_ftype*);
extern  bool_t xdr_wnl_fh(XDR *, wnl_fh*);
extern  bool_t xdr_wnl_time(XDR *, wnl_time*);
extern  bool_t xdr_wnl_fattr(XDR *, wnl_fattr*);
extern  bool_t xdr_wnl_filename(XDR *, wnl_filename*);
extern  bool_t xdr_wnl_diropargs(XDR *, wnl_diropargs*);
extern  bool_t xdr_wnl_diropokres(XDR *, wnl_diropokres*);
extern  bool_t xdr_wnl_diropres(XDR *, wnl_diropres*);
extern  bool_t xdr_wnl_uint64(XDR *, wnl_uint64*);
extern  bool_t xdr_wnl_int64(XDR *, wnl_int64*);
extern  bool_t xdr_wnl_uint32(XDR *, wnl_uint32*);
extern  bool_t xdr_wnl_filename3(XDR *, wnl_filename3*);
extern  bool_t xdr_wnl_fileid3(XDR *, wnl_fileid3*);
extern  bool_t xdr_wnl_uid3(XDR *, wnl_uid3*);
extern  bool_t xdr_wnl_gid3(XDR *, wnl_gid3*);
extern  bool_t xdr_wnl_size3(XDR *, wnl_size3*);
extern  bool_t xdr_wnl_mode3(XDR *, wnl_mode3*);
extern  bool_t xdr_wnl_stat3(XDR *, wnl_stat3*);
extern  bool_t xdr_wnl_ftype3(XDR *, wnl_ftype3*);
extern  bool_t xdr_wnl_specdata3(XDR *, wnl_specdata3*);
extern  bool_t xdr_wnl_fh3(XDR *, wnl_fh3*);
extern  bool_t xdr_wnl_time3(XDR *, wnl_time3*);
extern  bool_t xdr_wnl_fattr3(XDR *, wnl_fattr3*);
extern  bool_t xdr_wnl_post_op_attr(XDR *, wnl_post_op_attr*);
extern  bool_t xdr_wln_post_op_fh3(XDR *, wln_post_op_fh3*);
extern  bool_t xdr_wnl_diropargs3(XDR *, wnl_diropargs3*);
extern  bool_t xdr_WNL_LOOKUP3args(XDR *, WNL_LOOKUP3args*);
extern  bool_t xdr_WNL_LOOKUP3resok(XDR *, WNL_LOOKUP3resok*);
extern  bool_t xdr_WNL_LOOKUP3resfail(XDR *, WNL_LOOKUP3resfail*);
extern  bool_t xdr_WNL_LOOKUP3res(XDR *, WNL_LOOKUP3res*);
extern  bool_t xdr_snego_t(XDR *, snego_t*);
extern  bool_t xdr_snego_stat(XDR *, snego_stat*);

#else /* K&R C */
extern bool_t xdr_wnl_stat();
extern bool_t xdr_wnl_ftype();
extern bool_t xdr_wnl_fh();
extern bool_t xdr_wnl_time();
extern bool_t xdr_wnl_fattr();
extern bool_t xdr_wnl_filename();
extern bool_t xdr_wnl_diropargs();
extern bool_t xdr_wnl_diropokres();
extern bool_t xdr_wnl_diropres();
extern bool_t xdr_wnl_uint64();
extern bool_t xdr_wnl_int64();
extern bool_t xdr_wnl_uint32();
extern bool_t xdr_wnl_filename3();
extern bool_t xdr_wnl_fileid3();
extern bool_t xdr_wnl_uid3();
extern bool_t xdr_wnl_gid3();
extern bool_t xdr_wnl_size3();
extern bool_t xdr_wnl_mode3();
extern bool_t xdr_wnl_stat3();
extern bool_t xdr_wnl_ftype3();
extern bool_t xdr_wnl_specdata3();
extern bool_t xdr_wnl_fh3();
extern bool_t xdr_wnl_time3();
extern bool_t xdr_wnl_fattr3();
extern bool_t xdr_wnl_post_op_attr();
extern bool_t xdr_wln_post_op_fh3();
extern bool_t xdr_wnl_diropargs3();
extern bool_t xdr_WNL_LOOKUP3args();
extern bool_t xdr_WNL_LOOKUP3resok();
extern bool_t xdr_WNL_LOOKUP3resfail();
extern bool_t xdr_WNL_LOOKUP3res();
extern bool_t xdr_snego_t();
extern bool_t xdr_snego_stat();

#endif /* K&R C */

#ifdef __cplusplus
}
#endif

#endif /* !_AUTOFS_WEBNFS_H_RPCGEN */
/*
 * Please do not edit this file.
 * It was generated using rpcgen.
 */

#include <memory.h> /* for memset */
#include "webnfs.h"
#ifndef _KERNEL
#include <stdio.h>
#include <stdlib.h> /* getenv, exit */
#endif /* !_KERNEL */

/* Default timeout can be changed using clnt_control() */
static struct timeval TIMEOUT = { 25, 0 };

enum clnt_stat 
wnlproc_null_2(void *argp, void *clnt_res, CLIENT *clnt)
{
	return (clnt_call(clnt, WNLPROC_NULL,
		(xdrproc_t)xdr_void, (caddr_t)argp,
		(xdrproc_t)xdr_void, (caddr_t)clnt_res,
		TIMEOUT));
}

enum clnt_stat 
wnlproc_lookup_2(wnl_diropargs *argp, wnl_diropres *clnt_res, CLIENT *clnt)
{
	return (clnt_call(clnt, WNLPROC_LOOKUP,
		(xdrproc_t)xdr_wnl_diropargs, (caddr_t)argp,
		(xdrproc_t)xdr_wnl_diropres, (caddr_t)clnt_res,
		TIMEOUT));
}

enum clnt_stat 
wnlproc3_null_3(void *argp, void *clnt_res, CLIENT *clnt)
{
	return (clnt_call(clnt, WNLPROC3_NULL,
		(xdrproc_t)xdr_void, (caddr_t)argp,
		(xdrproc_t)xdr_void, (caddr_t)clnt_res,
		TIMEOUT));
}

enum clnt_stat 
wnlproc3_lookup_3(WNL_LOOKUP3args *argp, WNL_LOOKUP3res *clnt_res, CLIENT *clnt)
{
	return (clnt_call(clnt, WNLPROC3_LOOKUP,
		(xdrproc_t)xdr_WNL_LOOKUP3args, (caddr_t)argp,
		(xdrproc_t)xdr_WNL_LOOKUP3res, (caddr_t)clnt_res,
		TIMEOUT));
}

enum clnt_stat 
wnlproc4_null_4(void *argp, void *clnt_res, CLIENT *clnt)
{
	return (clnt_call(clnt, WNLPROC4_NULL,
		(xdrproc_t)xdr_void, (caddr_t)argp,
		(xdrproc_t)xdr_void, (caddr_t)clnt_res,
		TIMEOUT));
}
/*
 * Please do not edit this file.
 * It was generated using rpcgen.
 */

#include "webnfs.h"

#ifndef _KERNEL
#include <stdlib.h>
#endif /* !_KERNEL */


bool_t
xdr_wnl_stat(XDR *xdrs, wnl_stat *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_ftype(XDR *xdrs, wnl_ftype *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_fh(XDR *xdrs, wnl_fh *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_opaque(xdrs, objp->data, WNL_FHSIZE))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_time(XDR *xdrs, wnl_time *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_u_int(xdrs, &objp->seconds))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->useconds))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_fattr(XDR *xdrs, wnl_fattr *objp)
{

	rpc_inline_t *buf __unused;


	if (xdrs->x_op == XDR_ENCODE) {
		if (!xdr_wnl_ftype(xdrs, &objp->type))
			return (FALSE);
		buf = XDR_INLINE(xdrs, 10 * BYTES_PER_XDR_UNIT);
		if (buf == NULL) {
			if (!xdr_u_int(xdrs, &objp->mode))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->nlink))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->uid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->gid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->size))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->blocksize))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->rdev))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->blocks))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->fsid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->fileid))
				return (FALSE);
		} else {
#if defined(_LP64) || defined(_KERNEL)
			IXDR_PUT_U_INT32(buf, objp->mode);
			IXDR_PUT_U_INT32(buf, objp->nlink);
			IXDR_PUT_U_INT32(buf, objp->uid);
			IXDR_PUT_U_INT32(buf, objp->gid);
			IXDR_PUT_U_INT32(buf, objp->size);
			IXDR_PUT_U_INT32(buf, objp->blocksize);
			IXDR_PUT_U_INT32(buf, objp->rdev);
			IXDR_PUT_U_INT32(buf, objp->blocks);
			IXDR_PUT_U_INT32(buf, objp->fsid);
			IXDR_PUT_U_INT32(buf, objp->fileid);
#else
			IXDR_PUT_U_LONG(buf, objp->mode);
			IXDR_PUT_U_LONG(buf, objp->nlink);
			IXDR_PUT_U_LONG(buf, objp->uid);
			IXDR_PUT_U_LONG(buf, objp->gid);
			IXDR_PUT_U_LONG(buf, objp->size);
			IXDR_PUT_U_LONG(buf, objp->blocksize);
			IXDR_PUT_U_LONG(buf, objp->rdev);
			IXDR_PUT_U_LONG(buf, objp->blocks);
			IXDR_PUT_U_LONG(buf, objp->fsid);
			IXDR_PUT_U_LONG(buf, objp->fileid);
#endif
		}
		if (!xdr_wnl_time(xdrs, &objp->atime))
			return (FALSE);
		if (!xdr_wnl_time(xdrs, &objp->mtime))
			return (FALSE);
		if (!xdr_wnl_time(xdrs, &objp->ctime))
			return (FALSE);
		return (TRUE);
	} else if (xdrs->x_op == XDR_DECODE) {
		if (!xdr_wnl_ftype(xdrs, &objp->type))
			return (FALSE);
		buf = XDR_INLINE(xdrs, 10 * BYTES_PER_XDR_UNIT);
		if (buf == NULL) {
			if (!xdr_u_int(xdrs, &objp->mode))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->nlink))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->uid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->gid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->size))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->blocksize))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->rdev))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->blocks))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->fsid))
				return (FALSE);
			if (!xdr_u_int(xdrs, &objp->fileid))
				return (FALSE);
		} else {
#if defined(_LP64) || defined(_KERNEL)
			objp->mode = IXDR_GET_U_INT32(buf);
			objp->nlink = IXDR_GET_U_INT32(buf);
			objp->uid = IXDR_GET_U_INT32(buf);
			objp->gid = IXDR_GET_U_INT32(buf);
			objp->size = IXDR_GET_U_INT32(buf);
			objp->blocksize = IXDR_GET_U_INT32(buf);
			objp->rdev = IXDR_GET_U_INT32(buf);
			objp->blocks = IXDR_GET_U_INT32(buf);
			objp->fsid = IXDR_GET_U_INT32(buf);
			objp->fileid = IXDR_GET_U_INT32(buf);
#else
			objp->mode = IXDR_GET_U_LONG(buf);
			objp->nlink = IXDR_GET_U_LONG(buf);
			objp->uid = IXDR_GET_U_LONG(buf);
			objp->gid = IXDR_GET_U_LONG(buf);
			objp->size = IXDR_GET_U_LONG(buf);
			objp->blocksize = IXDR_GET_U_LONG(buf);
			objp->rdev = IXDR_GET_U_LONG(buf);
			objp->blocks = IXDR_GET_U_LONG(buf);
			objp->fsid = IXDR_GET_U_LONG(buf);
			objp->fileid = IXDR_GET_U_LONG(buf);
#endif
		}
		if (!xdr_wnl_time(xdrs, &objp->atime))
			return (FALSE);
		if (!xdr_wnl_time(xdrs, &objp->mtime))
			return (FALSE);
		if (!xdr_wnl_time(xdrs, &objp->ctime))
			return (FALSE);
		return (TRUE);
	}

	if (!xdr_wnl_ftype(xdrs, &objp->type))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->mode))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->nlink))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->uid))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->gid))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->size))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->blocksize))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->rdev))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->blocks))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->fsid))
		return (FALSE);
	if (!xdr_u_int(xdrs, &objp->fileid))
		return (FALSE);
	if (!xdr_wnl_time(xdrs, &objp->atime))
		return (FALSE);
	if (!xdr_wnl_time(xdrs, &objp->mtime))
		return (FALSE);
	if (!xdr_wnl_time(xdrs, &objp->ctime))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_filename(XDR *xdrs, wnl_filename *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_string(xdrs, objp, WNL_MAXNAMLEN))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_diropargs(XDR *xdrs, wnl_diropargs *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_fh(xdrs, &objp->dir))
		return (FALSE);
	if (!xdr_wnl_filename(xdrs, &objp->name))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_diropokres(XDR *xdrs, wnl_diropokres *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_fh(xdrs, &objp->file))
		return (FALSE);
	if (!xdr_wnl_fattr(xdrs, &objp->attributes))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_diropres(XDR *xdrs, wnl_diropres *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_stat(xdrs, &objp->status))
		return (FALSE);
	switch (objp->status) {
	case WNL_OK:
		if (!xdr_wnl_diropokres(xdrs, &objp->wnl_diropres_u.wnl_diropres))
			return (FALSE);
		break;
	default:
		break;
	}
	return (TRUE);
}

bool_t
xdr_wnl_uint64(XDR *xdrs, wnl_uint64 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_u_longlong_t(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_int64(XDR *xdrs, wnl_int64 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_longlong_t(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_uint32(XDR *xdrs, wnl_uint32 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_u_int(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_filename3(XDR *xdrs, wnl_filename3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_string(xdrs, objp, ~0))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_fileid3(XDR *xdrs, wnl_fileid3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint64(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_uid3(XDR *xdrs, wnl_uid3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint32(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_gid3(XDR *xdrs, wnl_gid3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint32(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_size3(XDR *xdrs, wnl_size3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint64(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_mode3(XDR *xdrs, wnl_mode3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint32(xdrs, objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_stat3(XDR *xdrs, wnl_stat3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_ftype3(XDR *xdrs, wnl_ftype3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_specdata3(XDR *xdrs, wnl_specdata3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint32(xdrs, &objp->specdata1))
		return (FALSE);
	if (!xdr_wnl_uint32(xdrs, &objp->specdata2))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_fh3(XDR *xdrs, wnl_fh3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_bytes(xdrs, (char **)&objp->data.data_val, (u_int *) &objp->data.data_len, WNL3_FHSIZE))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_time3(XDR *xdrs, wnl_time3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_uint32(xdrs, &objp->seconds))
		return (FALSE);
	if (!xdr_wnl_uint32(xdrs, &objp->nseconds))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_fattr3(XDR *xdrs, wnl_fattr3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_ftype3(xdrs, &objp->type))
		return (FALSE);
	if (!xdr_wnl_mode3(xdrs, &objp->mode))
		return (FALSE);
	if (!xdr_wnl_uint32(xdrs, &objp->nlink))
		return (FALSE);
	if (!xdr_wnl_uid3(xdrs, &objp->uid))
		return (FALSE);
	if (!xdr_wnl_gid3(xdrs, &objp->gid))
		return (FALSE);
	if (!xdr_wnl_size3(xdrs, &objp->size))
		return (FALSE);
	if (!xdr_wnl_size3(xdrs, &objp->used))
		return (FALSE);
	if (!xdr_wnl_specdata3(xdrs, &objp->rdev))
		return (FALSE);
	if (!xdr_wnl_uint64(xdrs, &objp->fsid))
		return (FALSE);
	if (!xdr_wnl_fileid3(xdrs, &objp->fileid))
		return (FALSE);
	if (!xdr_wnl_time3(xdrs, &objp->atime))
		return (FALSE);
	if (!xdr_wnl_time3(xdrs, &objp->mtime))
		return (FALSE);
	if (!xdr_wnl_time3(xdrs, &objp->ctime))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_wnl_post_op_attr(XDR *xdrs, wnl_post_op_attr *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_bool(xdrs, &objp->attributes_follow))
		return (FALSE);
	switch (objp->attributes_follow) {
	case TRUE:
		if (!xdr_wnl_fattr3(xdrs, &objp->wnl_post_op_attr_u.attributes))
			return (FALSE);
		break;
	case FALSE:
		break;
	default:
		return (FALSE);
	}
	return (TRUE);
}

bool_t
xdr_wln_post_op_fh3(XDR *xdrs, wln_post_op_fh3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_bool(xdrs, &objp->handle_follows))
		return (FALSE);
	switch (objp->handle_follows) {
	case TRUE:
		if (!xdr_wnl_fh3(xdrs, &objp->wln_post_op_fh3_u.handle))
			return (FALSE);
		break;
	case FALSE:
		break;
	default:
		return (FALSE);
	}
	return (TRUE);
}

bool_t
xdr_wnl_diropargs3(XDR *xdrs, wnl_diropargs3 *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_fh3(xdrs, &objp->dir))
		return (FALSE);
	if (!xdr_wnl_filename3(xdrs, &objp->name))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_WNL_LOOKUP3args(XDR *xdrs, WNL_LOOKUP3args *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_diropargs3(xdrs, &objp->what))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_WNL_LOOKUP3resok(XDR *xdrs, WNL_LOOKUP3resok *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_fh3(xdrs, &objp->object))
		return (FALSE);
	if (!xdr_wnl_post_op_attr(xdrs, &objp->obj_attributes))
		return (FALSE);
	if (!xdr_wnl_post_op_attr(xdrs, &objp->dir_attributes))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_WNL_LOOKUP3resfail(XDR *xdrs, WNL_LOOKUP3resfail *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_post_op_attr(xdrs, &objp->dir_attributes))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_WNL_LOOKUP3res(XDR *xdrs, WNL_LOOKUP3res *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_wnl_stat3(xdrs, &objp->status))
		return (FALSE);
	switch (objp->status) {
	case WNL3_OK:
		if (!xdr_WNL_LOOKUP3resok(xdrs, &objp->WNL_LOOKUP3res_u.res_ok))
			return (FALSE);
		break;
	default:
		if (!xdr_WNL_LOOKUP3resfail(xdrs, &objp->WNL_LOOKUP3res_u.res_fail))
			return (FALSE);
		break;
	}
	return (TRUE);
}

bool_t
xdr_snego_t(XDR *xdrs, snego_t *objp)
{

	rpc_inline_t *buf __unused;

	int i;

	if (xdrs->x_op == XDR_ENCODE) {
		buf = XDR_INLINE(xdrs, (1 + (MAX_FLAVORS)) * BYTES_PER_XDR_UNIT);
		if (buf == NULL) {
			if (!xdr_int(xdrs, &objp->cnt))
				return (FALSE);
			if (!xdr_vector(xdrs, (char *)objp->array, MAX_FLAVORS,
				sizeof (int), (xdrproc_t)xdr_int))
				return (FALSE);
		} else {
#if defined(_LP64) || defined(_KERNEL)
			IXDR_PUT_INT32(buf, objp->cnt);
			{
				int *genp;

				for (i = 0, genp = objp->array;
					i < MAX_FLAVORS; i++) {
					IXDR_PUT_INT32(buf, *genp++);
				}
			}
#else
			IXDR_PUT_LONG(buf, objp->cnt);
			{
				int *genp;

				for (i = 0, genp = objp->array;
					i < MAX_FLAVORS; i++) {
					IXDR_PUT_LONG(buf, *genp++);
				}
			}
#endif
		}
		return (TRUE);
	} else if (xdrs->x_op == XDR_DECODE) {
		buf = XDR_INLINE(xdrs, (1 + (MAX_FLAVORS)) * BYTES_PER_XDR_UNIT);
		if (buf == NULL) {
			if (!xdr_int(xdrs, &objp->cnt))
				return (FALSE);
			if (!xdr_vector(xdrs, (char *)objp->array, MAX_FLAVORS,
				sizeof (int), (xdrproc_t)xdr_int))
				return (FALSE);
		} else {
#if defined(_LP64) || defined(_KERNEL)
			objp->cnt = IXDR_GET_INT32(buf);
			{
				int *genp;

				for (i = 0, genp = objp->array;
					i < MAX_FLAVORS; i++) {
					*genp++ = IXDR_GET_INT32(buf);
				}
			}
#else
			objp->cnt = IXDR_GET_LONG(buf);
			{
				int *genp;

				for (i = 0, genp = objp->array;
					i < MAX_FLAVORS; i++) {
					*genp++ = IXDR_GET_LONG(buf);
				}
			}
#endif
		}
		return (TRUE);
	}

	if (!xdr_int(xdrs, &objp->cnt))
		return (FALSE);
	if (!xdr_vector(xdrs, (char *)objp->array, MAX_FLAVORS,
		sizeof (int), (xdrproc_t)xdr_int))
		return (FALSE);
	return (TRUE);
}

bool_t
xdr_snego_stat(XDR *xdrs, snego_stat *objp)
{

	rpc_inline_t *buf __unused;

	if (!xdr_enum(xdrs, (enum_t *)objp))
		return (FALSE);
	return (TRUE);
}