summaryrefslogblamecommitdiffstats
path: root/private/lsa/server/dbobject.c
blob: 0a8aa7f7bc707cb1e85db86f5a3c228990e381cb (plain) (tree)
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




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                 
/*++

Copyright (c) 1991  Microsoft Corporation

Module Name:

    dbobject.c

Abstract:

    Local Security Authority - LSA Database Public Object Management Routines

    This module contains the public routines that perform LSA Database object
    manipulation.  These routines are exported to the rest of the
    LSA, function prototypes of these routines will be found in db.h.  These
    exported routines present an implementation-independent hierarchic
    object-based view of the LSA Database and are used exclusively by the
    LSA API.  See the Additional Notes further below for a description of
    the LSA Database model.

    Routines in this module that are private to the object management
    function have function prototypes in dbp.h.

Author:

    Scott Birrell       (ScottBi)       August 26, 1991

Environment:

    User Mode

Revision History:

Notes on the LSA Database Architecture

OBJECT STRUCTURE

    The LSA Database is an hierarchic structure containing "objects" of
    several "types".  Objects have either a "name" or a Sid depending only
    on object type, and may have data stored with them under named
    "attributes".  The database hierarchy contains a single root object
    called the Lsa Database object and having name "Policy".  This object
    represents the entire LSA Database.  Currently, the Lsa Database has a
    simple hierarchy consisting of only two levels.

                           Policy

     Account Objects,  Trusted Domain Objects, Secret Objects

    The Policy object is called a "Container Object" for the other
    object types.  The attributes of the Policy object house information
    that applies generally to the whole database.  The single Policy object
    has name "Policy".

    Account objects represent those user accounts which are treated specially
    on the local system, but not necessarily so on other systems.  Such
    accounts may have additional privileges, or system quotas for example.
    Account objects are referenced by Sid.

    TrustedDomain objects describe domains which the system has a trust
    relationship with.  These objects are referenced by Sid.

    Secret Objects are named entities containing information that is protected
    in some way.  Secret objects are referenced by name.

OBJECT ACCESS AND DATABASE SECURITY

    Each object in the LSA Database is protected by a Security Descriptor which
    contains a Discretionary Access Control List (DACL) defining which groups
    can access the object and in which ways.  Before an object can be
    accessed, it must first be "opened" with the desired accesses requested
    that are needed to perform the desired operations on the object.  Opening
    an object returns a "handle" to the object.  This handle may then be
    specified on Lsa services that access the object.  After use, the handle
    to the object should then be "closed".  Closing the handle renders it
    invalid.

CONCURRENCY OF ACCESS

    More than one handle may be open to an object concurrently, possibly with
    different accesses granted.

PERMANENCY OF OBJECTS

    All LSA Database objects are backed by non-volatile storage media, that is,
    they remain in existence until deleted via the LsaDelete() service.
    The Policy object cannot be deleted and the single object of this type cannot
    be created via the public LSA service interface.

    Objects will not be deleted while there are open handles to them.
    When access to an object is no longer required, the handle should be
    "closed".

DATABASE DESIGN

    The LSA Database is of an hierarchic design permitting future extension.
    Currently the database has the following simple hierarchy:

                       Policy Object  (name = Policy)

       Account Objects    TrustedDomain Objects   Secret Objects

    The single object of type Policy is at the topmost level and serves as
    a parent or "container" object  for objects of the other three types.
    Since named objects of different types may potentially reside in the
    same container object in the future, an object is referenced uniquely
    only if the object name and type together with the identity of its
    container object (currently always the Policy object) are known.
    To implement this kind of reference easily, objects of the same type
    are held within a "classifying directory" which has a name derived
    from the object's type as follows:

    Object Type      Containing Directory Name

    Policy           Not required
    Account          Accounts
    TrustedDomain    Domains
    Secret           Secrets

IMPLEMENTATION NOTES

    The LSA Database is currently implemented as a subtree of the Configuration
    Registry.  This subtree has the following form

       \Policy\Accounts\<account_object_Rid>\<account_object_attribute_name>
              \Domains\<trusted_domain_Rid>\<trus_domain_object_attribute_name>
              \Secrets\<secret_name>\<secret_object_attribute_name>
              \<policy_object_attribute_name>

    where each item between \..\ is the name of a Registry Key and
    "Rid" is a character name made out of the Relative Id (lowest
    subauthority extracted from the object's Sid).  Named object attributes
    can have binary data "values".

--*/

#include "lsasrvp.h"
#include "dbp.h"
#include "adtp.h"


NTSTATUS
LsapDbOpenObject(
    IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
    IN ACCESS_MASK DesiredAccess,
    IN ULONG Options,
    OUT PLSAPR_HANDLE ObjectHandle
    )

/*++

Routine Description:

    This function opens an existing object in the LSA Database.  An error
    is returned if the object does not already exist.  The LSA Database must
    be already locked when calling this function and any container handle
    must have been validated as having the necessary access for creation
    of an object of the given type.

Arguments:

    ObjectInformation - Pointer to information describing this object.  The
        following information items must be specified:

        o Object Type Id
        o Object Logical Name (as ObjectAttributes->ObjectName, a pointer to
             a Unicode string)
        o Container object handle (for any object except the root Policy object).
        o Object Sid (if any)

        All other fields in ObjectAttributes portion of ObjectInformation
        such as SecurityDescriptor are ignored.

    DesiredAccess - Specifies the Desired accesses to the Lsa object

    Options - Specifies optional additional actions to be taken:

        LSAP_DB_TRUSTED - A trusted handle is wanted regardless of the trust
            status of any container handle provided in ObjectInformation.

        LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK - Omit the check for a BDC.
            This flag is set usually because an object (e.g. a local secret)
            is local to a specific computer and is not replicated.  Objects
            of this type may be created, updated or deleted by non-trusted
            clients on BDC's, so no BDC check is required.

        LSAP_DB_OMIT_REPLICATOR_NOTIFICATION - Omit replicator notification
            on object updates.  This flag will be stored in the handle
            created for the object and retrieved when committing an update
            to the object via LsapDbDereferenceObject().

    ObjectHandle - Receives the handle to the object.

Return Value:

    NTSTATUS - Standard NT status code

        STATUS_INVALID_PARAMETER - One or more parameters invalid.
            - Invalid syntax of parameters, e.g Sid
            - Sid not specified when required for object type
            - Name specified when not allowed.

        STATUS_INSUFFICIENT_RESOURCES - Insufficient system resources
            to complete the request (e.g. memory for reading object's
            Security Descriptor).

        STATUS_OBJECT_NOT_FOUND - Object does not exist.
--*/

{
    NTSTATUS Status;
    ULONG SecurityDescriptorLength;
    LSAP_DB_HANDLE NewObjectHandle = NULL;
    PSECURITY_DESCRIPTOR ContainerSecurityDescriptor = NULL;
    PSECURITY_DESCRIPTOR SecurityDescriptor = NULL;
    OBJECT_ATTRIBUTES OpenKeyObjectAttributes;
    ULONG States = Options & LSAP_DB_STATE_MASK;
    ULONG ResetStates = 0;
    LSAPR_HANDLE OutputHandle = NULL;
    LSAP_DB_HANDLE InternalOutputHandle = NULL;
    LSAP_DB_HANDLE ContainerHandle = NULL;

    PSECURITY_DESCRIPTOR SavedSecurityDescriptor =
        ObjectInformation->ObjectAttributes.SecurityDescriptor;

    //
    // Validate the Object Information parameter.
    //

    Status = LsapDbVerifyInformationObject( ObjectInformation );

    if (!NT_SUCCESS(Status)) {

        goto OpenObjectError;
    }

    //
    // Verify that the Lsa database is now locked.
    //

    ASSERT (LsapDbIsLocked());

    //
    // Allocate and initialize a handle for the object.  The object's
    // Registry Key, Logical and Physical Names will be derived from
    // the given ObjectInformation and pointers to them will be stored in
    // the handle.
    //

    OutputHandle = LsapDbCreateHandle( ObjectInformation, Options );
    InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;

    Status = STATUS_INSUFFICIENT_RESOURCES;

    if (OutputHandle == NULL) {

        goto OpenObjectError;
    }

    //
    // Setup Object Attributes structure for opening the Registry key of
    // the object.  Specify as path the Physical Name of the object, this
    // being the path of the object's Registry Key relative to the
    // LSA Database root key.
    //

    InitializeObjectAttributes(
        &OpenKeyObjectAttributes,
        &InternalOutputHandle->PhysicalNameU,
        OBJ_CASE_INSENSITIVE,
        LsapDbState.DbRootRegKeyHandle,
        NULL
        );

    //
    // Now attempt to open the object's Registry Key.  Store the Registry
    // Key handle in the object's handle.
    //

    Status = RtlpNtOpenKey(
                 (PHANDLE) &InternalOutputHandle->KeyHandle,
                 KEY_READ | KEY_WRITE,
                 &OpenKeyObjectAttributes,
                 0L
                 );

    if (!NT_SUCCESS(Status)) {

        InternalOutputHandle->KeyHandle = NULL; // For cleanup purposes
        goto OpenObjectError;
    }

    //
    // The object exists.  Unless access checking is to be bypassed, we
    // need to access the object's Security Descriptor and perform an
    // access check.  The Security Descriptor is stored as the object's
    // SecDesc attribute, so we need to read this.  First, we must query the
    // size of the Security Descriptor to determine how much memory to
    // allocate for reading it.  The query is done by issuing a read of the
    // object's SecDesc subkey with a NULL output buffer and zero size
    // specified.
    //

    if (!(InternalOutputHandle->Trusted)) {

        SecurityDescriptorLength = 0;

        Status = LsapDbReadAttributeObject(
                     OutputHandle,
                     &LsapDbNames[SecDesc],
                     NULL,
                     &SecurityDescriptorLength
                     );

        if (!NT_SUCCESS(Status)) {

            goto OpenObjectError;
        }

        //
        // Allocate a buffer from the Lsa Heap for the existing object's SD.
        //

        SecurityDescriptor = LsapAllocateLsaHeap( SecurityDescriptorLength );

        Status = STATUS_INSUFFICIENT_RESOURCES;

        if (SecurityDescriptor == NULL) {

            goto OpenObjectError;
        }

        //
        // Read the SD.  It is the value of the SecDesc subkey.
        //

        Status = LsapDbReadAttributeObject(
                     OutputHandle,
                     &LsapDbNames[SecDesc],
                     SecurityDescriptor,
                     &SecurityDescriptorLength
                     );

        if (!NT_SUCCESS(Status)) {

            goto OpenObjectError;
        }

        //
        // Reference the SD read from the LSA Database from the object
        // information.
        //

        ObjectInformation->ObjectAttributes.SecurityDescriptor =
            SecurityDescriptor;

        //
        // Request the desired accesses and store them in the object's handle.
        // granted.
        //

        Status = LsapDbRequestAccessObject(
                     OutputHandle,
                     ObjectInformation,
                     DesiredAccess,
                     Options
                     );

        //
        // If the accesses are granted, the open has completed successfully.
        // Store the container object handle in the object's handle and
        // return the handle to the caller..
        //

        if (!NT_SUCCESS(Status)) {

            goto OpenObjectError;
        }
    }

    *ObjectHandle = OutputHandle;

OpenObjectFinish:

    //
    // Restore the saved Security Descriptor reference in the object
    // information.
    //

    ObjectInformation->ObjectAttributes.SecurityDescriptor =
        SavedSecurityDescriptor;

    //
    // If necessary, free the memory allocated for the Security Descriptor
    //

    if (SecurityDescriptor != NULL) {

        LsapFreeLsaHeap( SecurityDescriptor );
    }

    return(Status);

OpenObjectError:

    //
    // If necessary, free the handle we created.
    //

    if (OutputHandle != NULL) {

        LsapDbFreeHandle(OutputHandle);
    }

    goto OpenObjectFinish;
}


NTSTATUS
LsapDbCreateObject(
    IN OUT PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
    IN ACCESS_MASK DesiredAccess,
    IN ULONG CreateDisposition,
    IN ULONG Options,
    IN OPTIONAL PLSAP_DB_ATTRIBUTE Attributes,
    IN ULONG TypeSpecificAttributeCount,
    OUT PLSAPR_HANDLE ObjectHandle
    )

/*++

Routine Description:

    This function creates an object in the LSA Database, together with
    the set of attributes, such as Security Descriptor that are common
    to all object types.  The object will be left in the open state
    and the caller may use the returned handle to create the type-
    specific attributes.

    NOTE:  For an object creation, it is the responsibility of the calling
    LSA object creation routine to verify that the necessary access to the
    container object is granted.  That access is dependent on the type of
    LSA object being created.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called.  No Lsa Database transaction may be pending when
              this function is called.

Arguments:

    ObjectInformation - Pointer to information describing this object.  The
        following information items must be specified:

        o Object Type Id
        o Object Logical Name (as ObjectAttributes->ObjectName, a pointer to
             a Unicode string)
        o Container object handle (for any object except the root Policy object).
        o Object Sid (if any)

        All other fields in ObjectAttributes portion of ObjectInformation
        such as SecurityDescriptor are ignored.

    DesiredAccess - Specifies the Desired accesses to the object.

    CreateDisposition - Specifies the Creation Disposition.  This is the
        action to take depending on whether the object already exists.

        LSA_OBJECT_CREATE - Create the object if it does not exist.  If
            the object already exists, return an error.

        LSA_OBJECT_OPEN_IF - Create the object if it does not exist.  If
            the object already exists, just open it.

    Options - Specifies optional information and actions to be taken

        LSAP_DB_ACQUIRE_LOCK - Acquire the LSA Database lock

        LSAP_DB_TRUSTED - A Trusted Handle is wanted regardless of the
            Trust status of any container handle provided in
            ObjectInformation.

        LSAP_DB_OMIT_REPLICATOR_NOTIFICATION - Omit notification of the
            object creation to Replicator.

        Note, this routine performs a complete database transaction so
        there is no option to start one.

    Attributes - Optional pointer to an array of attribute
        names and values.  These are specific to the type of object.

    TypeSpecificAttributeCount - Number of elements in the array
        referenced by the Attributes parameter.

    ObjectHandle - Receives the handle to the object.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INVALID_PARAMETER - The given Sid is invalid.

        STATUS_OBJECT_NAME_EXISTS - An object having the given Sid
            already exists and has been opened because LSA_OBJECT_OPEN_IF
            disposition has been specified.  This is a warning only.

        STATUS_OBJECT_NAME_COLLISION - An object having the given Sid
            already exists but has not been opened because LSA_OBJECT_CREATE
            disposition has been specified.  This is an error.
--*/

{
    NTSTATUS Status, SecondaryStatus, IgnoreStatus;
    OBJECT_ATTRIBUTES OpenKeyObjectAttributes;
    ULONG CloseOptions;
    BOOLEAN AcquiredLock = FALSE;
    BOOLEAN CreatedObject = FALSE;
    BOOLEAN OpenedObject = FALSE;
    BOOLEAN OpenedTransaction = FALSE;
    LSAPR_HANDLE OutputHandle = NULL;
    LSAP_DB_HANDLE InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;
    LSAP_DB_HANDLE ContainerHandle = NULL;
    LSAP_DB_OBJECT_TYPE_ID ObjectTypeId = ObjectInformation->ObjectTypeId;

    //
    // Verify the creation disposition.
    //

    if ((CreateDisposition != LSAP_DB_OBJECT_CREATE) &&
        (CreateDisposition != LSAP_DB_OBJECT_OPEN_IF)) {

        Status = STATUS_INVALID_PARAMETER;
        goto CreateObjectError;
    }

    //
    // Optionally lock the Lsa Database
    //

    if (Options & LSAP_DB_ACQUIRE_LOCK) {

        Status = LsapDbAcquireLock();

        if (!NT_SUCCESS(Status)) {

            goto CreateObjectError;
        }
    }

    AcquiredLock = TRUE;

    //
    // Try to open the object.  It is permissible for the object to
    // exist already if LSA_OBJECT_OPEN_IF disposition was specified.
    //

    Status = LsapDbOpenObject(
                 ObjectInformation,
                 DesiredAccess,
                 Options,
                 &OutputHandle
                 );

    InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;

    if (NT_SUCCESS(Status)) {

        //
        // The object was successfully opened.  If LSA_OBJECT_OPEN_IF
        // disposition was specified, we're done, otherwise, we
        // return a collision error.
        //

        OpenedObject = TRUE;

        Status = STATUS_OBJECT_NAME_EXISTS;

        if (CreateDisposition == LSAP_DB_OBJECT_OPEN_IF) {

            goto CreateObjectFinish;
        }

        Status = STATUS_OBJECT_NAME_COLLISION;

        if (CreateDisposition == LSAP_DB_OBJECT_CREATE) {

            goto CreateObjectError;
        }

        Status = STATUS_SUCCESS;
    }

    //
    // The object was not successfully opened.  If this is for any
    // reason other than that the object was not found, return an error.
    //

    if (Status != STATUS_OBJECT_NAME_NOT_FOUND) {

        goto CreateObjectError;
    }

    //
    // The object was not found.  Prepare to create it.  First, we need to
    // check that any maximum limit on the number of objects of this type
    // imposed will not be exceeded.
    //

    Status = LsapDbCheckCountObject(ObjectTypeId);

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    //
    // Next we need to create a handle for the new object.
    //

    OutputHandle = LsapDbCreateHandle( ObjectInformation, Options );
    InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;

    Status = STATUS_INSUFFICIENT_RESOURCES;

    if (OutputHandle == NULL) {

        goto CreateObjectError;
    }

    //
    // Verify that the requested accesses can be given to the handle that
    // has been opened and grant them if so.
    //

    Status = LsapDbRequestAccessNewObject(
                 OutputHandle,
                 ObjectInformation,
                 DesiredAccess,
                 Options
                 );

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    //
    // Open a Registry transaction for creation of the object.
    //

    Status = LsapDbOpenTransaction();

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    OpenedTransaction = TRUE;

    //
    // Add a registry transaction to create the Registry key for the new
    // Database object.
    //

    Status = RtlAddActionToRXact(
                 LsapDbState.RXactContext,
                 RtlRXactOperationSetValue,
                 &InternalOutputHandle->PhysicalNameU,
                 ObjectTypeId,
                 NULL,        // No Key Value needed
                 0L
                 );

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    //
    // Create the Security Descriptor for the new object.  This will be
    // stored in Self-Relative form as the value of the SecDesc attribute
    // of the new object.
    //

    Status = LsapDbCreateSDAttributeObject(
                 OutputHandle,
                 ObjectInformation
                 );

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    //
    // The self-relative SD returned is not needed here or by callers of
    // this routine.
    //

    if (ObjectInformation->ObjectAttributes.SecurityDescriptor != NULL) {

        RtlFreeHeap(
            RtlProcessHeap(),
            0,
            ObjectInformation->ObjectAttributes.SecurityDescriptor
            );

        ObjectInformation->ObjectAttributes.SecurityDescriptor = NULL;
    }

    //
    // Write the type-specific attributes (if any) for the object).
    //

    if (TypeSpecificAttributeCount != 0) {

        Status = LsapDbWriteAttributesObject(
                     OutputHandle,
                     Attributes,
                     TypeSpecificAttributeCount
                     );

        if (!NT_SUCCESS(Status)) {

            goto CreateObjectError;
        }
    }

    //
    // Apply the Registry Transaction to create the object.  Note
    // that we have to create the object before we can open its
    // registry key for placement within the handle.
    //

    Status = LsapDbResetStates(
                 OutputHandle,
                 Options | LSAP_DB_FINISH_TRANSACTION,
                 SecurityDbNew,
                 Status
                 );

    OpenedTransaction = FALSE;

    if (!NT_SUCCESS(Status)) {

        goto CreateObjectError;
    }

    //
    // Increment the count of objects created.  It should not have
    // changed since we're still holding the LSA Database lock.
    // NOTE: Count is decremented on error inside LsapDbDeleteObject()
    //

    LsapDbIncrementCountObject(ObjectInformation->ObjectTypeId);

    CreatedObject = TRUE;

    //
    // The object has now been created.  We need to obtain its Registry
    // Key handle so that we can save it in the Object Handle.
    // Setup Object Attributes structure for opening the Registry key of
    // the object.  Specify as path the Physical Name of the object, this
    // being the path of the object's Registry Key relative to the
    // LSA Database root key.
    //

    InitializeObjectAttributes(
        &OpenKeyObjectAttributes,
        &InternalOutputHandle->PhysicalNameU,
        OBJ_CASE_INSENSITIVE,
        LsapDbState.DbRootRegKeyHandle,
        NULL
        );

    //
    // Now attempt to open the object's Registry Key.  Store the Registry
    // Key handle in the object's handle.
    //

    Status = RtlpNtOpenKey(
                 (PHANDLE) &InternalOutputHandle->KeyHandle,
                 KEY_READ | KEY_WRITE,
                 &OpenKeyObjectAttributes,
                 0L
                 );

    if (!NT_SUCCESS(Status)) {

        InternalOutputHandle->KeyHandle = NULL;
        goto CreateObjectError;
    }

    //
    // Add the new object to the in-memory cache (if any).  This is done
    // after all other actions, so that no removal from the cache is required
    // on the error paths.  If the object cannot be added to the cache, the
    // cache routine automatically disables the cache.
    //

    if (LsapDbIsCacheSupported( ObjectTypeId)) {

        if (LsapDbIsCacheValid( ObjectTypeId)) {

            switch (ObjectTypeId) {

            case AccountObject:

                IgnoreStatus = LsapDbCreateAccount(
                                   InternalOutputHandle->Sid,
                                   NULL
                                   );
                break;

            default:

                break;
            }
        }
    }

CreateObjectFinish:

    //
    // Return NULL or a handle to the newly created and opened object.
    //

    *ObjectHandle = OutputHandle;
    return(Status);

CreateObjectError:

    //
    // Cleanup after error.  Various variables are set non-null if
    // there is cleanup work to do.
    //

    //
    // If necessary, abort the Registry Transaction to create the object
    //

    if (OpenedTransaction) {

        Status = LsapDbResetStates(
                     OutputHandle,
                     LSAP_DB_FINISH_TRANSACTION,
                     (SECURITY_DB_DELTA_TYPE) 0,
                     Status
                     );
    }

    //
    // If we opened the object, close it.
    //

    if (OpenedObject) {

        CloseOptions = 0;
        SecondaryStatus = LsapDbCloseObject( &OutputHandle, CloseOptions );

        if (!NT_SUCCESS(SecondaryStatus)) {

            LsapLogError(
                "LsapDbCreateObject: LsapDbCloseObject failed 0x%lx\n",
                SecondaryStatus
                );
        }

        OutputHandle = NULL;
        InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;

    } else if (CreatedObject) {

        //
        // If we created the object, convert its handle into a trusted
        // handle and delete it.
        //

        InternalOutputHandle->Trusted = TRUE;

        SecondaryStatus = LsarDelete( OutputHandle );

        if (!NT_SUCCESS(SecondaryStatus)) {

            LsapLogError(
                "LsapDbCreateObject: LsarDeleteObject failed 0x%lx\n",
                SecondaryStatus
                );
        }

    } else if (OutputHandle != NULL) {

        //
        // If we just created the handle, free it.
        //

        LsapDbFreeHandle( OutputHandle );

        OutputHandle = NULL;
        InternalOutputHandle = (LSAP_DB_HANDLE) OutputHandle;
    }

    goto CreateObjectFinish;

    DBG_UNREFERENCED_PARAMETER( CloseOptions );
}


NTSTATUS
LsapDbRequestAccessObject(
    IN OUT LSAPR_HANDLE ObjectHandle,
    IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
    IN ACCESS_MASK DesiredAccess,
    IN ULONG Options
    )

/*++

Routine Description:

    This function performs an access check for an LSA Database object.  While
    impersonating an RPC client, the specified Desired Accesses are reconciled
    with the Discretionary Access Control List (DACL) in the object's
    Security Descriptor.  Note that the object's Security Descriptor is
    passed explicitly so that this routine can be called for new objects
    for which a SD has been constructed but not yet written to the
    Registry.

Arguments:

    ObjectHandle - Handle to object.  The handle will receive the
        granted accesses if the call is successful.

    ObjectInformation - Pointer to object's information.  As a minimum, the
        object's Security Descriptor must be set up.

    DesiredAccess - Specifies a mask of the access types desired to the
        object.

    Options - Specifies optional actions to be taken

        LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK - Omit the check for a BDC for
            a create/update/delete operation on a local (non-replicated)
            object such as a local secret.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_ACCESS_DENIED - Not all of the Desired Accessed can be
            granted to the caller.

        STATUS_BACKUP_CONTROLLER - A create, update or delete operation
            is not allowed for a non-trusted client for this object on a BDC,
            because the object is global to all DC's for a domain and is replicated.

        Errors from RPC client impersonation
--*/

{
    NTSTATUS Status, RevertStatus, AccessStatus;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;
    LSAP_DB_OBJECT_TYPE_ID ObjectTypeId = InternalHandle->ObjectTypeId;
    BOOLEAN WriteOperation = FALSE;
    ULONG EffectiveOptions = Options | InternalHandle->Options;

    //
    // If the system is a Backup Domain Controller, disallow update
    // operations for non-trusted callers except in special cases such
    // as local non-replicated objects.  In these special cases, the
    // flag LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK will be already set
    // in the handle Options.
    //

    WriteOperation = RtlAreAnyAccessesGranted(
                         LsapDbState.DbObjectTypes[InternalHandle->ObjectTypeId].WriteOperations,
                         DesiredAccess
                         );

    if ((LsapDbState.PolicyLsaServerRoleInfo.LsaServerRole == PolicyServerRoleBackup)  &&
         (!InternalHandle->Trusted) &&
         WriteOperation &&
         (!(EffectiveOptions & LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK))) {

        Status = STATUS_BACKUP_CONTROLLER;
        return Status;
    }

    //
    // Common path for Object Open and Creation.  We need to reconcile
    // the desired accesses to the object with the Discretionary Access
    // Control List contained in the Security Descriptor.  Note that this
    // needs to be done even for newly created objects, since they are
    // being opened as well as created.

    //
    // Impersonate the client thread prior to doing an access check.
    //

    Status = I_RpcMapWin32Status(RpcImpersonateClient(0));

    if (!NT_SUCCESS(Status)) {

        return Status;
    }

    //
    // Map any Generic Access Types to Specific Access Types
    //

    RtlMapGenericMask(
        &DesiredAccess,
        &(LsapDbState.DbObjectTypes[ObjectTypeId].GenericMapping)
        );

    //
    // Reconcile the desired access with the discretionary ACL
    // of the Resultant Descriptor.  Note that this operation is performed
    // even if we are just creating the object since the object is to
    // be opened.
    //

    Status = NtAccessCheckAndAuditAlarm(
                 &LsapState.SubsystemName,
                 ObjectHandle,
                 &LsapDbObjectTypeNames[ObjectTypeId],
                 (PUNICODE_STRING) ObjectInformation->ObjectAttributes.ObjectName,
                 ObjectInformation->ObjectAttributes.SecurityDescriptor,
                 DesiredAccess,
                 &(LsapDbState.DbObjectTypes[ObjectTypeId].GenericMapping),
                 FALSE,
                 (PACCESS_MASK) &(InternalHandle->GrantedAccess),
                 (PNTSTATUS) &AccessStatus,
                 (PBOOLEAN) &(InternalHandle->GenerateOnClose)
                 );

    //
    // Before checking the Status, stop impersonating the client and become
    // our former self.
    //

    RevertStatus = I_RpcMapWin32Status(RpcRevertToSelf());

    if (!NT_SUCCESS(RevertStatus)) {

        LsapLogError(
            "LsapDbRequestAccessObject: RpcRevertToSelf failed 0x%lx\n",
            Status
            );
    }

    //
    // If the primary status code is a success status code, return the
    // secondary status code.  If this is alsoa success code, return the
    // revert to self status.
    //

    if (NT_SUCCESS(Status)) {

        Status = AccessStatus;

        if (NT_SUCCESS(Status)) {

            Status = RevertStatus;
        }
    }

    return Status;
}

NTSTATUS
LsapDbRequestAccessNewObject(
    IN OUT LSAPR_HANDLE ObjectHandle,
    IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
    IN ACCESS_MASK DesiredAccess,
    IN ULONG Options
    )

/*++

Routine Description:

    This function verifies that a desired set of accesses can be granted
    to the handle that is opened when a new object is created.

    It is important to note that the rules for granting accesses to the
    handle that is open upon object creation are different from the rules
    for granting accesses upon the opening of an existing object.  For a new
    object, the associated handle will be granted any subset of GENERIC_ALL
    access desired and, if the creator has SE_SECURITY_PRIVILEGE, the handle
    will be granted ACCESS_SYSTEM_SECURITY access if requested.  If the
    creator requests MAXIMUM_ALLOWED, the handle will be granted GENERIC_ALL.

Arguments:

    ObjectHandle - Handle to object.  The handle will receive the
        granted accesses if the call is successful.

    ObjectInformation - Pointer to object's information.  As a minimum, the
        object's Security Descriptor must be set up.

    DesiredAccess - Specifies a mask of the access types desired to the
        object.

    Options - Specifies optional actions to be taken

        LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK - Omit the check for a BDC for
            a create/update/delete operation on a local (non-replicated)
            object such as a local secret.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_ACCESS_DENIED - Not all of the Desired Accessed can be
            granted to the caller.

        STATUS_BACKUP_CONTROLLER - A create, update or delete operation
            is not allowed for a non-trusted client for this object on a BDC,
            because the object is global to all DC's for a domain and is replicated.
--*/

{
    NTSTATUS Status = STATUS_SUCCESS;
    ACCESS_MASK EffectiveDesiredAccess = DesiredAccess;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;
    LSAP_DB_OBJECT_TYPE_ID ObjectTypeId = InternalHandle->ObjectTypeId;
    BOOLEAN WriteOperation = FALSE;
    ULONG EffectiveOptions = Options | InternalHandle->Options;

    //
    // If the system is a Backup Domain Controller, disallow update
    // operations for non-trusted callers except in special cases such
    // as local non-replicated objects.  In these special cases, the
    // flag LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK will be already set
    // in the handle Options.
    //

    WriteOperation = RtlAreAnyAccessesGranted(
                         LsapDbState.DbObjectTypes[ObjectTypeId].WriteOperations,
                         EffectiveDesiredAccess
                         );

    if ((LsapDbState.PolicyLsaServerRoleInfo.LsaServerRole == PolicyServerRoleBackup)  &&
         (!InternalHandle->Trusted) &&
         WriteOperation &&
         (!(EffectiveOptions & LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK))) {

        Status = STATUS_BACKUP_CONTROLLER;
        return Status;
    }

    //
    // If MAXIMUM_ALLOWED is requested, add GENERIC_ALL
    //

    if (EffectiveDesiredAccess & MAXIMUM_ALLOWED) {

        EffectiveDesiredAccess |= GENERIC_ALL;
    }

    //
    // If ACCESS_SYSTEM_SECURITY is requested and we are a non-trusted
    // client, check that we have SE_SECURITY_PRIVILEGE.
    //

    if ((EffectiveDesiredAccess & ACCESS_SYSTEM_SECURITY) &&
        (!InternalHandle->Trusted)) {

        Status = LsapRtlWellKnownPrivilegeCheck(
                     (PVOID)ObjectHandle,
                     TRUE,
                     SE_SECURITY_PRIVILEGE,
                     NULL
                     );

        if (!NT_SUCCESS(Status)) {

            goto RequestAccessNewObjectError;
        }
    }

    //
    // Make sure the caller can be given the requested access
    // to the new object
    //

    InternalHandle->GrantedAccess = EffectiveDesiredAccess;

    RtlMapGenericMask(
        &InternalHandle->GrantedAccess,
        &LsapDbState.DbObjectTypes[ObjectTypeId].GenericMapping
        );

    if ((LsapDbState.DbObjectTypes[ObjectTypeId].InvalidMappedAccess
        &InternalHandle->GrantedAccess) != 0) {

        Status = STATUS_ACCESS_DENIED;
        goto RequestAccessNewObjectError;
    }

RequestAccessNewObjectFinish:

    return(Status);

RequestAccessNewObjectError:

    goto RequestAccessNewObjectFinish;
}


NTSTATUS
LsapDbCloseObject(
    IN PLSAPR_HANDLE ObjectHandle,
    IN ULONG Options
    )

/*++

Routine Description:

    This function closes (dereferences) a handle to an Lsa Database object.
    If the reference count of the handle reduces to 0, the handle is freed.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called.

Arguments:

    ObjectHandle - Pointer to handle to object from LsapDbOpenObject or
        LsapDbCreateObject.

    Options - Optional actions to be performed

        LSAP_DB_VALIDATE_HANDLE - Verify that the handle is valid.

        LSAP_DB_DEREFERENCE_CONTR - Dereference the Container Handle.  Note
            that the Container Handle was referenced when the subordinate
            handle was created.

        LSAP_DB_FREE_HANDLE - Free the handle whether or not the
            Reference Count reaches zero.

        LSAP_DB_ADMIT_DELETED_OBJECT_HANDLES - Permit the handle provided
            to be for a deleted object.

Return Value:

    NTSTATUS - Standard Nt Result Code

--*/

{
    NTSTATUS Status = STATUS_SUCCESS;

    //
    // Verify that the LSA Database is locked
    //

    ASSERT (LsapDbIsLocked());

    //
    // Dereference the object handle and free the handle if the reference count
    // reaches zero.  Optionally, the handle will be verified and/or freed
    // and the container object handle dereferenced.
    //

    Status = LsapDbDereferenceObject(
                 ObjectHandle,
                 NullObject,
                 Options,
                 (SECURITY_DB_DELTA_TYPE) 0,
                 Status
                 );

    *ObjectHandle = NULL;

    return(Status);
}


NTSTATUS
LsapDbDeleteObject(
    IN LSAPR_HANDLE ObjectHandle
    )

/*++

Routine Description:

    This function deletes an object from the Lsa Database.

Arguments:

    ObjectHandle - Handle to open object to be deleted.

Return Value:

    NTSTATUS - Standard NT Result Code.

        STATUS_INVALID_HANDLE - Handle is not a valid handle to an open
            object.

        STATUS_ACCESS_DENIED - Handle does not specify DELETE access.
--*/

{
    NTSTATUS Status;
    LSAP_DB_HANDLE Handle = (LSAP_DB_HANDLE) ObjectHandle;
    PUNICODE_STRING AttributeNames[LSAP_DB_MAX_ATTRIBUTES];
    PUNICODE_STRING *NextAttributeName;
    ULONG AttributeCount;
    ULONG AttributeNumber;
    LSAPR_TRUST_INFORMATION TrustInformation;

    //
    // Verify that the LSA Database is locked.
    //

    ASSERT (LsapDbIsLocked());

    //
    // All object types have a Security Descriptor stored as the SecDesc
    // attribute.
    //

    NextAttributeName = AttributeNames;
    AttributeCount = 0;
    *NextAttributeName = &LsapDbNames[SecDesc];

    NextAttributeName++;
    AttributeCount++;

    Status = STATUS_SUCCESS;

    //
    // Check the other references to the object and mark all other handles
    // invalid.
    //

    Status = LsapDbMarkDeletedObjectHandles( ObjectHandle, FALSE );

    if (!NT_SUCCESS(Status)) {

        goto DeleteObjectError;
    }

    //
    // Switch on object type
    //

    switch (Handle->ObjectTypeId) {

        case PolicyObject:

            Status = STATUS_INVALID_PARAMETER;
            break;

        case TrustedDomainObject:

            *NextAttributeName = &LsapDbNames[TrDmName];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[Sid];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[TrDmAcN];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[TrDmCtN];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[TrDmPxOf];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[TrDmCtEn];
            NextAttributeName++;
            AttributeCount++;

            //
            // Delete the object from the list of Trusted Domains
            //

            TrustInformation.Sid = Handle->Sid;
            TrustInformation.Name = *((PLSAPR_UNICODE_STRING) &Handle->LogicalNameU);

            Status = LsapDbDeleteTrustedDomainList( NULL, &TrustInformation );

            break;

        case AccountObject:

            *NextAttributeName = &LsapDbNames[Sid];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[ActSysAc];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[Privilgs];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[QuotaLim];
            NextAttributeName++;
            AttributeCount++;

            break;

        case SecretObject:

            *NextAttributeName = &LsapDbNames[CurrVal];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[OldVal];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[CupdTime];
            NextAttributeName++;
            AttributeCount++;

            *NextAttributeName = &LsapDbNames[OupdTime];
            NextAttributeName++;
            AttributeCount++;
            break;

        default:

            Status = STATUS_INVALID_PARAMETER;
            break;
    }


    if (!NT_SUCCESS(Status)) {

        goto DeleteObjectError;
    }

    //
    // Add Registry Transactions to delete each of the object's attributes.
    //

    for(AttributeNumber = 0; AttributeNumber < AttributeCount; AttributeNumber++) {

        Status = LsapDbDeleteAttributeObject(
                     ObjectHandle,
                     AttributeNames[AttributeNumber]
                     );

        //
        // Ignore "attribute not found" errors.  The object need not
        // have all attributes set, or may be only partially created.
        //

        if (!NT_SUCCESS(Status)) {

            if (Status != STATUS_OBJECT_NAME_NOT_FOUND) {

                break;
            }

            Status = STATUS_SUCCESS;
        }
    }

    if (!NT_SUCCESS(Status)) {

        goto DeleteObjectError;
    }

    //
    // Close the handle to the Registry Key representing the object.
    // The Registry transaction package will open another handle with
    // DELETE access to perform the deletion.
    //

    Status = NtClose(Handle->KeyHandle);

    Handle->KeyHandle = NULL;

    if (!NT_SUCCESS(Status)) {

        goto DeleteObjectError;
    }

    //
    // Add a Registry Transaction to delete the object's Registry Key.
    //

    Status = RtlAddActionToRXact(
                 LsapDbState.RXactContext,
                 RtlRXactOperationDelete,
                 &((LSAP_DB_HANDLE) ObjectHandle)->PhysicalNameU,
                 0L,
                 NULL,
                 0
                 );

    if (!NT_SUCCESS(Status)) {

        goto DeleteObjectError;
    }

DeleteObjectFinish:

    //
    // Decrement the count of objects of the given type.
    //

    LsapDbDecrementCountObject(
        ((LSAP_DB_HANDLE) ObjectHandle)->ObjectTypeId
        );

    return (Status);

DeleteObjectError:

    goto DeleteObjectFinish;
}


NTSTATUS
LsapDbReferenceObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN ACCESS_MASK DesiredAccess,
    IN LSAP_DB_OBJECT_TYPE_ID ObjectTypeId,
    IN ULONG Options
    )

/*++

Routine Description:

    This function verifies that a passed handle is valid, is for an
    object of the specified type and has the specified accesses granted.
    The handle's reference count is then incremented.  If Lsa Database
    locking is not requested, the Lsa Database must aready be locked.
    If Lsa Database locking is requested, the Lsa Database must NOT be
    locked.

Arguments:

    ObjectHandle - Pointer to handle to be validated and referenced.

    DesiredAccess - Specifies the accesses that are desired.  The function
        returns an error if any of the specified accesses have not been
        granted.

    ObjectTypeId - Specifies the expected object type to which the handle
        relates.  An error is returned if this type does not match the
        type contained in the handle.

    Options - Specifies optional additional actions including database state
        changes to be made, or actions not to be performed.

        LSAP_DB_ACQUIRE_LOCK - Acquire the Lsa database lock.  If this
            flag is specified, the Lsa Database must NOT already be locked.
            If this flag is not specified, the Lsa Database must already
            be locked.

        LSAP_DB_ACQUIRE_LOG_QUEUE_LOCK - Acquire the Lsa Audit Log Queue
            Lock.

        LSAP_DB_START_TRANSACTION - Start an Lsa database transaction.

        LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK - Omit check that local system
            is not a Backup Domain Controller.

        NOTE: There may be some Options (not database states) provided in the
              ObjectHandle.  These options augment those provided.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INVALID_HANDLE - The handle could not be found.

        STATUS_ACCESS_DENIED - Not all of the accesses specified have
            been granted.

        STATUS_OBJECT_TYPE_MISMATCH - The specified object type id does not
            match the object type id contained in the handle.

        STATUS_INSUFFICIENT_RESOURCES - Insufficient system resources to
            complete the command.  An example is too many references to
            the handle causing the count to overflow.

        STATUS_BACKUP_CONTROLLER - A request to open a transaction has been
            made by a non-trusted caller and the system is a Backup Domain
            Controller.  The LSA Database of a Backup Domain Controller
            can only be updated by a trusted client, such as a replicator.

        Result Codes from database transaction package.
--*/

{
    NTSTATUS Status;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;
    BOOLEAN GlobalSecret = FALSE;
    ULONG States, EffectiveOptions;
    ULONG ResetStates = 0;
    BOOLEAN WriteOperation;

    States = Options & LSAP_DB_STATE_MASK;

    //
    // Set the requested states before doing anything else.  This ensures
    // that the validity checks performed by this function are performed
    // while the Lsa database is locked.
    //

    if (States != 0) {

        Status = LsapDbSetStates( States );

        if (!NT_SUCCESS(Status)) {

            goto ReferenceError;
        }

        if (States & LSAP_DB_START_TRANSACTION) {

            ResetStates |= LSAP_DB_FINISH_TRANSACTION;
        }

        if (States & LSAP_DB_ACQUIRE_LOCK) {

            ResetStates |= LSAP_DB_RELEASE_LOCK;
        }

        if (States & LSAP_DB_ACQUIRE_LOG_QUEUE_LOCK) {

            ResetStates |= LSAP_DB_RELEASE_LOG_QUEUE_LOCK;
        }
    }

    //
    // Search the list of handles for the given handle, validate the
    // handle and verify that is for an object of the expected type.
    // Augment the options passed in with those contained in the handle.
    //

    Status =  LsapDbVerifyHandle( ObjectHandle, 0, ObjectTypeId );

    if (!NT_SUCCESS(Status)) {

        goto ReferenceError;
    }

    //
    // There may also be options set in the handle.  Take these into
    // account as well.
    //

    EffectiveOptions = Options | InternalHandle->Options;

    //
    // If the system is a Backup Domain Controller, disallow update
    // operations for non-trusted callers except in special cases such
    // as local non-replicated objects.  In these special cases where update
    // is allowed, the flag LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK will be already set
    // in the handle Options.
    //

    WriteOperation = RtlAreAnyAccessesGranted(
                         LsapDbState.DbObjectTypes[InternalHandle->ObjectTypeId].WriteOperations,
                         DesiredAccess
                         );

    if ((LsapDbState.PolicyLsaServerRoleInfo.LsaServerRole == PolicyServerRoleBackup)  &&
         (!InternalHandle->Trusted) &&
         WriteOperation &&
         (!(EffectiveOptions & LSAP_DB_OMIT_BACKUP_CONTROLLER_CHECK))) {

        Status = STATUS_BACKUP_CONTROLLER;
        goto ReferenceError;
    }

    //
    // If the handle is not Trusted, verify that the desired accesses have been granted
    //

    if (!(InternalHandle->Trusted)) {

        if (!RtlAreAllAccessesGranted( InternalHandle->GrantedAccess, DesiredAccess )) {

            Status = STATUS_ACCESS_DENIED;
            goto ReferenceError;
        }
    }

    //
    // Reference the handle
    //

    if (InternalHandle->ReferenceCount == LSAP_DB_MAXIMUM_REFERENCE_COUNT) {

        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto ReferenceError;
    }

    InternalHandle->ReferenceCount++;
    return (Status);

ReferenceError:

    //
    // Unset the states in the correct order.  If a database transaction
    // was started by this routine, it will be aborted.
    //

    Status = LsapDbResetStates(
                 ObjectHandle,
                 ResetStates,
                 (SECURITY_DB_DELTA_TYPE) 0,
                 Status
                 );

    return Status;
}


NTSTATUS
LsapDbDereferenceObject(
    IN OUT PLSAPR_HANDLE ObjectHandle,
    IN LSAP_DB_OBJECT_TYPE_ID ObjectTypeId,
    IN ULONG Options,
    IN SECURITY_DB_DELTA_TYPE SecurityDbDeltaType,
    IN NTSTATUS PreliminaryStatus
    )

/*++

Routine Description:

    This function dereferences a handle, optionally validating it first.
    If the Reference Count in the handle goes to 0, the handle is freed.
    The Lsa Database may optionally be unlocked by this function.  It
    must be locked before calling this function.

Arguments:

    ObjectHandle - Pointer to handle to be dereferenced.  If the reference
        count reaches 0, NULL is returned in this location.

    ObjectTypeId - Expected type of object.  This parameter is ignored
        if ValidateHandle is set to FALSE.

    Options - Specifies optional additional actions to be performed including
        Lsa Database states to be cleared.

        LSAP_DB_VALIDATE_HANDLE - Validate the handle.

        LSAP_DEREFERENCE_CONTR - Dereference the container object

        LSAP_DB_FREE_HANDLE - Free the handle whether or not the
            Reference Count reaches zero.  If LSAP_DB_DEREFERENCE_CONTR
            is also specified, the container handle Reference Count is
            decremented by the reference count in the handle being deleted.

        LSAP_DB_FINISH_TRANSACTION - A database transaction was started
            and must be concluded.  Conclude the current Lsa Database
            transaction by applying or aborting it depending on the
            final Status.

        LSAP_DB_RELEASE_LOCK - The Lsa database lock was acquired and
            should be released.

        LSAP_DB_RELEASE_LOG_QUEUE_LOCK - The Lsa Audit Log Queue Lock
            was acquired and should be released.

        LSAP_DB_OMIT_REPLICATOR_NOTIFICATION - Omit notification to
            Replicator of the change.

        LSAP_DB_ADMIT_DELETED_OBJECT_HANDLES - Permit the handle provided
            to be for a deleted object.

        NOTE: There may be some Options (not database states) provided in the
              ObjectHandle.  These options augment those provided.

    PreliminaryStatus = Current Result Code.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INVALID_HANDLE - The handle could not be found.

        STATUS_OBJECT_TYPE_MISMATCH - The specified object type id does not
            match the object type id contained in the handle.
--*/

{
    NTSTATUS Status, SecondaryStatus, TmpStatus;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) *ObjectHandle;
    BOOLEAN DecrementCount = TRUE;
    ULONG EffectiveOptions;
    ULONG ReferenceCount = 0;

    Status = PreliminaryStatus;
    SecondaryStatus = STATUS_SUCCESS;


    ASSERT (LsapDbIsLocked());

    //
    // There may also be options set in the handle.  Take these into
    // account as well.
    //

    EffectiveOptions = Options | InternalHandle->Options;

    //
    // If validating, lookup the handle and match the type.
    //

    if (EffectiveOptions & LSAP_DB_VALIDATE_HANDLE) {

        SecondaryStatus = LsapDbVerifyHandle(
                              *ObjectHandle,
                              EffectiveOptions,
                              ObjectTypeId
                              );

        if (!NT_SUCCESS(SecondaryStatus)) {

            DecrementCount = FALSE;
            goto DereferenceObjectError;
        }
    }

    //
    // Dereference the container handle if so requested
    //

    if (EffectiveOptions & LSAP_DB_DEREFERENCE_CONTR) {

        if (InternalHandle->ContainerHandle != NULL) {
            //
            // Dereference the container object.
            //

            Status = LsapDbDereferenceObject(
                        (PLSAPR_HANDLE) &InternalHandle->ContainerHandle,
                        NullObject,
                        0,
                        (SECURITY_DB_DELTA_TYPE) 0,
                        Status
                        );

        }
    }


DereferenceObjectFinish:

    //
    // Decrement the Reference Count.  If it becomes zero, free the
    // handle.  If explicitly requested to free the handle (regardless of
    // the Reference Count), force the Reference Count to zero prior to
    // freeing.
    //

    if (DecrementCount) {

        if (Options & LSAP_DB_FREE_HANDLE) {

            InternalHandle->ReferenceCount = (ULONG) 1;
        }

        (InternalHandle->ReferenceCount)--;
        ReferenceCount = InternalHandle->ReferenceCount;

    }


    //
    // This must happen after the reference count is adjusted, as it the one
    // that will unlock the database.
    //

    if (NT_SUCCESS(SecondaryStatus))
    {
        Status = LsapDbResetStates(
                    *ObjectHandle,
                    EffectiveOptions,
                    SecurityDbDeltaType,
                    Status
                    );

    }

    //
    // This has to happen after resetting states because resetting
    // requires the handle to be present.
    //

    if (DecrementCount && (ReferenceCount == 0)) {

        TmpStatus = NtCloseObjectAuditAlarm (
                        &LsapState.SubsystemName,
                        *ObjectHandle,
                        InternalHandle->GenerateOnClose
                        );

        if (!NT_SUCCESS( TmpStatus )) {
            LsapAuditFailed();
        }

        LsapDbFreeHandle( *ObjectHandle );

        *ObjectHandle = NULL;
    }



    return( Status );

DereferenceObjectError:

    if (NT_SUCCESS(Status) && !NT_SUCCESS(SecondaryStatus)) {

        Status = SecondaryStatus;
    }

    goto DereferenceObjectFinish;
}


NTSTATUS
LsapDbReadAttributeObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN PUNICODE_STRING AttributeNameU,
    IN OPTIONAL PVOID AttributeValue,
    IN OUT PULONG AttributeValueLength
    )

/*++

Routine Description:

    This routine reads the value of an attribute of an open LSA Database object.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called and the supplied ObjectHandle must be valid.

Arguments:

    ObjectHandle - LSA Handle to object.  This must be valid.

    AttributeNameU - Pointer to Unicode name of attribute

    AttributeValue - Pointer to buffer to receive attribute's value.  This
        parameter may be NULL if the input AttributeValueLength is zero.

    AttributeValueLength - Pointer to variable containing on input the size of
        attribute value buffer and on output the size of the attributes's
        value.  A value of zero may be specified to indicate that the size of
        the attribute's value is unknown.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_BUFFER_OVERFLOW - This warning is returned if the specified
            attribute value length is non-zero and too small for the
            attribute's value.
--*/

{
    //
    // The LSA Database is implemented as a subtree of the Configuration
    // Registry.  In this implementation, Lsa Database objects correspond
    // to Registry keys and "attributes" and their "values" correspond to
    // Registry "subkeys" and "values" of the Registry key representing the
    // object.
    //

    NTSTATUS Status, SecondaryStatus;
    ULONG SubKeyValueActualLength;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE SubKeyHandle = NULL;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;

    //
    // Verify that the LSA Database is locked
    //

    ASSERT (LsapDbIsLocked());

    //
    // Reading an attribute of an object is simpler than writing one,
    // because the Registry Transaction package is not used.  Since an
    // attribute is stored as the value of a subkey of the object's
    // Registry Key, we can simply call the Registry API RtlpNtReadKey
    // specifying the relative name of the subkey and the parent key's
    // handle.
    //
    // Prior to opening the subkey in the Registry, setup ObjectAttributes
    // containing the SubKey name and the Registry Handle for the LSA Database
    // Root.
    //

    InitializeObjectAttributes(
        &ObjectAttributes,
        AttributeNameU,
        OBJ_CASE_INSENSITIVE,
        InternalHandle->KeyHandle,
        NULL
        );

    //
    // Open the subkey
    //

    Status = RtlpNtOpenKey(
                 &SubKeyHandle,
                 KEY_READ,
                 &ObjectAttributes,
                 0L
                 );

    if (!NT_SUCCESS(Status)) {

        SubKeyHandle = NULL; //For error processing
        return(Status);
    }

    //
    // Now query the size of the buffer required to read the subkey's
    // value.
    //

    SubKeyValueActualLength = *AttributeValueLength;

    Status = RtlpNtQueryValueKey(
                 SubKeyHandle,
                 NULL,
                 NULL,
                 &SubKeyValueActualLength,
                 NULL
                 );

    if ((Status == STATUS_BUFFER_OVERFLOW) || NT_SUCCESS(Status)) {

        Status = STATUS_SUCCESS;

    } else {

        goto ReadAttError;
    }

    //
    // If a NULL buffer parameter has been supplied or the size of the
    // buffer given is 0, this is just a size query.
    //

    if (!ARGUMENT_PRESENT(AttributeValue) || *AttributeValueLength == 0) {

        *AttributeValueLength = SubKeyValueActualLength;
        Status = STATUS_SUCCESS;
        goto ReadAttError;

    } else if(*AttributeValueLength < SubKeyValueActualLength) {

        *AttributeValueLength = SubKeyValueActualLength;
        Status = STATUS_BUFFER_OVERFLOW;
        goto ReadAttError;
    }

    //
    // Supplied buffer is large enough to hold the SubKey's value.
    // Query the value.
    //

    Status = RtlpNtQueryValueKey(
                 SubKeyHandle,
                 NULL,
                 AttributeValue,
                 &SubKeyValueActualLength,
                 NULL
                 );

    if (!NT_SUCCESS(Status)) {

        goto ReadAttError;
    }

    //
    // Return the length of the Sub Key.
    //

    *AttributeValueLength = SubKeyValueActualLength;

ReadAttFinish:

    //
    // If necessary, close the Sub Key
    //

    if (SubKeyHandle != NULL) {

        SecondaryStatus = NtClose( SubKeyHandle );

#if DBG

        if (!NT_SUCCESS(SecondaryStatus)) {

            DbgPrint(
                "LsapDbReadAttributeObject: NtClose failed 0x%lx\n",
                Status
                );
        }

#endif // DBG

    }

    return(Status);

ReadAttError:

    goto ReadAttFinish;
}


NTSTATUS
LsapDbWriteAttributeObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN PUNICODE_STRING AttributeNameU,
    IN PVOID AttributeValue,
    IN ULONG AttributeValueLength
    )

/*++

Routine Description:

    This routine writes the value of an attribute of an open LSA Database
    object.  A Database transaction must already be open: the write is
    appended to the transaction log.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called.

Arguments:

    ObjectHandle - Lsa Handle of open object.

    AttributeNameU - Pointer to Unicode string containing the name of the
       attribute whose value is to be written.

    AttributeValue - Pointer to buffer containing attribute's value.  If NULL
        is specified for this parameter, AttributeValueLength must be 0.

    AttributeValueLength - Contains the size of attribute value buffer to be
        written.  0 may be specified, indicating that the attribute is to be
        deleted.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_SUCCESS - The attribute was successfully added to the
            transaction log.

        STATUS_INVALID_PARAMETER - AttributeValue is NULL but the
            AttributeValueLength value is not 0.

        Errors from the Registry Transaction Package.
--*/

{
    //
    // The LSA Database is implemented as a subtree of the Configuration
    // Registry.  In this implementation, Lsa Database objects correspond
    // to Registry keys and "attributes" and their "values" correspond to
    // Registry "subkeys" and "values" of the Registry key representing the
    // object.
    //

    NTSTATUS Status;
    UNICODE_STRING PhysicalSubKeyNameU;

    PhysicalSubKeyNameU.Buffer = NULL;

    //
    // Verify that the LSA Database is locked
    //

    ASSERT (LsapDbIsLocked());

    //
    // If the attribute value is null, verify that the AttributeValueLength
    // field is 0.
    //

    if (!ARGUMENT_PRESENT(AttributeValue)) {

        if (AttributeValueLength != 0) {

            Status = STATUS_INVALID_PARAMETER;
            goto WriteAttributeObjectError;
        }
    }

    //
    // Writing an object attribute's value is more complex than reading
    // one because the Registry Transaction package is called instead of
    // calling the Registry API directly.  Since the transaction package
    // expects to perform its own open of the target subkey representing
    // the attribute (when a transaction commit is finally done) using a
    // name relative to the LSA Database Registry Transaction Key (which
    // we call the Physical Name within the LSA Database code).  The
    // Registry Key handle contained in the object handle is therefore
    // not used by the present routine.  Instead, we need to construct the
    // Physical Name the sub key and pass it together with the LSA Database
    // Registry transaction key handle on the Registry transaction API
    // call.  The Physical Name of the subkey is constructed by
    // concatenating the Physical Object Name stored in the object handle
    // with a "\" and the given sub key name.
    //

    Status = LsapDbLogicalToPhysicalSubKey(
                 ObjectHandle,
                 &PhysicalSubKeyNameU,
                 AttributeNameU
                 );

    if (!NT_SUCCESS(Status)) {

        goto WriteAttributeObjectError;
    }

    //
    // Now log the sub key write as a Registry Transaction
    //

    Status = RtlAddActionToRXact(
                 LsapDbState.RXactContext,
                 RtlRXactOperationSetValue,
                 &PhysicalSubKeyNameU,
                 0L,
                 AttributeValue,
                 AttributeValueLength
                 );

    if (!NT_SUCCESS(Status)) {

        goto WriteAttributeObjectError;
    }

WriteAttributeObjectFinish:

    //
    // If necessary, free the Unicode String buffer allocated by
    // LsapDbLogicalToPhysicalSubKey;
    //

    if (PhysicalSubKeyNameU.Buffer != NULL) {

        RtlFreeUnicodeString(&PhysicalSubKeyNameU);
    }

    return(Status);

WriteAttributeObjectError:

    goto WriteAttributeObjectFinish;
}


NTSTATUS
LsapDbWriteAttributesObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN PLSAP_DB_ATTRIBUTE Attributes,
    IN ULONG AttributeCount
    )

/*++

Routine Description:

    This routine writes the values of one or more attributes of an open LSA
    Database object.  A Database transaction must already be open: the write
    is appended to the transaction log.  The attribute names specified are
    assumed to be consistent with the object type and the values supplied
    are assumed to be valid.

    WARNINGS:  The Lsa Database must be in the locked state when this function
               is called.

Arguments:

    ObjectHandle - Lsa Handle of open object.

    Attributes - Pointer to an array of Attribute Information blocks each
        containing pointers to the attribute's Unicode Name, the value
        to be stored, and the length of the value in bytes.

    AttributeCount - Count of the attributes to be written, equivalently,
        this is the number of elements of the array pointed to by Attributes.

Return Value:

    NTSTATUS - Standard Nt Result Code

--*/

{
    NTSTATUS Status = STATUS_SUCCESS;
    ULONG Index;

    for(Index = 0; Index < AttributeCount; Index++) {

        Status = LsapDbWriteAttributeObject(
                     ObjectHandle,
                     Attributes[Index].AttributeName,
                     Attributes[Index].AttributeValue,
                     Attributes[Index].AttributeValueLength
                     );


        if (!NT_SUCCESS(Status)) {

            break;
        }
    }

    return(Status);
}


NTSTATUS
LsapDbReadAttributesObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN OUT PLSAP_DB_ATTRIBUTE Attributes,
    IN ULONG AttributeCount
    )

/*++

Routine Description:

    This routine reads the values of one or more attributes of an open LSA
    Database object.  A Database transaction must already be open: the write
    is appended to the transaction log.  The attribute names specified are
    assumed to be consistent with the object type and the values supplied
    are assumed to be valid.  This routine will allocate memory via
    MIDL_user_allocate for buffers which will receive attribute values if
    requested.  This memory must be freed after use by calling MIDL_User_free
    after use.

    WARNINGS:  The Lsa Database must be in the locked state when this function
               is called.

Arguments:

    ObjectHandle - Lsa Handle of open object.

    Attributes - Pointer to an array of Attribute Information blocks each
        containing pointers to the attribute's Unicode Name, an optional
        pointer to a buffer that will receive the value and an optional
        length of the value expected in bytes.

        If the AttributeValue field in this structure is specified as non-NULL,
        the attribute's data will be returned in the specified buffer.  In
        this case, the AttributeValueLength field must specify a sufficiently
        large buffer size in bytes.  If the specified size is too small,
        a warning is returned and the buffer size required is returned in
        AttributeValueLength.

        If the AttributeValue field in this structure is NULL, the routine
        will allocate memory for the attribute value's buffer, via MIDL_user_allocate().  If
        the AttributeValueLength field is non-zero, the number of bytes specified
        will be allocated.  If the size of buffer allocated is too small to
        hold the attribute's value, a warning is returned.  If the
        AttributeValuelength field is 0, the routine will first query the size
        of buffer required and then allocate its memory.

        In all success cases and buffer overflow cases, the
        AttributeValueLength is set upon exit to the size of data required.

    AttributeCount - Count of the attributes to be read, equivalently,
        this is the number of elements of the array pointed to by Attributes.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_SUCCESS - The call completed successfully.

        STATUS_OBJECT_NAME_NOT_FOUND - One or more of the specified
            attributes do not exist.  In this case, the attribute information
            AttributeValue, AttributeValueLength fields are zeroised.  Note
            that an attempt will be made to read all of the supplied
            attributes, even if one of them is not found.

--*/

{
    NTSTATUS Status = STATUS_SUCCESS;
    PLSAP_DB_ATTRIBUTE NextAttribute = NULL;
    BOOLEAN MemoryToFree = FALSE;
    ULONG MemoryToFreeCount = 0;

    for (NextAttribute = Attributes;
         NextAttribute < &Attributes[AttributeCount];
         NextAttribute++) {

        NextAttribute->MemoryAllocated = FALSE;

        // If an explicit buffer pointer is given, verify that the length
        // specified is non-zero and attempt to use that buffer.
        //

        if (NextAttribute->AttributeValue != NULL) {

            if (NextAttribute->AttributeValueLength == 0) {


                return(STATUS_INVALID_PARAMETER);
            }

            Status = LsapDbReadAttributeObject(
                         ObjectHandle,
                         NextAttribute->AttributeName,
                         (PVOID) NextAttribute->AttributeValue,
                         (PULONG) &NextAttribute->AttributeValueLength
                         );

            if (!NT_SUCCESS(Status)) {

                //
                // If the attribute was not found, set the AttributeValue
                // and AttributeValueLength fields to NULL and continue.
                //

                if (Status != STATUS_OBJECT_NAME_NOT_FOUND) {

                    break;
                }

                NextAttribute->AttributeValue = NULL;
                NextAttribute->AttributeValueLength = 0;
            }

            continue;
        }

        //
        // No output buffer pointer has been given.  If a zero buffer
        // size is given, query size of memory required.  Since the
        // buffer length is 0, STATUS_SUCCESS should be returned rather
        // than STATUS_BUFFER_OVERFLOW.
        //

        if (NextAttribute->AttributeValueLength == 0) {

            Status = LsapDbReadAttributeObject(
                         ObjectHandle,
                         NextAttribute->AttributeName,
                         NULL,
                         (PULONG) &NextAttribute->AttributeValueLength
                         );

            if (!NT_SUCCESS(Status)) {

                //
                // If the attribute was not found, set the AttributeValue
                // and AttributeValueLength fields to NULL and continue.
                //

                if (Status != STATUS_OBJECT_NAME_NOT_FOUND) {

                    break;
                }

                NextAttribute->AttributeValue = NULL;
                NextAttribute->AttributeValueLength = 0;
                continue;
            }

            Status = STATUS_SUCCESS;
        }

        //
        // If the attribute value size needed is 0, return NULL pointer
        //

        if (NextAttribute->AttributeValueLength == 0) {

            NextAttribute->AttributeValue = NULL;
            continue;
        }

        //
        // Allocate memory for the buffer.
        //

        NextAttribute->AttributeValue =
            MIDL_user_allocate(NextAttribute->AttributeValueLength);

        if (NextAttribute->AttributeValue == NULL) {

            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        NextAttribute->MemoryAllocated = TRUE;
        MemoryToFree = TRUE;
        MemoryToFreeCount++;

        //
        // Now read the attribute into the buffer.
        //

        Status = LsapDbReadAttributeObject(
                     ObjectHandle,
                     NextAttribute->AttributeName,
                     (PVOID) NextAttribute->AttributeValue,
                     (PULONG) &NextAttribute->AttributeValueLength
                     );

        if (!NT_SUCCESS(Status)) {

            break;
        }
    }

    if (!NT_SUCCESS(Status)) {

        goto ReadAttributesError;
    }

ReadAttributesFinish:

    return(Status);

ReadAttributesError:

    //
    // If memory was allocated for any values read, it must be freed.
    //

    if (MemoryToFree) {

        for (NextAttribute = &Attributes[0];
             (MemoryToFreeCount > 0) &&
                 (NextAttribute < &Attributes[AttributeCount]);
             NextAttribute++) {

            if (NextAttribute->MemoryAllocated) {

                 MIDL_user_free( NextAttribute->AttributeValue );
                 NextAttribute->AttributeValue = NULL;
                 MemoryToFreeCount--;
            }
        }
    }

    goto ReadAttributesFinish;
}


NTSTATUS
LsapDbDeleteAttributeObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN PUNICODE_STRING AttributeNameU
    )

/*++

Routine Description:

    This routine deletes an attribute of an open LSA Database object.
    A Database transaction must already be open: the delete actions are
    appended to the transaction log.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called.

    The LSA Database is implemented as a subtree of the Configuration
    Registry.  In this implementation, Lsa Database objects correspond
    to Registry keys and "attributes" and their "values" correspond to
    Registry "subkeys" and "values" of the Registry key representing the
    object.

Arguments:

    ObjectHandle - Lsa Handle of open object.

    AttributeNameU - Pointer to Unicode string containing the name of the
       attribute whose value is to be written.

Return Value:

    NTSTATUS - Standard Nt Result Code

--*/

{
    NTSTATUS Status;
    UNICODE_STRING PhysicalSubKeyNameU;
    ULONG AttributeLength = 0;

    //
    // Verify that the LSA Database is locked
    //

    ASSERT (LsapDbIsLocked());

    //
    // The Registry code will actually create a key if one does not exist, so
    // probe for the existence of the key first.
    //

    Status = LsapDbReadAttributeObject(
                 ObjectHandle,
                 AttributeNameU,
                 NULL,
                 &AttributeLength
                 );

    if (!NT_SUCCESS(Status)) {

        goto DeleteAttributeObjectError;
    }

    //
    // We need to construct the Physical Name the sub key relative
    // to the LSA Database root node in the Registry.  This is done by
    // concatenating the Physical Object Name stored in the object handle with
    // a "\" and the given sub key name.
    //

    Status = LsapDbLogicalToPhysicalSubKey(
                 ObjectHandle,
                 &PhysicalSubKeyNameU,
                 AttributeNameU
                 );

    if (!NT_SUCCESS(Status)) {

        goto DeleteAttributeObjectError;
    }

    //
    // Now log the sub key write as a Registry Transaction
    //

    Status = RtlAddActionToRXact(
                 LsapDbState.RXactContext,
                 RtlRXactOperationDelete,
                 &PhysicalSubKeyNameU,
                 0L,
                 NULL,
                 0
                 );

    RtlFreeUnicodeString(&PhysicalSubKeyNameU);

    if (!NT_SUCCESS(Status)) {

        goto DeleteAttributeObjectError;
    }

DeleteAttributeObjectFinish:

    return(Status);

DeleteAttributeObjectError:

    //
    // Add any cleanup required on error paths only here.
    //

    goto DeleteAttributeObjectFinish;
}


NTSTATUS
LsapDbReferencesObject(
    IN LSAPR_HANDLE ObjectHandle,
    OUT PULONG ReferenceCount
    )

/*++

Routine Description:

    This function returns the Reference Count for the object.  This is
    the sum of the Reference Counts found in each open handle.  The LSA
    Database must be locked before calling this function.

Arguments:

    ObjectHandle - Handle to the object.

    ReferenceCount - Receives the Reference Count for the object.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INVALID_HANDLE - Specified handle is invalid.
--*/

{
    NTSTATUS Status;

    //
    // Verify that the Lsa Database is locked.
    //

    ASSERT (LsapDbIsLocked());

    Status = LsapDbReferencesHandle( ObjectHandle, ReferenceCount );

    return Status;
}


NTSTATUS
LsapDbNotifyChangeObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN SECURITY_DB_DELTA_TYPE SecurityDbDeltaType
    )

/*++

Routine Description:

    This function notifies the LSA Database Replicator (if any) of a
    change to an object.  Change notifications for Secret objects specify
    that replication of the change should occur immediately.

    WARNING! All parameters passed to this routine are assumed valid.
    No checking will be done.

Arguments:

    ObjectHandle - Handle to an LSA object.  This is expected to have
        already been validated.

    SecurityDbDeltaType - Specifies the type of change being made.  The
        following values only are relevant:

        SecurityDbNew - Indicates that a new object has been created.
        SecurityDbDelete - Indicates that an object is being deleted.
        SecurityDbChange - Indicates that the attributes of an object
            are being changed, including creation or deletion of
            attributes.

Return Values:

    NTSTATUS - Standard Nt Result Code.

        STATUS_SUCCESS - The call completed successfully.

        STATUS_INVALID_HANDLE - The specified handle is invalid.  This
            error is only returned if the Object Type Id in the handle
            is invalid.

        STATUS_INSUFFICIENT_RESOURCES - Insufficient system resources,
            such as memory, to complete the call.
--*/

{
    NTSTATUS Status = STATUS_SUCCESS;
    SECURITY_DB_OBJECT_TYPE ObjectType;
    UNICODE_STRING ObjectName;
    PSID ObjectSid = NULL;
    ULONG ObjectRid = 0;
    UCHAR SubAuthorityCount;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;
    BOOLEAN ReplicateImmediately = FALSE;

    ObjectName.Buffer = NULL;
    ObjectName.Length = ObjectName.MaximumLength = 0;

    //
    // If notifications are disabled, just exit.
    //

    if (!LsapDbState.ReplicatorNotificationEnabled) {

        goto NotifyChangeObjectFinish;
    }

    //
    // If the system is a Backup Domain Controller, don't notify the
    // replicator of any changes.
    //

    if (LsapDbState.PolicyLsaServerRoleInfo.LsaServerRole == PolicyServerRoleBackup) {

        goto NotifyChangeObjectFinish;
    }

    //
    // Convert the Lsa Database Object Type to a Database Delta Type.
    //

    switch (InternalHandle->ObjectTypeId) {

    case PolicyObject:

        ObjectType = SecurityDbObjectLsaPolicy;
        break;

    case AccountObject:

        ObjectType = SecurityDbObjectLsaAccount;
        break;

    case TrustedDomainObject:

        ObjectType = SecurityDbObjectLsaTDomain;
        break;

    case SecretObject:

        ObjectType = SecurityDbObjectLsaSecret;
        ReplicateImmediately = TRUE;
        break;

    default:

        Status = STATUS_INVALID_HANDLE;
        break;
    }

    if (!NT_SUCCESS(Status)) {

        goto NotifyChangeObjectError;
    }

    //
    // Get the Name or Sid of the object from its handle.  If the object
    // is of a type such as SecretObject that is accessed by Name, then
    // the object's externally known name is equal to its internal
    // Logical Name contained in the handle.
    //

    if (LsapDbAccessedBySidObject( InternalHandle->ObjectTypeId )) {

        ObjectSid = InternalHandle->Sid;
        SubAuthorityCount = *RtlSubAuthorityCountSid( ObjectSid );
        ObjectRid = *RtlSubAuthoritySid( ObjectSid, SubAuthorityCount -1 );

    } else if (LsapDbAccessedByNameObject( InternalHandle->ObjectTypeId )) {

        Status = LsapRpcCopyUnicodeString(
                     NULL,
                     &ObjectName,
                     &InternalHandle->LogicalNameU
                     );

        if (!NT_SUCCESS(Status)) {

            goto NotifyChangeObjectError;
        }

    } else {

        //
        // Currently, an object is either accessed by Sid or by Name, so
        // something is wrong if both of the above chacks have failed.
        //

        Status = STATUS_INVALID_HANDLE;

        goto NotifyChangeObjectError;
    }

    //
    // Notify the LSA Database Replicator of the change.
    //

    Status = I_NetNotifyDelta (
                 SecurityDbLsa,
                 LsapDbState.PolicyModificationInfo.ModifiedId,
                 SecurityDbDeltaType,
                 ObjectType,
                 ObjectRid,
                 ObjectSid,
                 &ObjectName,
                 ReplicateImmediately,
                 NULL
                 );

    if (!NT_SUCCESS(Status)) {

        goto NotifyChangeObjectError;
    }

NotifyChangeObjectFinish:

    //
    // If we allocated memory for the Object Name Unicode buffer, free it.
    //

    if (ObjectName.Buffer != NULL) {

        MIDL_user_free( ObjectName.Buffer );
    }

    //
    // Suppress any error and return STATUS_SUCCESS.  Currently, there is
    // no meaningful action an LSA client of this routine can take.
    //

    Status = STATUS_SUCCESS;

    return(Status);

NotifyChangeObjectError:

    goto NotifyChangeObjectFinish;
}


NTSTATUS
LsapDbVerifyInformationObject(
    IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation
    )

/*++

Routine Description:

    This function verifies that the information specified in passed
    ObjectInformation is syntactically valid.

Arguments:

    ObjectInformation - Pointer to information describing this object.  The
        following information items must be specified:

        o Object Type Id
        o Object Logical Name (as ObjectAttributes->ObjectName, a pointer to
             a Unicode string)
        o Container object handle (for any object except the root Policy object).

        All other fields in ObjectAttributes portion of ObjectInformation
        such as SecurityDescriptor are ignored.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INVALID_PARAMETER - Invalid object information given
            - ObjectInformation is NULL
            - Object Type Id is out of range
            - No Logical Name pointer given
            - Logical Name not a pointer to a Unicode String (TBS)
--*/

{
    NTSTATUS Status = STATUS_SUCCESS;

    LSAP_DB_OBJECT_TYPE_ID ObjectTypeId = ObjectInformation->ObjectTypeId;

    //
    // Verify that ObjectInformation is given
    //

    if (!ARGUMENT_PRESENT(ObjectInformation)) {

         return(STATUS_INVALID_PARAMETER);
    }

    //
    // Validate the Object Type Id.  It must be in range.
    //

    if (!LsapDbIsValidTypeObject(ObjectTypeId)) {

        return(STATUS_INVALID_PARAMETER);
    }

    //
    // Verify that a Logical Name is given.  A pointer to a Unicode string
    // is expected.
    //

    if (!ARGUMENT_PRESENT(ObjectInformation->ObjectAttributes.ObjectName)) {

        Status = STATUS_INVALID_PARAMETER;
    }

    return(Status);
}


NTSTATUS
LsapDbSidToLogicalNameObject(
    IN PSID Sid,
    OUT PUNICODE_STRING LogicalNameU
    )

/*++

Routine Description:

    This function generates the Logical Name (Internal LSA Database Name)
    of an object from its Sid.  Currently, only the Relative Id (lowest
    sub-authority) is used due to Registry and hence Lsa Database limits
    on name components to 8 characters.  The Rid is extracted and converted
    to an 8-digit Unicode Integer.

Arguments:

    Sid - Pointer to the Sid to be looked up.  It is the caller's
        responsibility to ensure that the Sid has valid syntax.

    LogicalNameU -  Pointer to a Unicode String structure that will receive
        the Logical Name.  Note that memory for the string buffer in this
        Unicode String will be allocated by this routine if successful.  The
        caller must free this memory after use by calling RtlFreeUnicodeString.

Return Value:

    NTSTATUS - Standard Nt Status code

        STATUS_INSUFFICIENT_RESOURCES - Insufficient system resources
            to allocate buffer for Unicode String name.
--*/

{
    NTSTATUS Status;

    //
    // First, verify that the given Sid is valid
    //

    if (!RtlValidSid( Sid )) {

        return STATUS_INVALID_PARAMETER;
    }


    Status = RtlConvertSidToUnicodeString( LogicalNameU, Sid, TRUE);

    return Status;
}


NTSTATUS
LsapDbGetNamesObject(
    IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
    OUT OPTIONAL PUNICODE_STRING LogicalNameU,
    OUT OPTIONAL PUNICODE_STRING PhysicalNameU
    )

/*++

Routine Description:

    This function returns the Logical and/or Physical Names of an object
    given an object information buffer.  Memory will be allocated for
    the Unicode String Buffers that will receive the name(s).

    The Logical Name of an object is the path of the object within the
    LSA Database relative to its Classifying Directory.  The Logical Name
    of an object is implemntation-dependent and on current implementations
    is equal to one of the following depending on object type:

    o The External Name of the object (if any)
    o The Relative Id (lowest sub-authority) in the object's Sid (if any)
      converted to an 8-digit integer, including leading 0's added as
      padding.

    The Physical Name of an object is the full path of the object relative
    to the root ot the Database.  It is computed by concatenating the Physical
    Name of the Container Object (if any), the Classifying Directory
    corresponding to the object type id, and the Logical Name of the
    object.

    <Physical Name of Object> =
        [<Physical Name of Container Object> "\"]
        [<Classifying Directory> "\"] <Logical Name of Object>

    If there is no Container Object (as in the case of the Policy object)
    the <Physical Name of Container Object> and following \ are omitted.
    If there is no Classifying Directory (as in the case of the Policy object)
    the <Classifying Directory> and following \ are omitted.  If neither
    Container Object not Classifying Directory exist, the Logical and Physical
    names coincide.

    Note that memory is allocated by this routine for the output
    Unicode string buffer(s).  When the output Unicode String(s) are no
    longer needed, the memory must be freed by call(s) to
    RtlFreeUnicodeString().

    Example of Physical Name computation:

    Consider the user or group account object ScottBi

    Container Object Logical Name:     Policy
    Container Object Physical Name:    Policy  (no Classifying Directory or
                                               Container Object exists)
    Classifying Directory for ScottBi: Accounts
    Logical Name of Object:            ScottBi
    Physical Name of Object            Policy\Accounts\ScottBi

    Note that the Physical Name is exactly the Registry path relative to
    the Security directory.

    WARNING:  The Lsa Database must be in the locked state when this function
              is called.

Arguments:

    ObjectInformation - Pointer to object information containing as a minimum
        the object's Logical Name, Container Object's handle and object type
        id.

    LogicalNameU - Optional pointer to Unicode String structure which will
        receive the Logical Name of the object.  A buffer will be allocated
        by this routine for the name text.  This memory must be freed when no
        longer needed by calling RtlFreeUnicodeString() wiht a pointer such
        as LogicalNameU to the Unicode String structure.

    PhysicalNameU - Optional pointer to Unicode String structure which will
       receive the Physical Name of the object.  A buffer will be allocated by
       this routine for the name text.  This memory must be freed when no
       longer needed by calling RtlFreeUnicodeString() with a pointer such as
       PhysicalNameU to the Unicode String structure.

Return Value:

    NTSTATUS - Standard Nt Result Code

        STATUS_INSUFFICIENT_RESOURCES - Insufficient system resources to
            allocate the name string buffer for the Physical Name or
            Logical Name.
--*/

{
    NTSTATUS Status;

    PUNICODE_STRING ContainerPhysicalNameU = NULL;
    PUNICODE_STRING ClassifyingDirU = NULL;
    UNICODE_STRING IntermediatePath1U;
    PUNICODE_STRING JoinedPath1U = &IntermediatePath1U;
    LSAP_DB_OBJECT_TYPE_ID ObjectTypeId = ObjectInformation->ObjectTypeId;
    POBJECT_ATTRIBUTES ObjectAttributes = &ObjectInformation->ObjectAttributes;

    UNICODE_STRING TempLogicalNameU;

    //
    // Initialize
    //

    RtlInitUnicodeString( &IntermediatePath1U, NULL );
    RtlInitUnicodeString( &TempLogicalNameU, NULL );

    //
    // Verify that the LSA Database is locked
    //

    ASSERT (LsapDbIsLocked());

    //
    // Capture the Logical Name of the object into permanent memory.
    //

    Status = LsapRtlCopyUnicodeString(
                 &TempLogicalNameU,
                 (PUNICODE_STRING)
                 ObjectInformation->ObjectAttributes.ObjectName,
                 TRUE
                 );

    if (!NT_SUCCESS(Status)) {

        goto GetNamesError;
    }

    //
    // If the Logical Name of the object is requested, return this.
    //

    if (ARGUMENT_PRESENT(LogicalNameU)) {

        *LogicalNameU = TempLogicalNameU;
    }

    //
    // If the Physical Name of the object is not required, just return.
    //

    if (!ARGUMENT_PRESENT(PhysicalNameU)) {

         goto GetNamesFinish;
    }

    //
    // The Physical Name of the object is requested.  Construct this
    // in stages.  First, get the Container Object Physical Name from
    // the handle stored inside ObjectAttributes.
    //

    if (ObjectAttributes->RootDirectory != NULL) {

        ContainerPhysicalNameU =
            &(((LSAP_DB_HANDLE)
                ObjectAttributes->RootDirectory)->PhysicalNameU);
    }

    //
    // Next, get the Classifying Directory name appropriate to the
    // object type.
    //

    if (LsapDbContDirs[ObjectTypeId].Length != 0) {

        ClassifyingDirU = &LsapDbContDirs[ObjectTypeId];
    }

    //
    // Now join the Physical Name of the Container Object and Classifying
    // Directory together.  If there is no Container Object and no
    // Classifying Directory, just set the result to NULL.
    //

    if (ContainerPhysicalNameU == NULL && ClassifyingDirU == NULL) {

        JoinedPath1U = NULL;

    } else {

        Status = LsapDbJoinSubPaths(
                     ContainerPhysicalNameU,
                     ClassifyingDirU,
                     JoinedPath1U
                     );

        if (!NT_SUCCESS(Status)) {

            goto GetNamesError;
        }
    }

    //
    // Now join the Physical Name of the Containing Object, Classifying
    // Directory  and Logical Name of the object together.  Note that
    // JoinedPath1U may be NULL, but LogicalNameU is never NULL.
    //

    Status = LsapDbJoinSubPaths(
                 JoinedPath1U,
                 &TempLogicalNameU,
                 PhysicalNameU
                 );
    if (JoinedPath1U != NULL) {

        RtlFreeUnicodeString( JoinedPath1U );
        JoinedPath1U = NULL;  // so we don't try to free it again
    }

    if (!NT_SUCCESS(Status)) {

        goto GetNamesError;
    }

    goto GetNamesFinish;

GetNamesError:

    //
    // If necessary, free any string buffer allocated for the Logical Name
    //

    RtlFreeUnicodeString( &TempLogicalNameU );

    //
    // If necessary, free any string buffer allocated to JoinedPath1U
    //

    if (JoinedPath1U != NULL) {

        RtlFreeUnicodeString( JoinedPath1U );
    }

GetNamesFinish:

    return Status;
}


BOOLEAN
LsapDbIsLocked()

/*++

Routine Description:

    Check if LSA Database is locked.

Arguments:

    None.

Return Value:

    BOOLEAN - TRUE if LSA database is locked, else false.

--*/

{
    return (BOOLEAN)(LsapDbState.DbLock.LockCount != -1L);
}


NTSTATUS
LsarQuerySecurityObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN SECURITY_INFORMATION SecurityInformation,
    OUT PLSAPR_SR_SECURITY_DESCRIPTOR *SecurityDescriptor
    )

/*++

Routine Description:

    The LsaQuerySecurityObject API returns security information assigned
    to an LSA Database object.

    Based on the caller's access rights and privileges, this procedure will
    return a security descriptor containing any or all of the object's owner
    ID, group ID, discretionary ACL or system ACL.  To read the owner ID,
    group ID, or the discretionary ACL, the caller must be granted
    READ_CONTROL access to the object.  To read the system ACL, the caller must
    have SeSecurityPrivilege privilege.

    This API is modelled after the NtQuerySecurityObject() system service.

Arguments:

    ObjectHandle - A handle to an existing object in the LSA Database.

    SecurityInformation - Supplies a value describing which pieces of
        security information are being queried.  The values that may be
        specified are the same as those defined in the NtSetSecurityObject()
        API section.

    SecurityDescriptor - Receives a pointer to a buffer containing the
        requested security information.  This information is returned in
        the form of a Self-Relative Security Descriptor.

Return Values:

    NTSTATUS - Standard Nt Result Code

        STATUS_ACCESS_DENIED - Caller does not have the appropriate access
            to complete the operation.

        STATUS_INVALID_PARAMETER - An invalid parameter has been specified.
--*/

{
    NTSTATUS
        Status,
        IgnoreStatus;

    LSAP_DB_HANDLE
        InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;

    ACCESS_MASK
        RequiredAccess = 0;

    BOOLEAN
        Present,
        IgnoreBoolean;

    LSAP_DB_ATTRIBUTE
        Attribute;

    PLSAPR_SR_SECURITY_DESCRIPTOR
        RpcSD = NULL;

    SECURITY_DESCRIPTOR
        *SD,
        *ReturnSD;

    ULONG
        ReturnSDLength;



    if (!ARGUMENT_PRESENT( SecurityDescriptor )) {
        return(STATUS_INVALID_PARAMETER);
    }

    //
    // If this is a non-Trusted client, determine the required accesses
    // for querying the object's Security Descriptor.  These accesses
    // depend on the information being queried.
    //

    LsapRtlQuerySecurityAccessMask( SecurityInformation, &RequiredAccess );


    //
    // Acquire the Lsa Database lock.  Verify that the object handle
    // is a valid handle (of any type) and is trusted or has
    // all of the required accesses granted.  Reference the container
    // object handle.
    //

    Status = LsapDbReferenceObject(
                 ObjectHandle,
                 RequiredAccess,
                 NullObject,
                 LSAP_DB_ACQUIRE_LOCK
                 );

    if (NT_SUCCESS(Status)) {


        //
        // Read the existing Security Descriptor for the object.  This always
        // exists as the value of the SecDesc attribute of the object.
        //

        LsapDbInitializeAttribute(
            &Attribute,
            &LsapDbNames[ SecDesc ],
            NULL,
            0,
            FALSE
            );

        Status = LsapDbReadAttribute( ObjectHandle, &Attribute );



        if (NT_SUCCESS(Status)) {

            SD = Attribute.AttributeValue;
            ASSERT( SD != NULL );


            //
            // Elimate components that weren't requested.
            //

            if ( !(SecurityInformation & OWNER_SECURITY_INFORMATION)) {
                SD->Owner = NULL;
            }

            if ( !(SecurityInformation & GROUP_SECURITY_INFORMATION)) {
                SD->Group = NULL;
            }

            if ( !(SecurityInformation & DACL_SECURITY_INFORMATION)) {
                SD->Control &= (~SE_DACL_PRESENT);
            }

            if ( !(SecurityInformation & SACL_SECURITY_INFORMATION)) {
                SD->Control &= (~SE_SACL_PRESENT);
            }


            //
            // Now copy the parts of the security descriptor that we are going to return.
            //

            ReturnSDLength = 0;
            ReturnSD = NULL;
            Status = RtlMakeSelfRelativeSD( (PSECURITY_DESCRIPTOR) SD,
                                            (PSECURITY_DESCRIPTOR) ReturnSD,
                                            &ReturnSDLength );

            if (Status == STATUS_BUFFER_TOO_SMALL) {    // This is the expected case

                ReturnSD = MIDL_user_allocate( ReturnSDLength );

                if (ReturnSD == NULL) {
                    Status = STATUS_INSUFFICIENT_RESOURCES;
                } else {
                    Status = RtlMakeSelfRelativeSD( (PSECURITY_DESCRIPTOR) SD,
                                                    (PSECURITY_DESCRIPTOR) ReturnSD,
                                                    &ReturnSDLength );
                    ASSERT( NT_SUCCESS(Status) );
                }
            }


            if (NT_SUCCESS(Status)) {

                //
                // Allocate the first block of returned memory.
                //

                RpcSD = MIDL_user_allocate( sizeof(LSAPR_SR_SECURITY_DESCRIPTOR) );

                if (RpcSD == NULL) {

                    Status = STATUS_INSUFFICIENT_RESOURCES;
                    if (ReturnSD != NULL) {
                        MIDL_user_free( ReturnSD );
                    }
                } else {

                    RpcSD->Length = ReturnSDLength;
                    RpcSD->SecurityDescriptor = (PUCHAR)( (PVOID)ReturnSD );
                }
            }


            //
            // free the attribute read from disk
            //

            MIDL_user_free( SD );
        }

        IgnoreStatus = LsapDbDereferenceObject(
                           &ObjectHandle,
                           InternalHandle->ObjectTypeId,
                           LSAP_DB_RELEASE_LOCK,
                           (SECURITY_DB_DELTA_TYPE) 0,
                           Status
                           );
        ASSERT( NT_SUCCESS(IgnoreStatus) );
    }


    *SecurityDescriptor = RpcSD;
    return(Status);
}



NTSTATUS
LsarSetSecurityObject(
    IN LSAPR_HANDLE ObjectHandle,
    IN SECURITY_INFORMATION SecurityInformation,
    IN PLSAPR_SR_SECURITY_DESCRIPTOR SecurityDescriptor
    )

/*++

Routine Description:

    The LsaSetSecurityObject API takes a well formaed Security Descriptor
    and assigns specified portions of it to an object.  Based on the flags set
    in the SecurityInformation parameter and the caller's access rights, this
    procedure will replace any or alll of the security information associated
    with the object.

    The caller must have WRITE_OWNER access to the object to change the
    owner or Primary group of the object.  The caller must have WRITE_DAC
    access to the object to change the Discretionary ACL.  The caller must
    have SeSecurityPrivilege to assign a system ACL to an object.

    This API is modelled after the NtSetSecurityObject() system service.

Arguments:

    ObjectHandle - A handle to an existing object in the LSA Database.

    SecurityInformation - Indicates which security information is to be
        applied to the object.  The values that may be specified are the
        same as those defined in the NtSetSecurityObject() API section.
        The value(s) to be assigned are passed in the SecurityDescriptor
        parameter.

    SecurityDescriptor - A pointer to a well formed Self-Relative
        Security Descriptor.

Return Values:

    NTSTATUS - Standard Nt Result Code

        STATUS_ACCESS_DENIED - Caller does not have the appropriate access
            to complete the operation.

        STATUS_INVALID_PARAMETER - An invalid parameter has been specified.
--*/

{
    NTSTATUS Status;
    NTSTATUS SecondaryStatus = STATUS_SUCCESS;
    ACCESS_MASK RequiredAccess = 0;
    LSAP_DB_HANDLE InternalHandle = (LSAP_DB_HANDLE) ObjectHandle;
    LSAP_DB_ATTRIBUTE Attribute;
    PSECURITY_DESCRIPTOR SetSD = NULL;
    PSECURITY_DESCRIPTOR RetrieveSD = NULL;
    PSECURITY_DESCRIPTOR ModificationSD = NULL;
    ULONG RetrieveSDLength;
    ULONG SetSDLength;
    BOOLEAN ObjectReferenced = FALSE;
    HANDLE ClientToken = NULL;

    //
    // Verify that a Security Descriptor has been passed.
    //

    Status = STATUS_INVALID_PARAMETER;

    if (!ARGUMENT_PRESENT( SecurityDescriptor )) {

        goto SetSecurityObjectError;
    }

    if (!ARGUMENT_PRESENT( SecurityDescriptor->SecurityDescriptor )) {

        goto SetSecurityObjectError;
    }

    ModificationSD = (PSECURITY_DESCRIPTOR)(SecurityDescriptor->SecurityDescriptor);

    //
    // If the caller is non-trusted, figure the accesses required
    // to update the object's Security Descriptor based on the
    // information being changed.
    //

    if (!InternalHandle->Trusted) {

        LsapRtlSetSecurityAccessMask( SecurityInformation, &RequiredAccess);
    }

    //
    // Acquire the Lsa Database lock.  Verify that the object handle
    // is a valid handle (of any type), and is trusted or has
    // all of the desired accesses granted.  Reference the container
    // object handle.
    //

    Status = LsapDbReferenceObject(
                 ObjectHandle,
                 RequiredAccess,
                 NullObject,
                 LSAP_DB_ACQUIRE_LOCK | LSAP_DB_START_TRANSACTION
                 );

    if (!NT_SUCCESS(Status)) {

        goto SetSecurityObjectError;
    }

    ObjectReferenced = TRUE;

    //
    // Read the existing Security Descriptor for the object.  This always
    // exists as the value of the SecDesc attribute of the object.
    //

    LsapDbInitializeAttribute(
        &Attribute,
        &LsapDbNames[ SecDesc ],
        NULL,
        0,
        FALSE
        );

    Status = LsapDbReadAttribute( ObjectHandle, &Attribute );

    if (!NT_SUCCESS(Status)) {

        goto SetSecurityObjectError;
    }

    //
    // Copy the retrieved descriptor into process heap so we can use
    // RTL routines.
    //

    RetrieveSD = Attribute.AttributeValue;
    RetrieveSDLength = Attribute.AttributeValueLength;

    Status = STATUS_INTERNAL_DB_CORRUPTION;

    if (RetrieveSD == NULL) {

        goto SetSecurityObjectError;
    }

    if (RetrieveSDLength == 0) {

        goto SetSecurityObjectError;
    }

    SetSD = RtlAllocateHeap( RtlProcessHeap(), 0, RetrieveSDLength );

    Status = STATUS_INSUFFICIENT_RESOURCES;

    if (SetSD == NULL) {

        goto SetSecurityObjectError;
    }

    RtlCopyMemory( SetSD, RetrieveSD, RetrieveSDLength );

    //
    // If the caller is replacing the owner, then a handle to the impersonation
    // token is necessary.
    //

    ClientToken = 0;

    if (SecurityInformation & OWNER_SECURITY_INFORMATION) {

        if (!InternalHandle->Trusted) {

            //
            // Client is non-trusted.  Impersonate the client and
            // obtain a handle to the impersonation token.
            //

            Status = I_RpcMapWin32Status(RpcImpersonateClient( NULL ));

            if (!NT_SUCCESS(Status)) {

                goto SetSecurityObjectError;
            }

            Status = NtOpenThreadToken(
                         NtCurrentThread(),
                         TOKEN_QUERY,
                         TRUE,            //OpenAsSelf
                         &ClientToken
                         );

            if (!NT_SUCCESS(Status)) {

                if (Status != STATUS_NO_TOKEN) {

                    goto SetSecurityObjectError;
                }
            }

            //
            // Stop impersonating the client
            //

            SecondaryStatus = I_RpcMapWin32Status(RpcRevertToSelf());

            if (!NT_SUCCESS(SecondaryStatus)) {

                goto SetSecurityObjectError;
            }

        } else {

            //
            // Client is trusted and so is the LSA Process itself.  Open the
            // process token
            //

            Status = NtOpenProcessToken(
                         NtCurrentProcess(),
                         TOKEN_QUERY,
                         &ClientToken
                         );

            if (!NT_SUCCESS(Status)) {

                goto SetSecurityObjectError;
            }
        }
    }

    //
    // Build the replacement security descriptor.  This must be done in
    // process heap to satisfy the needs of the RTL routine.
    //

    Status = RtlSetSecurityObject(
                 SecurityInformation,
                 ModificationSD,
                 &SetSD,
                 &(LsapDbState.
                     DbObjectTypes[InternalHandle->ObjectTypeId].GenericMapping),
                 ClientToken
                 );

    if (!NT_SUCCESS(Status)) {

        goto SetSecurityObjectError;
    }

    SetSDLength = RtlLengthSecurityDescriptor( SetSD );

    //
    // Now replace the existing SD with the updated one.
    //

    Status = LsapDbWriteAttributeObject(
                 ObjectHandle,
                 &LsapDbNames[SecDesc],
                 SetSD,
                 SetSDLength
                 );

    if (!NT_SUCCESS(Status)) {

        goto SetSecurityObjectError;
    }

SetSecurityObjectFinish:

    //
    // If necessary, close the Client Token.
    //

    if (ClientToken != 0) {

        SecondaryStatus = NtClose( ClientToken );

        ClientToken = NULL;

        if (!NT_SUCCESS( Status )) {

            goto SetSecurityObjectError;
        }
    }

    //
    // If necessary, free the buffer containing the retrieved SD.
    //

    if (RetrieveSD != NULL) {

        MIDL_user_free( RetrieveSD );
        RetrieveSD = NULL;
    }

    //
    // If necessary, dereference the object, finish the database
    // transaction, notify the LSA Database Replicator of the change,
    // release the LSA Database lock and return.
    //

    if (ObjectReferenced) {

        Status = LsapDbDereferenceObject(
                     &ObjectHandle,
                     InternalHandle->ObjectTypeId,
                     LSAP_DB_RELEASE_LOCK | LSAP_DB_FINISH_TRANSACTION,
                     SecurityDbChange,
                     Status
                     );

        ObjectReferenced = FALSE;
    }

    return(Status);

SetSecurityObjectError:

    if (NT_SUCCESS(Status)) {

        Status = SecondaryStatus;
    }

    goto SetSecurityObjectFinish;
}


NTSTATUS
LsapDbRebuildCache(
    IN LSAP_DB_OBJECT_TYPE_ID ObjectTypeId
    )

/*++

Routine Description:

    This function rebuilds cached information for a given LSA object type.

Arguments:

    ObjectTypeId - Specifies the Object Type for which the cached information
        is to be rebuilt.

Return Values:

    NTSTATUS - Standard Nt Result Code

--*/

{
    NTSTATUS Status = STATUS_SUCCESS;

    //
    // If caching is not supporte, just return.
    //

    if (!LsapDbIsCacheSupported( ObjectTypeId )) {

        goto RebuildCacheFinish;
    }

    //
    // Disable caching
    //

    LsapDbMakeCacheInvalid( ObjectTypeId );

    //
    // Call the build routine for the specified LSA object Type
    //

    switch (ObjectTypeId) {

    case PolicyObject:

        Status = LsapDbBuildPolicyCache();
        break;

    case AccountObject:

        Status = LsapDbBuildAccountCache();
        break;

    case TrustedDomainObject:

        Status = LsapDbBuildTrustedDomainCache();
        break;

    case SecretObject:

        Status = LsapDbBuildSecretCache();
        break;
    }

    if (!NT_SUCCESS(Status)) {

        goto RebuildCacheError;
    }

    //
    // Enable caching.
    //

    LsapDbMakeCacheValid(ObjectTypeId);

RebuildCacheFinish:

    return(Status);

RebuildCacheError:

    //
    // Disable caching until the next reboot.
    //

    LsapDbMakeCacheUnsupported( ObjectTypeId );
    LsapDbMakeCacheInvalid( ObjectTypeId );
    goto RebuildCacheFinish;
}