summaryrefslogtreecommitdiff
path: root/source3/winbindd/winbindd_cache.c
blob: 68972dd18d4ae5790e849f50fb61702f472dba7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
/* 
   Unix SMB/CIFS implementation.

   Winbind cache backend functions

   Copyright (C) Andrew Tridgell 2001
   Copyright (C) Gerald Carter   2003-2007
   Copyright (C) Volker Lendecke 2005
   Copyright (C) Guenther Deschner 2005
   Copyright (C) Michael Adam    2007

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "winbindd.h"
#include "tdb_validate.h"
#include "../libcli/auth/libcli_auth.h"
#include "../librpc/gen_ndr/ndr_wbint.h"

#undef DBGC_CLASS
#define DBGC_CLASS DBGC_WINBIND

#define WINBINDD_CACHE_VERSION 1
#define WINBINDD_CACHE_VERSION_KEYSTR "WINBINDD_CACHE_VERSION"

extern struct winbindd_methods reconnect_methods;
#ifdef HAVE_ADS
extern struct winbindd_methods ads_methods;
#endif
extern struct winbindd_methods builtin_passdb_methods;

/*
 * JRA. KEEP THIS LIST UP TO DATE IF YOU ADD CACHE ENTRIES.
 * Here are the list of entry types that are *not* stored
 * as form struct cache_entry in the cache.
 */

static const char *non_centry_keys[] = {
	"SEQNUM/",
	"DR/",
	"DE/",
	"WINBINDD_OFFLINE",
	WINBINDD_CACHE_VERSION_KEYSTR,
	NULL
};

/************************************************************************
 Is this key a non-centry type ?
************************************************************************/

static bool is_non_centry_key(TDB_DATA kbuf)
{
	int i;

	if (kbuf.dptr == NULL || kbuf.dsize == 0) {
		return false;
	}
	for (i = 0; non_centry_keys[i] != NULL; i++) {
		size_t namelen = strlen(non_centry_keys[i]);
		if (kbuf.dsize < namelen) {
			continue;
		}
		if (strncmp(non_centry_keys[i], (const char *)kbuf.dptr, namelen) == 0) {
			return true;
		}
	}
	return false;
}

/* Global online/offline state - False when online. winbindd starts up online
   and sets this to true if the first query fails and there's an entry in
   the cache tdb telling us to stay offline. */

static bool global_winbindd_offline_state;

struct winbind_cache {
	TDB_CONTEXT *tdb;
};

struct cache_entry {
	NTSTATUS status;
	uint32 sequence_number;
	uint8 *data;
	uint32 len, ofs;
};

void (*smb_panic_fn)(const char *const why) = smb_panic;

#define WINBINDD_MAX_CACHE_SIZE (50*1024*1024)

static struct winbind_cache *wcache;

void winbindd_check_cache_size(time_t t)
{
	static time_t last_check_time;
	struct stat st;

	if (last_check_time == (time_t)0)
		last_check_time = t;

	if (t - last_check_time < 60 && t - last_check_time > 0)
		return;

	if (wcache == NULL || wcache->tdb == NULL) {
		DEBUG(0, ("Unable to check size of tdb cache - cache not open !\n"));
		return;
	}

	if (fstat(tdb_fd(wcache->tdb), &st) == -1) {
		DEBUG(0, ("Unable to check size of tdb cache %s!\n", strerror(errno) ));
		return;
	}

	if (st.st_size > WINBINDD_MAX_CACHE_SIZE) {
		DEBUG(10,("flushing cache due to size (%lu) > (%lu)\n",
			(unsigned long)st.st_size,
			(unsigned long)WINBINDD_MAX_CACHE_SIZE));
		wcache_flush_cache();
	}
}

/* get the winbind_cache structure */
static struct winbind_cache *get_cache(struct winbindd_domain *domain)
{
	struct winbind_cache *ret = wcache;

	/* We have to know what type of domain we are dealing with first. */

	if (domain->internal) {
		domain->backend = &builtin_passdb_methods;
		domain->initialized = True;
	}
	if ( !domain->initialized ) {
		init_dc_connection( domain );
	}

	/* 
	   OK.  listen up becasue I'm only going to say this once.
	   We have the following scenarios to consider
	   (a) trusted AD domains on a Samba DC,
	   (b) trusted AD domains and we are joined to a non-kerberos domain
	   (c) trusted AD domains and we are joined to a kerberos (AD) domain

	   For (a) we can always contact the trusted domain using krb5 
	   since we have the domain trust account password

	   For (b) we can only use RPC since we have no way of 
	   getting a krb5 ticket in our own domain

	   For (c) we can always use krb5 since we have a kerberos trust

	   --jerry
	 */

	if (!domain->backend) {
#ifdef HAVE_ADS
		struct winbindd_domain *our_domain = domain;

		/* find our domain first so we can figure out if we 
		   are joined to a kerberized domain */

		if ( !domain->primary )
			our_domain = find_our_domain();

		if ((our_domain->active_directory || IS_DC)
		    && domain->active_directory
		    && !lp_winbind_rpc_only()) {
			DEBUG(5,("get_cache: Setting ADS methods for domain %s\n", domain->name));
			domain->backend = &ads_methods;
		} else {
#endif	/* HAVE_ADS */
			DEBUG(5,("get_cache: Setting MS-RPC methods for domain %s\n", domain->name));
			domain->backend = &reconnect_methods;
#ifdef HAVE_ADS
		}
#endif	/* HAVE_ADS */
	}

	if (ret)
		return ret;

	ret = SMB_XMALLOC_P(struct winbind_cache);
	ZERO_STRUCTP(ret);

	wcache = ret;
	wcache_flush_cache();

	return ret;
}

/*
  free a centry structure
*/
static void centry_free(struct cache_entry *centry)
{
	if (!centry)
		return;
	SAFE_FREE(centry->data);
	free(centry);
}

static bool centry_check_bytes(struct cache_entry *centry, size_t nbytes)
{
	if (centry->len - centry->ofs < nbytes) {
		DEBUG(0,("centry corruption? needed %u bytes, have %d\n", 
			 (unsigned int)nbytes,
			 centry->len - centry->ofs));
		return false;
	}
	return true;
}

/*
  pull a uint32 from a cache entry 
*/
static uint32 centry_uint32(struct cache_entry *centry)
{
	uint32 ret;

	if (!centry_check_bytes(centry, 4)) {
		smb_panic_fn("centry_uint32");
	}
	ret = IVAL(centry->data, centry->ofs);
	centry->ofs += 4;
	return ret;
}

/*
  pull a uint16 from a cache entry 
*/
static uint16 centry_uint16(struct cache_entry *centry)
{
	uint16 ret;
	if (!centry_check_bytes(centry, 2)) {
		smb_panic_fn("centry_uint16");
	}
	ret = CVAL(centry->data, centry->ofs);
	centry->ofs += 2;
	return ret;
}

/*
  pull a uint8 from a cache entry 
*/
static uint8 centry_uint8(struct cache_entry *centry)
{
	uint8 ret;
	if (!centry_check_bytes(centry, 1)) {
		smb_panic_fn("centry_uint8");
	}
	ret = CVAL(centry->data, centry->ofs);
	centry->ofs += 1;
	return ret;
}

/*
  pull a NTTIME from a cache entry 
*/
static NTTIME centry_nttime(struct cache_entry *centry)
{
	NTTIME ret;
	if (!centry_check_bytes(centry, 8)) {
		smb_panic_fn("centry_nttime");
	}
	ret = IVAL(centry->data, centry->ofs);
	centry->ofs += 4;
	ret += (uint64_t)IVAL(centry->data, centry->ofs) << 32;
	centry->ofs += 4;
	return ret;
}

/*
  pull a time_t from a cache entry. time_t stored portably as a 64-bit time.
*/
static time_t centry_time(struct cache_entry *centry)
{
	return (time_t)centry_nttime(centry);
}

/* pull a string from a cache entry, using the supplied
   talloc context 
*/
static char *centry_string(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
{
	uint32 len;
	char *ret;

	len = centry_uint8(centry);

	if (len == 0xFF) {
		/* a deliberate NULL string */
		return NULL;
	}

	if (!centry_check_bytes(centry, (size_t)len)) {
		smb_panic_fn("centry_string");
	}

	ret = TALLOC_ARRAY(mem_ctx, char, len+1);
	if (!ret) {
		smb_panic_fn("centry_string out of memory\n");
	}
	memcpy(ret,centry->data + centry->ofs, len);
	ret[len] = 0;
	centry->ofs += len;
	return ret;
}

/* pull a hash16 from a cache entry, using the supplied
   talloc context 
*/
static char *centry_hash16(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
{
	uint32 len;
	char *ret;

	len = centry_uint8(centry);

	if (len != 16) {
		DEBUG(0,("centry corruption? hash len (%u) != 16\n", 
			len ));
		return NULL;
	}

	if (!centry_check_bytes(centry, 16)) {
		return NULL;
	}

	ret = TALLOC_ARRAY(mem_ctx, char, 16);
	if (!ret) {
		smb_panic_fn("centry_hash out of memory\n");
	}
	memcpy(ret,centry->data + centry->ofs, 16);
	centry->ofs += 16;
	return ret;
}

/* pull a sid from a cache entry, using the supplied
   talloc context 
*/
static bool centry_sid(struct cache_entry *centry, struct dom_sid *sid)
{
	char *sid_string;
	bool ret;

	sid_string = centry_string(centry, talloc_tos());
	if (sid_string == NULL) {
		return false;
	}
	ret = string_to_sid(sid, sid_string);
	TALLOC_FREE(sid_string);
	return ret;
}


/*
  pull a NTSTATUS from a cache entry
*/
static NTSTATUS centry_ntstatus(struct cache_entry *centry)
{
	NTSTATUS status;

	status = NT_STATUS(centry_uint32(centry));
	return status;
}


/* the server is considered down if it can't give us a sequence number */
static bool wcache_server_down(struct winbindd_domain *domain)
{
	bool ret;

	if (!wcache->tdb)
		return false;

	ret = (domain->sequence_number == DOM_SEQUENCE_NONE);

	if (ret)
		DEBUG(10,("wcache_server_down: server for Domain %s down\n", 
			domain->name ));
	return ret;
}

static bool wcache_fetch_seqnum(const char *domain_name, uint32_t *seqnum,
				uint32_t *last_seq_check)
{
	char *key;
	TDB_DATA data;

	if (wcache->tdb == NULL) {
		DEBUG(10,("wcache_fetch_seqnum: tdb == NULL\n"));
		return false;
	}

	key = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
	if (key == NULL) {
		DEBUG(10, ("talloc failed\n"));
		return false;
	}

	data = tdb_fetch_bystring(wcache->tdb, key);
	TALLOC_FREE(key);

	if (data.dptr == NULL) {
		DEBUG(10, ("wcache_fetch_seqnum: %s not found\n",
			   domain_name));
		return false;
	}
	if (data.dsize != 8) {
		DEBUG(10, ("wcache_fetch_seqnum: invalid data size %d\n",
			   (int)data.dsize));
		SAFE_FREE(data.dptr);
		return false;
	}

	*seqnum = IVAL(data.dptr, 0);
	*last_seq_check = IVAL(data.dptr, 4);
	SAFE_FREE(data.dptr);

	return true;
}

static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
{
	uint32 last_check, time_diff;

	if (!wcache_fetch_seqnum(domain->name, &domain->sequence_number,
				 &last_check)) {
		return NT_STATUS_UNSUCCESSFUL;
	}
	domain->last_seq_check = last_check;

	/* have we expired? */

	time_diff = now - domain->last_seq_check;
	if ( time_diff > lp_winbind_cache_time() ) {
		DEBUG(10,("fetch_cache_seqnum: timeout [%s][%u @ %u]\n",
			domain->name, domain->sequence_number,
			(uint32)domain->last_seq_check));
		return NT_STATUS_UNSUCCESSFUL;
	}

	DEBUG(10,("fetch_cache_seqnum: success [%s][%u @ %u]\n", 
		domain->name, domain->sequence_number, 
		(uint32)domain->last_seq_check));

	return NT_STATUS_OK;
}

bool wcache_store_seqnum(const char *domain_name, uint32_t seqnum,
			 time_t last_seq_check)
{
	char *key_str;
	uint8_t buf[8];
	int ret;

	if (wcache->tdb == NULL) {
		DEBUG(10, ("wcache_store_seqnum: wcache->tdb == NULL\n"));
		return false;
	}

	key_str = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
	if (key_str == NULL) {
		DEBUG(10, ("talloc_asprintf failed\n"));
		return false;
	}

	SIVAL(buf, 0, seqnum);
	SIVAL(buf, 4, last_seq_check);

	ret = tdb_store_bystring(wcache->tdb, key_str,
				 make_tdb_data(buf, sizeof(buf)), TDB_REPLACE);
	TALLOC_FREE(key_str);
	if (ret == -1) {
		DEBUG(10, ("tdb_store_bystring failed: %s\n",
			   tdb_errorstr(wcache->tdb)));
		TALLOC_FREE(key_str);
		return false;
	}

	DEBUG(10, ("wcache_store_seqnum: success [%s][%u @ %u]\n",
		   domain_name, seqnum, (unsigned)last_seq_check));

	return true;
}

static bool store_cache_seqnum( struct winbindd_domain *domain )
{
	return wcache_store_seqnum(domain->name, domain->sequence_number,
				   domain->last_seq_check);
}

/*
  refresh the domain sequence number. If force is true
  then always refresh it, no matter how recently we fetched it
*/

static void refresh_sequence_number(struct winbindd_domain *domain, bool force)
{
	NTSTATUS status;
	unsigned time_diff;
	time_t t = time(NULL);
	unsigned cache_time = lp_winbind_cache_time();

	if (is_domain_offline(domain)) {
		return;
	}

	get_cache( domain );

#if 0	/* JERRY -- disable as the default cache time is now 5 minutes */
	/* trying to reconnect is expensive, don't do it too often */
	if (domain->sequence_number == DOM_SEQUENCE_NONE) {
		cache_time *= 8;
	}
#endif

	time_diff = t - domain->last_seq_check;

	/* see if we have to refetch the domain sequence number */
	if (!force && (time_diff < cache_time) &&
			(domain->sequence_number != DOM_SEQUENCE_NONE) &&
			NT_STATUS_IS_OK(domain->last_status)) {
		DEBUG(10, ("refresh_sequence_number: %s time ok\n", domain->name));
		goto done;
	}

	/* try to get the sequence number from the tdb cache first */
	/* this will update the timestamp as well */

	status = fetch_cache_seqnum( domain, t );
	if (NT_STATUS_IS_OK(status) &&
			(domain->sequence_number != DOM_SEQUENCE_NONE) &&
			NT_STATUS_IS_OK(domain->last_status)) {
		goto done;
	}

	/* important! make sure that we know if this is a native 
	   mode domain or not.  And that we can contact it. */

	if ( winbindd_can_contact_domain( domain ) ) {		
		status = domain->backend->sequence_number(domain, 
							  &domain->sequence_number);
	} else {
		/* just use the current time */
		status = NT_STATUS_OK;
		domain->sequence_number = time(NULL);
	}


	/* the above call could have set our domain->backend to NULL when
	 * coming from offline to online mode, make sure to reinitialize the
	 * backend - Guenther */
	get_cache( domain );

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(10,("refresh_sequence_number: failed with %s\n", nt_errstr(status)));
		domain->sequence_number = DOM_SEQUENCE_NONE;
	}

	domain->last_status = status;
	domain->last_seq_check = time(NULL);

	/* save the new sequence number in the cache */
	store_cache_seqnum( domain );

done:
	DEBUG(10, ("refresh_sequence_number: %s seq number is now %d\n", 
		   domain->name, domain->sequence_number));

	return;
}

/*
  decide if a cache entry has expired
*/
static bool centry_expired(struct winbindd_domain *domain, const char *keystr, struct cache_entry *centry)
{
	/* If we've been told to be offline - stay in that state... */
	if (lp_winbind_offline_logon() && global_winbindd_offline_state) {
		DEBUG(10,("centry_expired: Key %s for domain %s valid as winbindd is globally offline.\n",
			keystr, domain->name ));
		return false;
	}

	/* when the domain is offline return the cached entry.
	 * This deals with transient offline states... */

	if (!domain->online) {
		DEBUG(10,("centry_expired: Key %s for domain %s valid as domain is offline.\n",
			keystr, domain->name ));
		return false;
	}

	/* if the server is OK and our cache entry came from when it was down then
	   the entry is invalid */
	if ((domain->sequence_number != DOM_SEQUENCE_NONE) &&  
	    (centry->sequence_number == DOM_SEQUENCE_NONE)) {
		DEBUG(10,("centry_expired: Key %s for domain %s invalid sequence.\n",
			keystr, domain->name ));
		return true;
	}

	/* if the server is down or the cache entry is not older than the
	   current sequence number then it is OK */
	if (wcache_server_down(domain) || 
	    centry->sequence_number == domain->sequence_number) {
		DEBUG(10,("centry_expired: Key %s for domain %s is good.\n",
			keystr, domain->name ));
		return false;
	}

	DEBUG(10,("centry_expired: Key %s for domain %s expired\n",
		keystr, domain->name ));

	/* it's expired */
	return true;
}

static struct cache_entry *wcache_fetch_raw(char *kstr)
{
	TDB_DATA data;
	struct cache_entry *centry;
	TDB_DATA key;

	key = string_tdb_data(kstr);
	data = tdb_fetch(wcache->tdb, key);
	if (!data.dptr) {
		/* a cache miss */
		return NULL;
	}

	centry = SMB_XMALLOC_P(struct cache_entry);
	centry->data = (unsigned char *)data.dptr;
	centry->len = data.dsize;
	centry->ofs = 0;

	if (centry->len < 8) {
		/* huh? corrupt cache? */
		DEBUG(10,("wcache_fetch_raw: Corrupt cache for key %s (len < 8) ?\n", kstr));
		centry_free(centry);
		return NULL;
	}

	centry->status = centry_ntstatus(centry);
	centry->sequence_number = centry_uint32(centry);

	return centry;
}

/*
  fetch an entry from the cache, with a varargs key. auto-fetch the sequence
  number and return status
*/
static struct cache_entry *wcache_fetch(struct winbind_cache *cache, 
					struct winbindd_domain *domain,
					const char *format, ...) PRINTF_ATTRIBUTE(3,4);
static struct cache_entry *wcache_fetch(struct winbind_cache *cache, 
					struct winbindd_domain *domain,
					const char *format, ...)
{
	va_list ap;
	char *kstr;
	struct cache_entry *centry;

	if (!winbindd_use_cache()) {
		return NULL;
	}

	refresh_sequence_number(domain, false);

	va_start(ap, format);
	smb_xvasprintf(&kstr, format, ap);
	va_end(ap);

	centry = wcache_fetch_raw(kstr);
	if (centry == NULL) {
		free(kstr);
		return NULL;
	}

	if (centry_expired(domain, kstr, centry)) {

		DEBUG(10,("wcache_fetch: entry %s expired for domain %s\n",
			 kstr, domain->name ));

		centry_free(centry);
		free(kstr);
		return NULL;
	}

	DEBUG(10,("wcache_fetch: returning entry %s for domain %s\n",
		 kstr, domain->name ));

	free(kstr);
	return centry;
}

static void wcache_delete(const char *format, ...) PRINTF_ATTRIBUTE(1,2);
static void wcache_delete(const char *format, ...)
{
	va_list ap;
	char *kstr;
	TDB_DATA key;

	va_start(ap, format);
	smb_xvasprintf(&kstr, format, ap);
	va_end(ap);

	key = string_tdb_data(kstr);

	tdb_delete(wcache->tdb, key);
	free(kstr);
}

/*
  make sure we have at least len bytes available in a centry 
*/
static void centry_expand(struct cache_entry *centry, uint32 len)
{
	if (centry->len - centry->ofs >= len)
		return;
	centry->len *= 2;
	centry->data = SMB_REALLOC_ARRAY(centry->data, unsigned char,
					 centry->len);
	if (!centry->data) {
		DEBUG(0,("out of memory: needed %d bytes in centry_expand\n", centry->len));
		smb_panic_fn("out of memory in centry_expand");
	}
}

/*
  push a uint32 into a centry 
*/
static void centry_put_uint32(struct cache_entry *centry, uint32 v)
{
	centry_expand(centry, 4);
	SIVAL(centry->data, centry->ofs, v);
	centry->ofs += 4;
}

/*
  push a uint16 into a centry 
*/
static void centry_put_uint16(struct cache_entry *centry, uint16 v)
{
	centry_expand(centry, 2);
	SIVAL(centry->data, centry->ofs, v);
	centry->ofs += 2;
}

/*
  push a uint8 into a centry 
*/
static void centry_put_uint8(struct cache_entry *centry, uint8 v)
{
	centry_expand(centry, 1);
	SCVAL(centry->data, centry->ofs, v);
	centry->ofs += 1;
}

/* 
   push a string into a centry 
 */
static void centry_put_string(struct cache_entry *centry, const char *s)
{
	int len;

	if (!s) {
		/* null strings are marked as len 0xFFFF */
		centry_put_uint8(centry, 0xFF);
		return;
	}

	len = strlen(s);
	/* can't handle more than 254 char strings. Truncating is probably best */
	if (len > 254) {
		DEBUG(10,("centry_put_string: truncating len (%d) to: 254\n", len));
		len = 254;
	}
	centry_put_uint8(centry, len);
	centry_expand(centry, len);
	memcpy(centry->data + centry->ofs, s, len);
	centry->ofs += len;
}

/* 
   push a 16 byte hash into a centry - treat as 16 byte string.
 */
static void centry_put_hash16(struct cache_entry *centry, const uint8 val[16])
{
	centry_put_uint8(centry, 16);
	centry_expand(centry, 16);
	memcpy(centry->data + centry->ofs, val, 16);
	centry->ofs += 16;
}

static void centry_put_sid(struct cache_entry *centry, const DOM_SID *sid) 
{
	fstring sid_string;
	centry_put_string(centry, sid_to_fstring(sid_string, sid));
}


/*
  put NTSTATUS into a centry
*/
static void centry_put_ntstatus(struct cache_entry *centry, NTSTATUS status)
{
	uint32 status_value = NT_STATUS_V(status);
	centry_put_uint32(centry, status_value);
}


/*
  push a NTTIME into a centry 
*/
static void centry_put_nttime(struct cache_entry *centry, NTTIME nt)
{
	centry_expand(centry, 8);
	SIVAL(centry->data, centry->ofs, nt & 0xFFFFFFFF);
	centry->ofs += 4;
	SIVAL(centry->data, centry->ofs, nt >> 32);
	centry->ofs += 4;
}

/*
  push a time_t into a centry - use a 64 bit size.
  NTTIME here is being used as a convenient 64-bit size.
*/
static void centry_put_time(struct cache_entry *centry, time_t t)
{
	NTTIME nt = (NTTIME)t;
	centry_put_nttime(centry, nt);
}

/*
  start a centry for output. When finished, call centry_end()
*/
struct cache_entry *centry_start(struct winbindd_domain *domain, NTSTATUS status)
{
	struct cache_entry *centry;

	if (!wcache->tdb)
		return NULL;

	centry = SMB_XMALLOC_P(struct cache_entry);

	centry->len = 8192; /* reasonable default */
	centry->data = SMB_XMALLOC_ARRAY(uint8, centry->len);
	centry->ofs = 0;
	centry->sequence_number = domain->sequence_number;
	centry_put_ntstatus(centry, status);
	centry_put_uint32(centry, centry->sequence_number);
	return centry;
}

/*
  finish a centry and write it to the tdb
*/
static void centry_end(struct cache_entry *centry, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
static void centry_end(struct cache_entry *centry, const char *format, ...)
{
	va_list ap;
	char *kstr;
	TDB_DATA key, data;

	if (!winbindd_use_cache()) {
		return;
	}

	va_start(ap, format);
	smb_xvasprintf(&kstr, format, ap);
	va_end(ap);

	key = string_tdb_data(kstr);
	data.dptr = centry->data;
	data.dsize = centry->ofs;

	tdb_store(wcache->tdb, key, data, TDB_REPLACE);
	free(kstr);
}

static void wcache_save_name_to_sid(struct winbindd_domain *domain, 
				    NTSTATUS status, const char *domain_name,
				    const char *name, const DOM_SID *sid, 
				    enum lsa_SidType type)
{
	struct cache_entry *centry;
	fstring uname;

	centry = centry_start(domain, status);
	if (!centry)
		return;
	centry_put_uint32(centry, type);
	centry_put_sid(centry, sid);
	fstrcpy(uname, name);
	strupper_m(uname);
	centry_end(centry, "NS/%s/%s", domain_name, uname);
	DEBUG(10,("wcache_save_name_to_sid: %s\\%s -> %s (%s)\n", domain_name,
		  uname, sid_string_dbg(sid), nt_errstr(status)));
	centry_free(centry);
}

static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS status, 
				    const DOM_SID *sid, const char *domain_name, const char *name, enum lsa_SidType type)
{
	struct cache_entry *centry;
	fstring sid_string;

	centry = centry_start(domain, status);
	if (!centry)
		return;

	if (NT_STATUS_IS_OK(status)) {
		centry_put_uint32(centry, type);
		centry_put_string(centry, domain_name);
		centry_put_string(centry, name);
	}

	centry_end(centry, "SN/%s", sid_to_fstring(sid_string, sid));
	DEBUG(10,("wcache_save_sid_to_name: %s -> %s (%s)\n", sid_string, 
		  name, nt_errstr(status)));
	centry_free(centry);
}


static void wcache_save_user(struct winbindd_domain *domain, NTSTATUS status,
			     struct wbint_userinfo *info)
{
	struct cache_entry *centry;
	fstring sid_string;

	if (is_null_sid(&info->user_sid)) {
		return;
	}

	centry = centry_start(domain, status);
	if (!centry)
		return;
	centry_put_string(centry, info->acct_name);
	centry_put_string(centry, info->full_name);
	centry_put_string(centry, info->homedir);
	centry_put_string(centry, info->shell);
	centry_put_uint32(centry, info->primary_gid);
	centry_put_sid(centry, &info->user_sid);
	centry_put_sid(centry, &info->group_sid);
	centry_end(centry, "U/%s", sid_to_fstring(sid_string,
						  &info->user_sid));
	DEBUG(10,("wcache_save_user: %s (acct_name %s)\n", sid_string, info->acct_name));
	centry_free(centry);
}

static void wcache_save_lockout_policy(struct winbindd_domain *domain,
				       NTSTATUS status,
				       struct samr_DomInfo12 *lockout_policy)
{
	struct cache_entry *centry;

	centry = centry_start(domain, status);
	if (!centry)
		return;

	centry_put_nttime(centry, lockout_policy->lockout_duration);
	centry_put_nttime(centry, lockout_policy->lockout_window);
	centry_put_uint16(centry, lockout_policy->lockout_threshold);

	centry_end(centry, "LOC_POL/%s", domain->name);

	DEBUG(10,("wcache_save_lockout_policy: %s\n", domain->name));

	centry_free(centry);
}



static void wcache_save_password_policy(struct winbindd_domain *domain,
					NTSTATUS status,
					struct samr_DomInfo1 *policy)
{
	struct cache_entry *centry;

	centry = centry_start(domain, status);
	if (!centry)
		return;

	centry_put_uint16(centry, policy->min_password_length);
	centry_put_uint16(centry, policy->password_history_length);
	centry_put_uint32(centry, policy->password_properties);
	centry_put_nttime(centry, policy->max_password_age);
	centry_put_nttime(centry, policy->min_password_age);

	centry_end(centry, "PWD_POL/%s", domain->name);

	DEBUG(10,("wcache_save_password_policy: %s\n", domain->name));

	centry_free(centry);
}

/***************************************************************************
 ***************************************************************************/

static void wcache_save_username_alias(struct winbindd_domain *domain,
				       NTSTATUS status,
				       const char *name, const char *alias)
{
	struct cache_entry *centry;
	fstring uname;

	if ( (centry = centry_start(domain, status)) == NULL )
		return;

	centry_put_string( centry, alias );

	fstrcpy(uname, name);
	strupper_m(uname);
	centry_end(centry, "NSS/NA/%s", uname);

	DEBUG(10,("wcache_save_username_alias: %s -> %s\n", name, alias ));

	centry_free(centry);
}

static void wcache_save_alias_username(struct winbindd_domain *domain,
				       NTSTATUS status,
				       const char *alias, const char *name)
{
	struct cache_entry *centry;
	fstring uname;

	if ( (centry = centry_start(domain, status)) == NULL )
		return;

	centry_put_string( centry, name );

	fstrcpy(uname, alias);
	strupper_m(uname);
	centry_end(centry, "NSS/AN/%s", uname);

	DEBUG(10,("wcache_save_alias_username: %s -> %s\n", alias, name ));

	centry_free(centry);
}

/***************************************************************************
 ***************************************************************************/

NTSTATUS resolve_username_to_alias( TALLOC_CTX *mem_ctx,
				    struct winbindd_domain *domain,
				    const char *name, char **alias )
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	char *upper_name;

	if ( domain->internal )
		return NT_STATUS_NOT_SUPPORTED;

	if (!cache->tdb)
		goto do_query;

	if ( (upper_name = SMB_STRDUP(name)) == NULL )
		return NT_STATUS_NO_MEMORY;
	strupper_m(upper_name);

	centry = wcache_fetch(cache, domain, "NSS/NA/%s", upper_name);

	SAFE_FREE( upper_name );

	if (!centry)
		goto do_query;

	status = centry->status;

	if (!NT_STATUS_IS_OK(status)) {
		centry_free(centry);
		return status;
	}

	*alias = centry_string( centry, mem_ctx );

	centry_free(centry);

	DEBUG(10,("resolve_username_to_alias: [Cached] - mapped %s to %s\n",
		  name, *alias ? *alias : "(none)"));

	return (*alias) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;

do_query:

	/* If its not in cache and we are offline, then fail */

	if ( get_global_winbindd_state_offline() || !domain->online ) {
		DEBUG(8,("resolve_username_to_alias: rejecting query "
			 "in offline mode\n"));
		return NT_STATUS_NOT_FOUND;
	}

	status = nss_map_to_alias( mem_ctx, domain->name, name, alias );

	if ( NT_STATUS_IS_OK( status ) ) {
		wcache_save_username_alias(domain, status, name, *alias);
	}

	if ( NT_STATUS_EQUAL( status, NT_STATUS_NONE_MAPPED ) ) {
		wcache_save_username_alias(domain, status, name, "(NULL)");
	}

	DEBUG(5,("resolve_username_to_alias: backend query returned %s\n",
		 nt_errstr(status)));

	if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
		set_domain_offline( domain );
	}

	return status;
}

/***************************************************************************
 ***************************************************************************/

NTSTATUS resolve_alias_to_username( TALLOC_CTX *mem_ctx,
				    struct winbindd_domain *domain,
				    const char *alias, char **name )
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	char *upper_name;

	if ( domain->internal )
		return  NT_STATUS_NOT_SUPPORTED;

	if (!cache->tdb)
		goto do_query;

	if ( (upper_name = SMB_STRDUP(alias)) == NULL )
		return NT_STATUS_NO_MEMORY;
	strupper_m(upper_name);

	centry = wcache_fetch(cache, domain, "NSS/AN/%s", upper_name);

	SAFE_FREE( upper_name );

	if (!centry)
		goto do_query;

	status = centry->status;

	if (!NT_STATUS_IS_OK(status)) {
		centry_free(centry);
		return status;
	}

	*name = centry_string( centry, mem_ctx );

	centry_free(centry);

	DEBUG(10,("resolve_alias_to_username: [Cached] - mapped %s to %s\n",
		  alias, *name ? *name : "(none)"));

	return (*name) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;

do_query:

	/* If its not in cache and we are offline, then fail */

	if ( get_global_winbindd_state_offline() || !domain->online ) {
		DEBUG(8,("resolve_alias_to_username: rejecting query "
			 "in offline mode\n"));
		return NT_STATUS_NOT_FOUND;
	}

	/* an alias cannot contain a domain prefix or '@' */

	if (strchr(alias, '\\') || strchr(alias, '@')) {
		DEBUG(10,("resolve_alias_to_username: skipping fully "
			  "qualified name %s\n", alias));
		return NT_STATUS_OBJECT_NAME_INVALID;
	}

	status = nss_map_from_alias( mem_ctx, domain->name, alias, name );

	if ( NT_STATUS_IS_OK( status ) ) {
		wcache_save_alias_username( domain, status, alias, *name );
	}

	if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
		wcache_save_alias_username(domain, status, alias, "(NULL)");
	}

	DEBUG(5,("resolve_alias_to_username: backend query returned %s\n",
		 nt_errstr(status)));

	if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
		set_domain_offline( domain );
	}

	return status;
}

NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID *sid)
{
	struct winbind_cache *cache = get_cache(domain);
	TDB_DATA data;
	fstring key_str, tmp;
	uint32 rid;

	if (!cache->tdb) {
		return NT_STATUS_INTERNAL_DB_ERROR;
	}

	if (is_null_sid(sid)) {
		return NT_STATUS_INVALID_SID;
	}

	if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
		return NT_STATUS_INVALID_SID;
	}

	fstr_sprintf(key_str, "CRED/%s", sid_to_fstring(tmp, sid));

	data = tdb_fetch(cache->tdb, string_tdb_data(key_str));
	if (!data.dptr) {
		return NT_STATUS_OBJECT_NAME_NOT_FOUND;
	}

	SAFE_FREE(data.dptr);
	return NT_STATUS_OK;
}

/* Lookup creds for a SID - copes with old (unsalted) creds as well
   as new salted ones. */

NTSTATUS wcache_get_creds(struct winbindd_domain *domain, 
			  TALLOC_CTX *mem_ctx, 
			  const DOM_SID *sid,
			  const uint8 **cached_nt_pass,
			  const uint8 **cached_salt)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	time_t t;
	uint32 rid;
	fstring tmp;

	if (!cache->tdb) {
		return NT_STATUS_INTERNAL_DB_ERROR;
	}

	if (is_null_sid(sid)) {
		return NT_STATUS_INVALID_SID;
	}

	if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
		return NT_STATUS_INVALID_SID;
	}

	/* Try and get a salted cred first. If we can't
	   fall back to an unsalted cred. */

	centry = wcache_fetch(cache, domain, "CRED/%s",
			      sid_to_fstring(tmp, sid));
	if (!centry) {
		DEBUG(10,("wcache_get_creds: entry for [CRED/%s] not found\n", 
			  sid_string_dbg(sid)));
		return NT_STATUS_OBJECT_NAME_NOT_FOUND;
	}

	t = centry_time(centry);

	/* In the salted case this isn't actually the nt_hash itself,
	   but the MD5 of the salt + nt_hash. Let the caller
	   sort this out. It can tell as we only return the cached_salt
	   if we are returning a salted cred. */

	*cached_nt_pass = (const uint8 *)centry_hash16(centry, mem_ctx);
	if (*cached_nt_pass == NULL) {
		fstring sidstr;

		sid_to_fstring(sidstr, sid);

		/* Bad (old) cred cache. Delete and pretend we
		   don't have it. */
		DEBUG(0,("wcache_get_creds: bad entry for [CRED/%s] - deleting\n", 
				sidstr));
		wcache_delete("CRED/%s", sidstr);
		centry_free(centry);
		return NT_STATUS_OBJECT_NAME_NOT_FOUND;
	}

	/* We only have 17 bytes more data in the salted cred case. */
	if (centry->len - centry->ofs == 17) {
		*cached_salt = (const uint8 *)centry_hash16(centry, mem_ctx);
	} else {
		*cached_salt = NULL;
	}

	dump_data_pw("cached_nt_pass", *cached_nt_pass, NT_HASH_LEN);
	if (*cached_salt) {
		dump_data_pw("cached_salt", *cached_salt, NT_HASH_LEN);
	}

	status = centry->status;

	DEBUG(10,("wcache_get_creds: [Cached] - cached creds for user %s status: %s\n",
		  sid_string_dbg(sid), nt_errstr(status) ));

	centry_free(centry);
	return status;
}

/* Store creds for a SID - only writes out new salted ones. */

NTSTATUS wcache_save_creds(struct winbindd_domain *domain, 
			   TALLOC_CTX *mem_ctx, 
			   const DOM_SID *sid, 
			   const uint8 nt_pass[NT_HASH_LEN])
{
	struct cache_entry *centry;
	fstring sid_string;
	uint32 rid;
	uint8 cred_salt[NT_HASH_LEN];
	uint8 salted_hash[NT_HASH_LEN];

	if (is_null_sid(sid)) {
		return NT_STATUS_INVALID_SID;
	}

	if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
		return NT_STATUS_INVALID_SID;
	}

	centry = centry_start(domain, NT_STATUS_OK);
	if (!centry) {
		return NT_STATUS_INTERNAL_DB_ERROR;
	}

	dump_data_pw("nt_pass", nt_pass, NT_HASH_LEN);

	centry_put_time(centry, time(NULL));

	/* Create a salt and then salt the hash. */
	generate_random_buffer(cred_salt, NT_HASH_LEN);
	E_md5hash(cred_salt, nt_pass, salted_hash);

	centry_put_hash16(centry, salted_hash);
	centry_put_hash16(centry, cred_salt);
	centry_end(centry, "CRED/%s", sid_to_fstring(sid_string, sid));

	DEBUG(10,("wcache_save_creds: %s\n", sid_string));

	centry_free(centry);

	return NT_STATUS_OK;
}


/* Query display info. This is the basic user list fn */
static NTSTATUS query_user_list(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				uint32 *num_entries, 
				struct wbint_userinfo **info)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i, retry;
	bool old_status = domain->online;

	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "UL/%s", domain->name);
	if (!centry)
		goto do_query;

do_fetch_cache:
	*num_entries = centry_uint32(centry);

	if (*num_entries == 0)
		goto do_cached;

	(*info) = TALLOC_ARRAY(mem_ctx, struct wbint_userinfo, *num_entries);
	if (! (*info)) {
		smb_panic_fn("query_user_list out of memory");
	}
	for (i=0; i<(*num_entries); i++) {
		(*info)[i].acct_name = centry_string(centry, mem_ctx);
		(*info)[i].full_name = centry_string(centry, mem_ctx);
		(*info)[i].homedir = centry_string(centry, mem_ctx);
		(*info)[i].shell = centry_string(centry, mem_ctx);
		centry_sid(centry, &(*info)[i].user_sid);
		centry_sid(centry, &(*info)[i].group_sid);
	}

do_cached:	
	status = centry->status;

	DEBUG(10,("query_user_list: [Cached] - cached list for domain %s status: %s\n",
		domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;

do_query:
	*num_entries = 0;
	*info = NULL;

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	/* Put the query_user_list() in a retry loop.  There appears to be
	 * some bug either with Windows 2000 or Samba's handling of large
	 * rpc replies.  This manifests itself as sudden disconnection
	 * at a random point in the enumeration of a large (60k) user list.
	 * The retry loop simply tries the operation again. )-:  It's not
	 * pretty but an acceptable workaround until we work out what the
	 * real problem is. */

	retry = 0;
	do {

		DEBUG(10,("query_user_list: [Cached] - doing backend query for list for domain %s\n",
			domain->name ));

		status = domain->backend->query_user_list(domain, mem_ctx, num_entries, info);
		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(3, ("query_user_list: returned 0x%08x, "
				  "retrying\n", NT_STATUS_V(status)));
		}
		if (NT_STATUS_EQUAL(status, NT_STATUS_UNSUCCESSFUL)) {
			DEBUG(3, ("query_user_list: flushing "
				  "connection cache\n"));
			invalidate_cm_connection(&domain->conn);
		}
		if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		    NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
			if (!domain->internal && old_status) {
				set_domain_offline(domain);
			}
			/* store partial response. */
			if (*num_entries > 0) {
				/*
				 * humm, what about the status used for cache?
				 * Should it be NT_STATUS_OK?
				 */
				break;
			}
			/*
			 * domain is offline now, and there is no user entries,
			 * try to fetch from cache again.
			 */
			if (cache->tdb && !domain->online && !domain->internal && old_status) {
				centry = wcache_fetch(cache, domain, "UL/%s", domain->name);
				/* partial response... */
				if (!centry) {
					goto skip_save;
				} else {
					goto do_fetch_cache;
				}
			} else {
				goto skip_save;
			}
		}

	} while (NT_STATUS_V(status) == NT_STATUS_V(NT_STATUS_UNSUCCESSFUL) && 
		 (retry++ < 5));

	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;
	centry_put_uint32(centry, *num_entries);
	for (i=0; i<(*num_entries); i++) {
		centry_put_string(centry, (*info)[i].acct_name);
		centry_put_string(centry, (*info)[i].full_name);
		centry_put_string(centry, (*info)[i].homedir);
		centry_put_string(centry, (*info)[i].shell);
		centry_put_sid(centry, &(*info)[i].user_sid);
		centry_put_sid(centry, &(*info)[i].group_sid);
		if (domain->backend && domain->backend->consistent) {
			/* when the backend is consistent we can pre-prime some mappings */
			wcache_save_name_to_sid(domain, NT_STATUS_OK, 
						domain->name,
						(*info)[i].acct_name, 
						&(*info)[i].user_sid,
						SID_NAME_USER);
			wcache_save_sid_to_name(domain, NT_STATUS_OK, 
						&(*info)[i].user_sid,
						domain->name,
						(*info)[i].acct_name, 
						SID_NAME_USER);
			wcache_save_user(domain, NT_STATUS_OK, &(*info)[i]);
		}
	}	
	centry_end(centry, "UL/%s", domain->name);
	centry_free(centry);

skip_save:
	return status;
}

/* list all domain groups */
static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				uint32 *num_entries, 
				struct acct_info **info)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i;
	bool old_status;

	old_status = domain->online;
	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "GL/%s/domain", domain->name);
	if (!centry)
		goto do_query;

do_fetch_cache:
	*num_entries = centry_uint32(centry);

	if (*num_entries == 0)
		goto do_cached;

	(*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
	if (! (*info)) {
		smb_panic_fn("enum_dom_groups out of memory");
	}
	for (i=0; i<(*num_entries); i++) {
		fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
		fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
		(*info)[i].rid = centry_uint32(centry);
	}

do_cached:	
	status = centry->status;

	DEBUG(10,("enum_dom_groups: [Cached] - cached list for domain %s status: %s\n",
		domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;

do_query:
	*num_entries = 0;
	*info = NULL;

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("enum_dom_groups: [Cached] - doing backend query for list for domain %s\n",
		domain->name ));

	status = domain->backend->enum_dom_groups(domain, mem_ctx, num_entries, info);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
	    NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (cache->tdb &&
			!domain->online &&
			!domain->internal &&
			old_status) {
			centry = wcache_fetch(cache, domain, "GL/%s/domain", domain->name);
			if (centry) {
				goto do_fetch_cache;
			}
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;
	centry_put_uint32(centry, *num_entries);
	for (i=0; i<(*num_entries); i++) {
		centry_put_string(centry, (*info)[i].acct_name);
		centry_put_string(centry, (*info)[i].acct_desc);
		centry_put_uint32(centry, (*info)[i].rid);
	}	
	centry_end(centry, "GL/%s/domain", domain->name);
	centry_free(centry);

skip_save:
	return status;
}

/* list all domain groups */
static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				uint32 *num_entries, 
				struct acct_info **info)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i;
	bool old_status;

	old_status = domain->online;
	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "GL/%s/local", domain->name);
	if (!centry)
		goto do_query;

do_fetch_cache:
	*num_entries = centry_uint32(centry);

	if (*num_entries == 0)
		goto do_cached;

	(*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
	if (! (*info)) {
		smb_panic_fn("enum_dom_groups out of memory");
	}
	for (i=0; i<(*num_entries); i++) {
		fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
		fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
		(*info)[i].rid = centry_uint32(centry);
	}

do_cached:	

	/* If we are returning cached data and the domain controller
	   is down then we don't know whether the data is up to date
	   or not.  Return NT_STATUS_MORE_PROCESSING_REQUIRED to
	   indicate this. */

	if (wcache_server_down(domain)) {
		DEBUG(10, ("enum_local_groups: returning cached user list and server was down\n"));
		status = NT_STATUS_MORE_PROCESSING_REQUIRED;
	} else
		status = centry->status;

	DEBUG(10,("enum_local_groups: [Cached] - cached list for domain %s status: %s\n",
		domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;

do_query:
	*num_entries = 0;
	*info = NULL;

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("enum_local_groups: [Cached] - doing backend query for list for domain %s\n",
		domain->name ));

	status = domain->backend->enum_local_groups(domain, mem_ctx, num_entries, info);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (cache->tdb &&
			!domain->internal &&
			!domain->online &&
			old_status) {
			centry = wcache_fetch(cache, domain, "GL/%s/local", domain->name);
			if (centry) {
				goto do_fetch_cache;
			}
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;
	centry_put_uint32(centry, *num_entries);
	for (i=0; i<(*num_entries); i++) {
		centry_put_string(centry, (*info)[i].acct_name);
		centry_put_string(centry, (*info)[i].acct_desc);
		centry_put_uint32(centry, (*info)[i].rid);
	}
	centry_end(centry, "GL/%s/local", domain->name);
	centry_free(centry);

skip_save:
	return status;
}

NTSTATUS wcache_name_to_sid(struct winbindd_domain *domain,
			    const char *domain_name,
			    const char *name,
			    struct dom_sid *sid,
			    enum lsa_SidType *type)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry;
	NTSTATUS status;
	char *uname;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	uname = talloc_strdup_upper(talloc_tos(), name);
	if (uname == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	centry = wcache_fetch(cache, domain, "NS/%s/%s", domain_name, uname);
	TALLOC_FREE(uname);
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	status = centry->status;
	if (NT_STATUS_IS_OK(status)) {
		*type = (enum lsa_SidType)centry_uint32(centry);
		centry_sid(centry, sid);
	}

	DEBUG(10,("name_to_sid: [Cached] - cached name for domain %s status: "
		  "%s\n", domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;
}

/* convert a single name to a sid in a domain */
static NTSTATUS name_to_sid(struct winbindd_domain *domain,
			    TALLOC_CTX *mem_ctx,
			    const char *domain_name,
			    const char *name,
			    uint32_t flags,
			    DOM_SID *sid,
			    enum lsa_SidType *type)
{
	NTSTATUS status;
	bool old_status;

	old_status = domain->online;

	status = wcache_name_to_sid(domain, domain_name, name, sid, type);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	ZERO_STRUCTP(sid);

	/* If the seq number check indicated that there is a problem
	 * with this DC, then return that status... except for
	 * access_denied.  This is special because the dc may be in
	 * "restrict anonymous = 1" mode, in which case it will deny
	 * most unauthenticated operations, but *will* allow the LSA
	 * name-to-sid that we try as a fallback. */

	if (!(NT_STATUS_IS_OK(domain->last_status)
	      || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
		return domain->last_status;

	DEBUG(10,("name_to_sid: [Cached] - doing backend query for name for domain %s\n",
		domain->name ));

	status = domain->backend->name_to_sid(domain, mem_ctx, domain_name,
					      name, flags, sid, type);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_name_to_sid(domain, domain_name, name, sid, type);
			return cache_status;
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);

	if (domain->online &&
	    (NT_STATUS_IS_OK(status) || NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED))) {
		wcache_save_name_to_sid(domain, status, domain_name, name, sid, *type);

		/* Only save the reverse mapping if this was not a UPN */
		if (!strchr(name, '@')) {
			strupper_m(CONST_DISCARD(char *,domain_name));
			strlower_m(CONST_DISCARD(char *,name));
			wcache_save_sid_to_name(domain, status, sid, domain_name, name, *type);
		}
	}

	return status;
}

NTSTATUS wcache_sid_to_name(struct winbindd_domain *domain,
			    const struct dom_sid *sid,
			    TALLOC_CTX *mem_ctx,
			    char **domain_name,
			    char **name,
			    enum lsa_SidType *type)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry;
	char *sid_string;
	NTSTATUS status;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	sid_string = sid_string_tos(sid);
	if (sid_string == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	centry = wcache_fetch(cache, domain, "SN/%s", sid_string);
	TALLOC_FREE(sid_string);
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	if (NT_STATUS_IS_OK(centry->status)) {
		*type = (enum lsa_SidType)centry_uint32(centry);
		*domain_name = centry_string(centry, mem_ctx);
		*name = centry_string(centry, mem_ctx);
	}

	status = centry->status;
	centry_free(centry);

	DEBUG(10,("sid_to_name: [Cached] - cached name for domain %s status: "
		  "%s\n", domain->name, nt_errstr(status) ));

	return status;
}

/* convert a sid to a user or group name. The sid is guaranteed to be in the domain
   given */
static NTSTATUS sid_to_name(struct winbindd_domain *domain,
			    TALLOC_CTX *mem_ctx,
			    const DOM_SID *sid,
			    char **domain_name,
			    char **name,
			    enum lsa_SidType *type)
{
	NTSTATUS status;
	bool old_status;

	old_status = domain->online;
	status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
				    type);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	*name = NULL;
	*domain_name = NULL;

	/* If the seq number check indicated that there is a problem
	 * with this DC, then return that status... except for
	 * access_denied.  This is special because the dc may be in
	 * "restrict anonymous = 1" mode, in which case it will deny
	 * most unauthenticated operations, but *will* allow the LSA
	 * sid-to-name that we try as a fallback. */

	if (!(NT_STATUS_IS_OK(domain->last_status)
	      || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
		return domain->last_status;

	DEBUG(10,("sid_to_name: [Cached] - doing backend query for name for domain %s\n",
		domain->name ));

	status = domain->backend->sid_to_name(domain, mem_ctx, sid, domain_name, name, type);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_sid_to_name(domain, sid, mem_ctx,
							domain_name, name, type);
			return cache_status;
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	wcache_save_sid_to_name(domain, status, sid, *domain_name, *name, *type);

	/* We can't save the name to sid mapping here, as with sid history a
	 * later name2sid would give the wrong sid. */

	return status;
}

static NTSTATUS rids_to_names(struct winbindd_domain *domain,
			      TALLOC_CTX *mem_ctx,
			      const DOM_SID *domain_sid,
			      uint32 *rids,
			      size_t num_rids,
			      char **domain_name,
			      char ***names,
			      enum lsa_SidType **types)
{
	struct winbind_cache *cache = get_cache(domain);
	size_t i;
	NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
	bool have_mapped;
	bool have_unmapped;
	bool old_status;

	old_status = domain->online;
	*domain_name = NULL;
	*names = NULL;
	*types = NULL;

	if (!cache->tdb) {
		goto do_query;
	}

	if (num_rids == 0) {
		return NT_STATUS_OK;
	}

	*names = TALLOC_ARRAY(mem_ctx, char *, num_rids);
	*types = TALLOC_ARRAY(mem_ctx, enum lsa_SidType, num_rids);

	if ((*names == NULL) || (*types == NULL)) {
		result = NT_STATUS_NO_MEMORY;
		goto error;
	}

	have_mapped = have_unmapped = false;

	for (i=0; i<num_rids; i++) {
		DOM_SID sid;
		struct cache_entry *centry;
		fstring tmp;

		if (!sid_compose(&sid, domain_sid, rids[i])) {
			result = NT_STATUS_INTERNAL_ERROR;
			goto error;
		}

		centry = wcache_fetch(cache, domain, "SN/%s",
				      sid_to_fstring(tmp, &sid));
		if (!centry) {
			goto do_query;
		}

		(*types)[i] = SID_NAME_UNKNOWN;
		(*names)[i] = talloc_strdup(*names, "");

		if (NT_STATUS_IS_OK(centry->status)) {
			char *dom;
			have_mapped = true;
			(*types)[i] = (enum lsa_SidType)centry_uint32(centry);

			dom = centry_string(centry, mem_ctx);
			if (*domain_name == NULL) {
				*domain_name = dom;
			} else {
				talloc_free(dom);
			}

			(*names)[i] = centry_string(centry, *names);

		} else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)) {
			have_unmapped = true;

		} else {
			/* something's definitely wrong */
			result = centry->status;
			goto error;
		}

		centry_free(centry);
	}

	if (!have_mapped) {
		return NT_STATUS_NONE_MAPPED;
	}
	if (!have_unmapped) {
		return NT_STATUS_OK;
	}
	return STATUS_SOME_UNMAPPED;

 do_query:

	TALLOC_FREE(*names);
	TALLOC_FREE(*types);

	result = domain->backend->rids_to_names(domain, mem_ctx, domain_sid,
						rids, num_rids, domain_name,
						names, types);

	if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (cache->tdb &&
			!domain->internal &&
			!domain->online &&
			old_status) {
			have_mapped = have_unmapped = false;

			for (i=0; i<num_rids; i++) {
				DOM_SID sid;
				struct cache_entry *centry;
				fstring tmp;

				if (!sid_compose(&sid, domain_sid, rids[i])) {
					result = NT_STATUS_INTERNAL_ERROR;
					goto error;
				}

				centry = wcache_fetch(cache, domain, "SN/%s",
						      sid_to_fstring(tmp, &sid));
				if (!centry) {
					(*types)[i] = SID_NAME_UNKNOWN;
					(*names)[i] = talloc_strdup(*names, "");
					continue;
				}

				(*types)[i] = SID_NAME_UNKNOWN;
				(*names)[i] = talloc_strdup(*names, "");

				if (NT_STATUS_IS_OK(centry->status)) {
					char *dom;
					have_mapped = true;
					(*types)[i] = (enum lsa_SidType)centry_uint32(centry);

					dom = centry_string(centry, mem_ctx);
					if (*domain_name == NULL) {
						*domain_name = dom;
					} else {
						talloc_free(dom);
					}

					(*names)[i] = centry_string(centry, *names);

				} else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)) {
					have_unmapped = true;

				} else {
					/* something's definitely wrong */
					result = centry->status;
					goto error;
				}

				centry_free(centry);
			}

			if (!have_mapped) {
				return NT_STATUS_NONE_MAPPED;
			}
			if (!have_unmapped) {
				return NT_STATUS_OK;
			}
			return STATUS_SOME_UNMAPPED;
		}
	}
	/*
	  None of the queried rids has been found so save all negative entries
	*/
	if (NT_STATUS_EQUAL(result, NT_STATUS_NONE_MAPPED)) {
		for (i = 0; i < num_rids; i++) {
			DOM_SID sid;
			const char *name = "";
			const enum lsa_SidType type = SID_NAME_UNKNOWN;
			NTSTATUS status = NT_STATUS_NONE_MAPPED;

			if (!sid_compose(&sid, domain_sid, rids[i])) {
				return NT_STATUS_INTERNAL_ERROR;
			}

			wcache_save_sid_to_name(domain, status, &sid, *domain_name,
						name, type);
		}

		return result;
	}

	/*
	  Some or all of the queried rids have been found.
	*/
	if (!NT_STATUS_IS_OK(result) &&
	    !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
		return result;
	}

	refresh_sequence_number(domain, false);

	for (i=0; i<num_rids; i++) {
		DOM_SID sid;
		NTSTATUS status;

		if (!sid_compose(&sid, domain_sid, rids[i])) {
			result = NT_STATUS_INTERNAL_ERROR;
			goto error;
		}

		status = (*types)[i] == SID_NAME_UNKNOWN ?
			NT_STATUS_NONE_MAPPED : NT_STATUS_OK;

		wcache_save_sid_to_name(domain, status, &sid, *domain_name,
					(*names)[i], (*types)[i]);
	}

	return result;

 error:
	TALLOC_FREE(*names);
	TALLOC_FREE(*types);
	return result;
}

NTSTATUS wcache_query_user(struct winbindd_domain *domain,
			   TALLOC_CTX *mem_ctx,
			   const struct dom_sid *user_sid,
			   struct wbint_userinfo *info)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	char *sid_string;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	sid_string = sid_string_tos(user_sid);
	if (sid_string == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	centry = wcache_fetch(cache, domain, "U/%s", sid_string);
	TALLOC_FREE(sid_string);
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	/*
	 * If we have an access denied cache entry and a cached info3
	 * in the samlogon cache then do a query.  This will force the
	 * rpc back end to return the info3 data.
	 */

	if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED) &&
	    netsamlogon_cache_have(user_sid)) {
		DEBUG(10, ("query_user: cached access denied and have cached "
			   "info3\n"));
		domain->last_status = NT_STATUS_OK;
		centry_free(centry);
		return NT_STATUS_NOT_FOUND;
	}

	/* if status is not ok then this is a negative hit
	   and the rest of the data doesn't matter */
	status = centry->status;
	if (NT_STATUS_IS_OK(status)) {
		info->acct_name = centry_string(centry, mem_ctx);
		info->full_name = centry_string(centry, mem_ctx);
		info->homedir = centry_string(centry, mem_ctx);
		info->shell = centry_string(centry, mem_ctx);
		info->primary_gid = centry_uint32(centry);
		centry_sid(centry, &info->user_sid);
		centry_sid(centry, &info->group_sid);
	}

	DEBUG(10,("query_user: [Cached] - cached info for domain %s status: "
		  "%s\n", domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;
}

/* Lookup user information from a rid */
static NTSTATUS query_user(struct winbindd_domain *domain,
			   TALLOC_CTX *mem_ctx,
			   const DOM_SID *user_sid,
			   struct wbint_userinfo *info)
{
	NTSTATUS status;
	bool old_status;

	old_status = domain->online;
	status = wcache_query_user(domain, mem_ctx, user_sid, info);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	ZERO_STRUCTP(info);

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("query_user: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->query_user(domain, mem_ctx, user_sid, info);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_query_user(domain, mem_ctx, user_sid, info);
			return cache_status;
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	wcache_save_user(domain, status, info);

	return status;
}

NTSTATUS wcache_lookup_usergroups(struct winbindd_domain *domain,
				  TALLOC_CTX *mem_ctx,
				  const struct dom_sid *user_sid,
				  uint32_t *pnum_sids,
				  struct dom_sid **psids)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	uint32_t i, num_sids;
	struct dom_sid *sids;
	fstring sid_string;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	centry = wcache_fetch(cache, domain, "UG/%s",
			      sid_to_fstring(sid_string, user_sid));
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	/* If we have an access denied cache entry and a cached info3 in the
           samlogon cache then do a query.  This will force the rpc back end
           to return the info3 data. */

	if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)
	    && netsamlogon_cache_have(user_sid)) {
		DEBUG(10, ("lookup_usergroups: cached access denied and have "
			   "cached info3\n"));
		domain->last_status = NT_STATUS_OK;
		centry_free(centry);
		return NT_STATUS_NOT_FOUND;
	}

	num_sids = centry_uint32(centry);
	sids = talloc_array(mem_ctx, struct dom_sid, num_sids);
	if (sids == NULL) {
		centry_free(centry);
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0; i<num_sids; i++) {
		centry_sid(centry, &sids[i]);
	}

	status = centry->status;

	DEBUG(10,("lookup_usergroups: [Cached] - cached info for domain %s "
		  "status: %s\n", domain->name, nt_errstr(status)));

	centry_free(centry);

	*pnum_sids = num_sids;
	*psids = sids;
	return status;
}

/* Lookup groups a user is a member of. */
static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
				  TALLOC_CTX *mem_ctx,
				  const DOM_SID *user_sid,
				  uint32 *num_groups, DOM_SID **user_gids)
{
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i;
	fstring sid_string;
	bool old_status;

	old_status = domain->online;
	status = wcache_lookup_usergroups(domain, mem_ctx, user_sid,
					  num_groups, user_gids);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	(*num_groups) = 0;
	(*user_gids) = NULL;

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->lookup_usergroups(domain, mem_ctx, user_sid, num_groups, user_gids);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_lookup_usergroups(domain, mem_ctx, user_sid,
							  num_groups, user_gids);
			return cache_status;
		}
	}
	if ( NT_STATUS_EQUAL(status, NT_STATUS_SYNCHRONIZATION_REQUIRED) )
		goto skip_save;

	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;

	centry_put_uint32(centry, *num_groups);
	for (i=0; i<(*num_groups); i++) {
		centry_put_sid(centry, &(*user_gids)[i]);
	}	

	centry_end(centry, "UG/%s", sid_to_fstring(sid_string, user_sid));
	centry_free(centry);

skip_save:
	return status;
}

static char *wcache_make_sidlist(TALLOC_CTX *mem_ctx, uint32_t num_sids,
				 const struct dom_sid *sids)
{
	uint32_t i;
	char *sidlist;

	sidlist = talloc_strdup(mem_ctx, "");
	if (sidlist == NULL) {
		return NULL;
	}
	for (i=0; i<num_sids; i++) {
		fstring tmp;
		sidlist = talloc_asprintf_append_buffer(
			sidlist, "/%s", sid_to_fstring(tmp, &sids[i]));
		if (sidlist == NULL) {
			return NULL;
		}
	}
	return sidlist;
}

NTSTATUS wcache_lookup_useraliases(struct winbindd_domain *domain,
				   TALLOC_CTX *mem_ctx, uint32_t num_sids,
				   const struct dom_sid *sids,
				   uint32_t *pnum_aliases, uint32_t **paliases)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	uint32_t num_aliases;
	uint32_t *aliases;
	NTSTATUS status;
	char *sidlist;
	int i;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	if (num_sids == 0) {
		*pnum_aliases = 0;
		*paliases = NULL;
		return NT_STATUS_OK;
	}

	/* We need to cache indexed by the whole list of SIDs, the aliases
	 * resulting might come from any of the SIDs. */

	sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
	if (sidlist == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	centry = wcache_fetch(cache, domain, "UA%s", sidlist);
	TALLOC_FREE(sidlist);
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	num_aliases = centry_uint32(centry);
	aliases = talloc_array(mem_ctx, uint32_t, num_aliases);
	if (aliases == NULL) {
		centry_free(centry);
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0; i<num_aliases; i++) {
		aliases[i] = centry_uint32(centry);
	}

	status = centry->status;

	DEBUG(10,("lookup_useraliases: [Cached] - cached info for domain: %s "
		  "status %s\n", domain->name, nt_errstr(status)));

	centry_free(centry);

	*pnum_aliases = num_aliases;
	*paliases = aliases;

	return status;
}

static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
				   TALLOC_CTX *mem_ctx,
				   uint32 num_sids, const DOM_SID *sids,
				   uint32 *num_aliases, uint32 **alias_rids)
{
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	char *sidlist;
	int i;
	bool old_status;

	old_status = domain->online;
	status = wcache_lookup_useraliases(domain, mem_ctx, num_sids, sids,
					   num_aliases, alias_rids);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	(*num_aliases) = 0;
	(*alias_rids) = NULL;

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info "
		  "for domain %s\n", domain->name ));

	sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
	if (sidlist == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	status = domain->backend->lookup_useraliases(domain, mem_ctx,
						     num_sids, sids,
						     num_aliases, alias_rids);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_lookup_useraliases(domain, mem_ctx, num_sids,
								 sids, num_aliases, alias_rids);
			return cache_status;
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;
	centry_put_uint32(centry, *num_aliases);
	for (i=0; i<(*num_aliases); i++)
		centry_put_uint32(centry, (*alias_rids)[i]);
	centry_end(centry, "UA%s", sidlist);
	centry_free(centry);

 skip_save:
	return status;
}

NTSTATUS wcache_lookup_groupmem(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				const struct dom_sid *group_sid,
				uint32_t *num_names,
				struct dom_sid **sid_mem, char ***names,
				uint32_t **name_types)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i;
	char *sid_string;

	if (cache->tdb == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	sid_string = sid_string_tos(group_sid);
	if (sid_string == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	centry = wcache_fetch(cache, domain, "GM/%s", sid_string);
	TALLOC_FREE(sid_string);
	if (centry == NULL) {
		return NT_STATUS_NOT_FOUND;
	}

	*sid_mem = NULL;
	*names = NULL;
	*name_types = NULL;

	*num_names = centry_uint32(centry);
	if (*num_names == 0) {
		centry_free(centry);
		return NT_STATUS_OK;
	}

	*sid_mem = talloc_array(mem_ctx, DOM_SID, *num_names);
	*names = talloc_array(mem_ctx, char *, *num_names);
	*name_types = talloc_array(mem_ctx, uint32, *num_names);

	if ((*sid_mem == NULL) || (*names == NULL) || (*name_types == NULL)) {
		TALLOC_FREE(*sid_mem);
		TALLOC_FREE(*names);
		TALLOC_FREE(*name_types);
		centry_free(centry);
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0; i<(*num_names); i++) {
		centry_sid(centry, &(*sid_mem)[i]);
		(*names)[i] = centry_string(centry, mem_ctx);
		(*name_types)[i] = centry_uint32(centry);
	}

	status = centry->status;

	DEBUG(10,("lookup_groupmem: [Cached] - cached info for domain %s "
		  "status: %s\n", domain->name, nt_errstr(status)));

	centry_free(centry);
	return status;
}

static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				const DOM_SID *group_sid,
				enum lsa_SidType type,
				uint32 *num_names,
				DOM_SID **sid_mem, char ***names,
				uint32 **name_types)
{
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	unsigned int i;
	fstring sid_string;
	bool old_status;

	old_status = domain->online;
	status = wcache_lookup_groupmem(domain, mem_ctx, group_sid, num_names,
					sid_mem, names, name_types);
	if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		return status;
	}

	(*num_names) = 0;
	(*sid_mem) = NULL;
	(*names) = NULL;
	(*name_types) = NULL;

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("lookup_groupmem: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->lookup_groupmem(domain, mem_ctx, group_sid,
						  type, num_names,
						  sid_mem, names, name_types);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			NTSTATUS cache_status;
			cache_status = wcache_lookup_groupmem(domain, mem_ctx, group_sid,
							      num_names, sid_mem, names,
							      name_types);
			return cache_status;
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	centry = centry_start(domain, status);
	if (!centry)
		goto skip_save;
	centry_put_uint32(centry, *num_names);
	for (i=0; i<(*num_names); i++) {
		centry_put_sid(centry, &(*sid_mem)[i]);
		centry_put_string(centry, (*names)[i]);
		centry_put_uint32(centry, (*name_types)[i]);
	}	
	centry_end(centry, "GM/%s", sid_to_fstring(sid_string, group_sid));
	centry_free(centry);

skip_save:
	return status;
}

/* find the sequence number for a domain */
static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
{
	refresh_sequence_number(domain, false);

	*seq = domain->sequence_number;

	return NT_STATUS_OK;
}

/* enumerate trusted domains 
 * (we need to have the list of trustdoms in the cache when we go offline) -
 * Guenther */
static NTSTATUS trusted_domains(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				struct netr_DomainTrustList *trusts)
{
 	NTSTATUS status;
	struct winbind_cache *cache;
	struct winbindd_tdc_domain *dom_list = NULL;
	size_t num_domains = 0;
	bool retval = false;
	int i;
	bool old_status;

	old_status = domain->online;
	trusts->count = 0;
	trusts->array = NULL;
	if (domain->online) {
		goto do_query;
	}

	cache = get_cache(domain);
	if (!cache || !cache->tdb) {
		goto do_query;
	}

	retval = wcache_tdc_fetch_list(&dom_list, &num_domains);
	if (!retval || !num_domains || !dom_list) {
		TALLOC_FREE(dom_list);
		goto do_query;
	}

do_fetch_cache:
	trusts->array = TALLOC_ZERO_ARRAY(mem_ctx, struct netr_DomainTrust, num_domains);
	if (!trusts->array) {
		TALLOC_FREE(dom_list);
		return NT_STATUS_NO_MEMORY;
	}

	for (i = 0; i < num_domains; i++) {
		struct netr_DomainTrust *trust;
		struct dom_sid *sid;
		struct winbindd_domain *dom;

		dom = find_domain_from_name_noinit(dom_list[i].domain_name);
		if (dom && dom->internal) {
			continue;
		}

		trust = &trusts->array[trusts->count];
		trust->netbios_name = talloc_strdup(trusts->array, dom_list[i].domain_name);
		trust->dns_name = talloc_strdup(trusts->array, dom_list[i].dns_name);
		sid = talloc(trusts->array, struct dom_sid);
		if (!trust->netbios_name || !trust->dns_name ||
			!sid) {
			TALLOC_FREE(dom_list);
			TALLOC_FREE(trusts->array);
			return NT_STATUS_NO_MEMORY;
		}

		trust->trust_flags = dom_list[i].trust_flags;
		trust->trust_attributes = dom_list[i].trust_attribs;
		trust->trust_type = dom_list[i].trust_type;
		sid_copy(sid, &dom_list[i].sid);
		trust->sid = sid;
		trusts->count++;
	}

	TALLOC_FREE(dom_list);
	return NT_STATUS_OK;

do_query:
	/* Return status value returned by seq number check */

 	if (!NT_STATUS_IS_OK(domain->last_status))
 		return domain->last_status;

	DEBUG(10,("trusted_domains: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->trusted_domains(domain, mem_ctx, trusts);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (!domain->internal &&
			!domain->online &&
			old_status) {
			retval = wcache_tdc_fetch_list(&dom_list, &num_domains);
			if (retval && num_domains && dom_list) {
				TALLOC_FREE(trusts->array);
				trusts->count = 0;
				goto do_fetch_cache;
			}
		}
	}
	/* no trusts gives NT_STATUS_NO_MORE_ENTRIES resetting to NT_STATUS_OK
	 * so that the generic centry handling still applies correctly -
	 * Guenther*/

	if (!NT_STATUS_IS_ERR(status)) {
		status = NT_STATUS_OK;
	}
 	return status;
}	

/* get lockout policy */
static NTSTATUS lockout_policy(struct winbindd_domain *domain,
 			       TALLOC_CTX *mem_ctx,
			       struct samr_DomInfo12 *policy)
{
 	struct winbind_cache *cache = get_cache(domain);
 	struct cache_entry *centry = NULL;
 	NTSTATUS status;
	bool old_status;

	old_status = domain->online;
	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "LOC_POL/%s", domain->name);

	if (!centry)
 		goto do_query;

do_fetch_cache:
	policy->lockout_duration = centry_nttime(centry);
	policy->lockout_window = centry_nttime(centry);
	policy->lockout_threshold = centry_uint16(centry);

 	status = centry->status;

	DEBUG(10,("lockout_policy: [Cached] - cached info for domain %s status: %s\n",
		domain->name, nt_errstr(status) ));

 	centry_free(centry);
 	return status;

do_query:
	ZERO_STRUCTP(policy);

	/* Return status value returned by seq number check */

 	if (!NT_STATUS_IS_OK(domain->last_status))
 		return domain->last_status;

	DEBUG(10,("lockout_policy: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->lockout_policy(domain, mem_ctx, policy);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (cache->tdb &&
			!domain->internal &&
			!domain->online &&
			old_status) {
			centry = wcache_fetch(cache, domain, "LOC_POL/%s", domain->name);
			if (centry) {
				goto do_fetch_cache;
			}
		}
	}
	/* and save it */
 	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	wcache_save_lockout_policy(domain, status, policy);

 	return status;
}

/* get password policy */
static NTSTATUS password_policy(struct winbindd_domain *domain,
				TALLOC_CTX *mem_ctx,
				struct samr_DomInfo1 *policy)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS status;
	bool old_status;

	old_status = domain->online;
	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "PWD_POL/%s", domain->name);

	if (!centry)
		goto do_query;

do_fetch_cache:
	policy->min_password_length = centry_uint16(centry);
	policy->password_history_length = centry_uint16(centry);
	policy->password_properties = centry_uint32(centry);
	policy->max_password_age = centry_nttime(centry);
	policy->min_password_age = centry_nttime(centry);

	status = centry->status;

	DEBUG(10,("lockout_policy: [Cached] - cached info for domain %s status: %s\n",
		domain->name, nt_errstr(status) ));

	centry_free(centry);
	return status;

do_query:
	ZERO_STRUCTP(policy);

	/* Return status value returned by seq number check */

	if (!NT_STATUS_IS_OK(domain->last_status))
		return domain->last_status;

	DEBUG(10,("password_policy: [Cached] - doing backend query for info for domain %s\n",
		domain->name ));

	status = domain->backend->password_policy(domain, mem_ctx, policy);

	if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
		NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
		if (!domain->internal && old_status) {
			set_domain_offline(domain);
		}
		if (cache->tdb &&
			!domain->internal &&
			!domain->online &&
			old_status) {
			centry = wcache_fetch(cache, domain, "PWD_POL/%s", domain->name);
			if (centry) {
				goto do_fetch_cache;
			}
		}
	}
	/* and save it */
	refresh_sequence_number(domain, false);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	wcache_save_password_policy(domain, status, policy);

	return status;
}


/* Invalidate cached user and group lists coherently */

static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
		       void *state)
{
	if (strncmp((const char *)kbuf.dptr, "UL/", 3) == 0 ||
	    strncmp((const char *)kbuf.dptr, "GL/", 3) == 0)
		tdb_delete(the_tdb, kbuf);

	return 0;
}

/* Invalidate the getpwnam and getgroups entries for a winbindd domain */

void wcache_invalidate_samlogon(struct winbindd_domain *domain, 
				struct netr_SamInfo3 *info3)
{
        DOM_SID sid;
        fstring key_str, sid_string;
	struct winbind_cache *cache;

	/* dont clear cached U/SID and UG/SID entries when we want to logon
	 * offline - gd */

	if (lp_winbind_offline_logon()) {
		return;
	}

	if (!domain)
		return;

	cache = get_cache(domain);

        if (!cache->tdb) {
                return;
        }

	sid_copy(&sid, info3->base.domain_sid);
	sid_append_rid(&sid, info3->base.rid);

	/* Clear U/SID cache entry */
	fstr_sprintf(key_str, "U/%s", sid_to_fstring(sid_string, &sid));
	DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
	tdb_delete(cache->tdb, string_tdb_data(key_str));

	/* Clear UG/SID cache entry */
	fstr_sprintf(key_str, "UG/%s", sid_to_fstring(sid_string, &sid));
	DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
	tdb_delete(cache->tdb, string_tdb_data(key_str));

	/* Samba/winbindd never needs this. */
	netsamlogon_clear_cached_user(info3);
}

bool wcache_invalidate_cache(void)
{
	struct winbindd_domain *domain;

	for (domain = domain_list(); domain; domain = domain->next) {
		struct winbind_cache *cache = get_cache(domain);

		DEBUG(10, ("wcache_invalidate_cache: invalidating cache "
			   "entries for %s\n", domain->name));
		if (cache) {
			if (cache->tdb) {
				tdb_traverse(cache->tdb, traverse_fn, NULL);
			} else {
				return false;
			}
		}
	}
	return true;
}

bool init_wcache(void)
{
	if (wcache == NULL) {
		wcache = SMB_XMALLOC_P(struct winbind_cache);
		ZERO_STRUCTP(wcache);
	}

	if (wcache->tdb != NULL)
		return true;

	/* when working offline we must not clear the cache on restart */
	wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
				WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE, 
				lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST), 
				O_RDWR|O_CREAT, 0600);

	if (wcache->tdb == NULL) {
		DEBUG(0,("Failed to open winbindd_cache.tdb!\n"));
		return false;
	}

	return true;
}

/************************************************************************
 This is called by the parent to initialize the cache file.
 We don't need sophisticated locking here as we know we're the
 only opener.
************************************************************************/

bool initialize_winbindd_cache(void)
{
	bool cache_bad = true;
	uint32 vers;

	if (!init_wcache()) {
		DEBUG(0,("initialize_winbindd_cache: init_wcache failed.\n"));
		return false;
	}

	/* Check version number. */
	if (tdb_fetch_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, &vers) &&
			vers == WINBINDD_CACHE_VERSION) {
		cache_bad = false;
	}

	if (cache_bad) {
		DEBUG(0,("initialize_winbindd_cache: clearing cache "
			"and re-creating with version number %d\n",
			WINBINDD_CACHE_VERSION ));

		tdb_close(wcache->tdb);
		wcache->tdb = NULL;

		if (unlink(cache_path("winbindd_cache.tdb")) == -1) {
			DEBUG(0,("initialize_winbindd_cache: unlink %s failed %s ",
				cache_path("winbindd_cache.tdb"),
				strerror(errno) ));
			return false;
		}
		if (!init_wcache()) {
			DEBUG(0,("initialize_winbindd_cache: re-initialization "
					"init_wcache failed.\n"));
			return false;
		}

		/* Write the version. */
		if (!tdb_store_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, WINBINDD_CACHE_VERSION)) {
			DEBUG(0,("initialize_winbindd_cache: version number store failed %s\n",
				tdb_errorstr(wcache->tdb) ));
			return false;
		}
	}

	tdb_close(wcache->tdb);
	wcache->tdb = NULL;
	return true;
}

void close_winbindd_cache(void)
{
	if (!wcache) {
		return;
	}
	if (wcache->tdb) {
		tdb_close(wcache->tdb);
		wcache->tdb = NULL;
	}
}

bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const DOM_SID *sid,
		       char **domain_name, char **name,
		       enum lsa_SidType *type)
{
	struct winbindd_domain *domain;
	NTSTATUS status;

	domain = find_lookup_domain_from_sid(sid);
	if (domain == NULL) {
		return false;
	}
	status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
				    type);
	return NT_STATUS_IS_OK(status);
}

bool lookup_cached_name(TALLOC_CTX *mem_ctx,
			const char *domain_name,
			const char *name,
			DOM_SID *sid,
			enum lsa_SidType *type)
{
	struct winbindd_domain *domain;
	NTSTATUS status;
	bool original_online_state;

	domain = find_lookup_domain_from_name(domain_name);
	if (domain == NULL) {
		return false;
	}

	/* If we are doing a cached logon, temporarily set the domain
	   offline so the cache won't expire the entry */

	original_online_state = domain->online;
	domain->online = false;
	status = wcache_name_to_sid(domain, domain_name, name, sid, type);
	domain->online = original_online_state;

	return NT_STATUS_IS_OK(status);
}

void cache_name2sid(struct winbindd_domain *domain, 
		    const char *domain_name, const char *name,
		    enum lsa_SidType type, const DOM_SID *sid)
{
	refresh_sequence_number(domain, false);
	wcache_save_name_to_sid(domain, NT_STATUS_OK, domain_name, name,
				sid, type);
}

/*
 * The original idea that this cache only contains centries has
 * been blurred - now other stuff gets put in here. Ensure we
 * ignore these things on cleanup.
 */

static int traverse_fn_cleanup(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, 
			       TDB_DATA dbuf, void *state)
{
	struct cache_entry *centry;

	if (is_non_centry_key(kbuf)) {
		return 0;
	}

	centry = wcache_fetch_raw((char *)kbuf.dptr);
	if (!centry) {
		return 0;
	}

	if (!NT_STATUS_IS_OK(centry->status)) {
		DEBUG(10,("deleting centry %s\n", (const char *)kbuf.dptr));
		tdb_delete(the_tdb, kbuf);
	}

	centry_free(centry);
	return 0;
}

/* flush the cache */
void wcache_flush_cache(void)
{
	if (!wcache)
		return;
	if (wcache->tdb) {
		tdb_close(wcache->tdb);
		wcache->tdb = NULL;
	}
	if (!winbindd_use_cache()) {
		return;
	}

	/* when working offline we must not clear the cache on restart */
	wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
				WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE, 
				lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST), 
				O_RDWR|O_CREAT, 0600);

	if (!wcache->tdb) {
		DEBUG(0,("Failed to open winbindd_cache.tdb!\n"));
		return;
	}

	tdb_traverse(wcache->tdb, traverse_fn_cleanup, NULL);

	DEBUG(10,("wcache_flush_cache success\n"));
}

/* Count cached creds */

static int traverse_fn_cached_creds(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
			 	    void *state)
{
	int *cred_count = (int*)state;
 
	if (strncmp((const char *)kbuf.dptr, "CRED/", 5) == 0) {
		(*cred_count)++;
	}
	return 0;
}

NTSTATUS wcache_count_cached_creds(struct winbindd_domain *domain, int *count)
{
	struct winbind_cache *cache = get_cache(domain);

	*count = 0;

	if (!cache->tdb) {
		return NT_STATUS_INTERNAL_DB_ERROR;
	}
 
	tdb_traverse(cache->tdb, traverse_fn_cached_creds, (void *)count);

	return NT_STATUS_OK;
}

struct cred_list {
	struct cred_list *prev, *next;
	TDB_DATA key;
	fstring name;
	time_t created;
};
static struct cred_list *wcache_cred_list;

static int traverse_fn_get_credlist(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
				    void *state)
{
	struct cred_list *cred;

	if (strncmp((const char *)kbuf.dptr, "CRED/", 5) == 0) {

		cred = SMB_MALLOC_P(struct cred_list);
		if (cred == NULL) {
			DEBUG(0,("traverse_fn_remove_first_creds: failed to malloc new entry for list\n"));
			return -1;
		}

		ZERO_STRUCTP(cred);

		/* save a copy of the key */

		fstrcpy(cred->name, (const char *)kbuf.dptr);		
		DLIST_ADD(wcache_cred_list, cred);
	}

	return 0;
}

NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const DOM_SID *sid) 
{
	struct winbind_cache *cache = get_cache(domain);
	NTSTATUS status;
	int ret;
	struct cred_list *cred, *oldest = NULL;

	if (!cache->tdb) {
		return NT_STATUS_INTERNAL_DB_ERROR;
	}

	/* we possibly already have an entry */
 	if (sid && NT_STATUS_IS_OK(wcache_cached_creds_exist(domain, sid))) {

		fstring key_str, tmp;

		DEBUG(11,("we already have an entry, deleting that\n"));

		fstr_sprintf(key_str, "CRED/%s", sid_to_fstring(tmp, sid));

		tdb_delete(cache->tdb, string_tdb_data(key_str));

		return NT_STATUS_OK;
	}

	ret = tdb_traverse(cache->tdb, traverse_fn_get_credlist, NULL);
	if (ret == 0) {
		return NT_STATUS_OK;
	} else if ((ret == -1) || (wcache_cred_list == NULL)) {
		return NT_STATUS_OBJECT_NAME_NOT_FOUND;
	}

	ZERO_STRUCTP(oldest);

	for (cred = wcache_cred_list; cred; cred = cred->next) {

		TDB_DATA data;
		time_t t;

		data = tdb_fetch(cache->tdb, string_tdb_data(cred->name));
		if (!data.dptr) {
			DEBUG(10,("wcache_remove_oldest_cached_creds: entry for [%s] not found\n", 
				cred->name));
			status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
			goto done;
		}

		t = IVAL(data.dptr, 0);
		SAFE_FREE(data.dptr);

		if (!oldest) {
			oldest = SMB_MALLOC_P(struct cred_list);
			if (oldest == NULL) {
				status = NT_STATUS_NO_MEMORY;
				goto done;
			}

			fstrcpy(oldest->name, cred->name);
			oldest->created = t;
			continue;
		}

		if (t < oldest->created) {
			fstrcpy(oldest->name, cred->name);
			oldest->created = t;
		}
	}

	if (tdb_delete(cache->tdb, string_tdb_data(oldest->name)) == 0) {
		status = NT_STATUS_OK;
	} else {
		status = NT_STATUS_UNSUCCESSFUL;
	}
done:
	SAFE_FREE(wcache_cred_list);
	SAFE_FREE(oldest);

	return status;
}

/* Change the global online/offline state. */
bool set_global_winbindd_state_offline(void)
{
	TDB_DATA data;

	DEBUG(10,("set_global_winbindd_state_offline: offline requested.\n"));

	/* Only go offline if someone has created
	   the key "WINBINDD_OFFLINE" in the cache tdb. */

	if (wcache == NULL || wcache->tdb == NULL) {
		DEBUG(10,("set_global_winbindd_state_offline: wcache not open yet.\n"));
		return false;
	}

	if (!lp_winbind_offline_logon()) {
		DEBUG(10,("set_global_winbindd_state_offline: rejecting.\n"));
		return false;
	}

	if (global_winbindd_offline_state) {
		/* Already offline. */
		return true;
	}

	data = tdb_fetch_bystring( wcache->tdb, "WINBINDD_OFFLINE" );

	if (!data.dptr || data.dsize != 4) {
		DEBUG(10,("set_global_winbindd_state_offline: offline state not set.\n"));
		SAFE_FREE(data.dptr);
		return false;
	} else {
		DEBUG(10,("set_global_winbindd_state_offline: offline state set.\n"));
		global_winbindd_offline_state = true;
		SAFE_FREE(data.dptr);
		return true;
	}
}

void set_global_winbindd_state_online(void)
{
	DEBUG(10,("set_global_winbindd_state_online: online requested.\n"));

	if (!lp_winbind_offline_logon()) {
		DEBUG(10,("set_global_winbindd_state_online: rejecting.\n"));
		return;
	}

	if (!global_winbindd_offline_state) {
		/* Already online. */
		return;
	}
	global_winbindd_offline_state = false;

	if (!wcache->tdb) {
		return;
	}

	/* Ensure there is no key "WINBINDD_OFFLINE" in the cache tdb. */
	tdb_delete_bystring(wcache->tdb, "WINBINDD_OFFLINE");
}

bool get_global_winbindd_state_offline(void)
{
	return global_winbindd_offline_state;
}

/***********************************************************************
 Validate functions for all possible cache tdb keys.
***********************************************************************/

static struct cache_entry *create_centry_validate(const char *kstr, TDB_DATA data, 
						  struct tdb_validation_status *state)
{
	struct cache_entry *centry;

	centry = SMB_XMALLOC_P(struct cache_entry);
	centry->data = (unsigned char *)memdup(data.dptr, data.dsize);
	if (!centry->data) {
		SAFE_FREE(centry);
		return NULL;
	}
	centry->len = data.dsize;
	centry->ofs = 0;

	if (centry->len < 8) {
		/* huh? corrupt cache? */
		DEBUG(0,("create_centry_validate: Corrupt cache for key %s (len < 8) ?\n", kstr));
		centry_free(centry);
		state->bad_entry = true;
		state->success = false;
		return NULL;
	}

	centry->status = NT_STATUS(centry_uint32(centry));
	centry->sequence_number = centry_uint32(centry);
	return centry;
}

static int validate_seqnum(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			   struct tdb_validation_status *state)
{
	if (dbuf.dsize != 8) {
		DEBUG(0,("validate_seqnum: Corrupt cache for key %s (len %u != 8) ?\n",
				keystr, (unsigned int)dbuf.dsize ));
		state->bad_entry = true;
		return 1;
	}
	return 0;
}

static int validate_ns(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	if (!centry) {
		return 1;
	}

	(void)centry_uint32(centry);
	if (NT_STATUS_IS_OK(centry->status)) {
		DOM_SID sid;
		(void)centry_sid(centry, &sid);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_ns: %s ok\n", keystr));
	return 0;
}

static int validate_sn(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	if (!centry) {
		return 1;
	}

	if (NT_STATUS_IS_OK(centry->status)) {
		(void)centry_uint32(centry);
		(void)centry_string(centry, mem_ctx);
		(void)centry_string(centry, mem_ctx);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_sn: %s ok\n", keystr));
	return 0;
}

static int validate_u(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		      struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	DOM_SID sid;

	if (!centry) {
		return 1;
	}

	(void)centry_string(centry, mem_ctx);
	(void)centry_string(centry, mem_ctx);
	(void)centry_string(centry, mem_ctx);
	(void)centry_string(centry, mem_ctx);
	(void)centry_uint32(centry);
	(void)centry_sid(centry, &sid);
	(void)centry_sid(centry, &sid);

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_u: %s ok\n", keystr));
	return 0;
}

static int validate_loc_pol(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			    struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_nttime(centry);
	(void)centry_nttime(centry);
	(void)centry_uint16(centry);

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_loc_pol: %s ok\n", keystr));
	return 0;
}

static int validate_pwd_pol(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			    struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_uint16(centry);
	(void)centry_uint16(centry);
	(void)centry_uint32(centry);
	(void)centry_nttime(centry);
	(void)centry_nttime(centry);

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_pwd_pol: %s ok\n", keystr));
	return 0;
}

static int validate_cred(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			 struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_time(centry);
	(void)centry_hash16(centry, mem_ctx);

	/* We only have 17 bytes more data in the salted cred case. */
	if (centry->len - centry->ofs == 17) {
		(void)centry_hash16(centry, mem_ctx);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_cred: %s ok\n", keystr));
	return 0;
}

static int validate_ul(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	int32 num_entries, i;

	if (!centry) {
		return 1;
	}

	num_entries = (int32)centry_uint32(centry);

	for (i=0; i< num_entries; i++) {
		DOM_SID sid;
		(void)centry_string(centry, mem_ctx);
		(void)centry_string(centry, mem_ctx);
		(void)centry_string(centry, mem_ctx);
		(void)centry_string(centry, mem_ctx);
		(void)centry_sid(centry, &sid);
		(void)centry_sid(centry, &sid);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_ul: %s ok\n", keystr));
	return 0;
}

static int validate_gl(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	int32 num_entries, i;

	if (!centry) {
		return 1;
	}

	num_entries = centry_uint32(centry);

	for (i=0; i< num_entries; i++) {
		(void)centry_string(centry, mem_ctx);
		(void)centry_string(centry, mem_ctx);
		(void)centry_uint32(centry);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_gl: %s ok\n", keystr));
	return 0;
}

static int validate_ug(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	int32 num_groups, i;

	if (!centry) {
		return 1;
	}

	num_groups = centry_uint32(centry);

	for (i=0; i< num_groups; i++) {
		DOM_SID sid;
		centry_sid(centry, &sid);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_ug: %s ok\n", keystr));
	return 0;
}

static int validate_ua(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	int32 num_aliases, i;

	if (!centry) {
		return 1;
	}

	num_aliases = centry_uint32(centry);

	for (i=0; i < num_aliases; i++) {
		(void)centry_uint32(centry);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_ua: %s ok\n", keystr));
	return 0;
}

static int validate_gm(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
	int32 num_names, i;

	if (!centry) {
		return 1;
	}

	num_names = centry_uint32(centry);

	for (i=0; i< num_names; i++) {
		DOM_SID sid;
		centry_sid(centry, &sid);
		(void)centry_string(centry, mem_ctx);
		(void)centry_uint32(centry);
	}

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_gm: %s ok\n", keystr));
	return 0;
}

static int validate_dr(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	/* Can't say anything about this other than must be nonzero. */
	if (dbuf.dsize == 0) {
		DEBUG(0,("validate_dr: Corrupt cache for key %s (len == 0) ?\n",
				keystr));
		state->bad_entry = true;
		state->success = false;
		return 1;
	}

	DEBUG(10,("validate_dr: %s ok\n", keystr));
	return 0;
}

static int validate_de(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
		       struct tdb_validation_status *state)
{
	/* Can't say anything about this other than must be nonzero. */
	if (dbuf.dsize == 0) {
		DEBUG(0,("validate_de: Corrupt cache for key %s (len == 0) ?\n",
				keystr));
		state->bad_entry = true;
		state->success = false;
		return 1;
	}

	DEBUG(10,("validate_de: %s ok\n", keystr));
	return 0;
}

static int validate_pwinfo(TALLOC_CTX *mem_ctx, const char *keystr,
			   TDB_DATA dbuf, struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_string(centry, mem_ctx);
	(void)centry_string(centry, mem_ctx);
	(void)centry_string(centry, mem_ctx);
	(void)centry_uint32(centry);

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
	return 0;
}

static int validate_nss_an(TALLOC_CTX *mem_ctx, const char *keystr,
			   TDB_DATA dbuf,
			   struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_string( centry, mem_ctx );

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
	return 0;
}

static int validate_nss_na(TALLOC_CTX *mem_ctx, const char *keystr,
			   TDB_DATA dbuf,
			   struct tdb_validation_status *state)
{
	struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);

	if (!centry) {
		return 1;
	}

	(void)centry_string( centry, mem_ctx );

	centry_free(centry);

	if (!(state->success)) {
		return 1;
	}
	DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
	return 0;
}

static int validate_trustdomcache(TALLOC_CTX *mem_ctx, const char *keystr, 
				  TDB_DATA dbuf,
				  struct tdb_validation_status *state)
{
	if (dbuf.dsize == 0) {
		DEBUG(0, ("validate_trustdomcache: Corrupt cache for "
			  "key %s (len ==0) ?\n", keystr));
		state->bad_entry = true;
		state->success = false;
		return 1;
	}

	DEBUG(10,    ("validate_trustdomcache: %s ok\n", keystr));
	DEBUGADD(10, ("  Don't trust me, I am a DUMMY!\n"));
	return 0;
}

static int validate_offline(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			    struct tdb_validation_status *state)
{
	if (dbuf.dsize != 4) {
		DEBUG(0,("validate_offline: Corrupt cache for key %s (len %u != 4) ?\n",
				keystr, (unsigned int)dbuf.dsize ));
		state->bad_entry = true;
		state->success = false;
		return 1;
	}
	DEBUG(10,("validate_offline: %s ok\n", keystr));
	return 0;
}

static int validate_ndr(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
			struct tdb_validation_status *state)
{
	/*
	 * Ignore validation for now. The proper way to do this is with a
	 * checksum. Just pure parsing does not really catch much.
	 */
	return 0;
}

static int validate_cache_version(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
				  struct tdb_validation_status *state)
{
	if (dbuf.dsize != 4) {
		DEBUG(0, ("validate_cache_version: Corrupt cache for "
			  "key %s (len %u != 4) ?\n", 
			  keystr, (unsigned int)dbuf.dsize));
		state->bad_entry = true;
		state->success = false;
		return 1;
	}

	DEBUG(10, ("validate_cache_version: %s ok\n", keystr));
	return 0;
}

/***********************************************************************
 A list of all possible cache tdb keys with associated validation
 functions.
***********************************************************************/

struct key_val_struct {
	const char *keyname;
	int (*validate_data_fn)(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf, struct tdb_validation_status* state);
} key_val[] = {
	{"SEQNUM/", validate_seqnum},
	{"NS/", validate_ns},
	{"SN/", validate_sn},
	{"U/", validate_u},
	{"LOC_POL/", validate_loc_pol},
	{"PWD_POL/", validate_pwd_pol},
	{"CRED/", validate_cred},
	{"UL/", validate_ul},
	{"GL/", validate_gl},
	{"UG/", validate_ug},
	{"UA", validate_ua},
	{"GM/", validate_gm},
	{"DR/", validate_dr},
	{"DE/", validate_de},
	{"NSS/PWINFO/", validate_pwinfo},
	{"TRUSTDOMCACHE/", validate_trustdomcache},
	{"NSS/NA/", validate_nss_na},
	{"NSS/AN/", validate_nss_an},
	{"WINBINDD_OFFLINE", validate_offline},
	{"NDR/", validate_ndr},
	{WINBINDD_CACHE_VERSION_KEYSTR, validate_cache_version},
	{NULL, NULL}
};

/***********************************************************************
 Function to look at every entry in the tdb and validate it as far as
 possible.
***********************************************************************/

static int cache_traverse_validate_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, void *state)
{
	int i;
	unsigned int max_key_len = 1024;
	struct tdb_validation_status *v_state = (struct tdb_validation_status *)state;

	/* Paranoia check. */
	if (strncmp("UA/", (const char *)kbuf.dptr, 3) == 0) {
		max_key_len = 1024 * 1024;
	}
	if (kbuf.dsize > max_key_len) {
		DEBUG(0, ("cache_traverse_validate_fn: key length too large: "
			  "(%u) > (%u)\n\n",
			  (unsigned int)kbuf.dsize, (unsigned int)max_key_len));
		return 1;
	}

	for (i = 0; key_val[i].keyname; i++) {
		size_t namelen = strlen(key_val[i].keyname);
		if (kbuf.dsize >= namelen && (
				strncmp(key_val[i].keyname, (const char *)kbuf.dptr, namelen)) == 0) {
			TALLOC_CTX *mem_ctx;
			char *keystr;
			int ret;

			keystr = SMB_MALLOC_ARRAY(char, kbuf.dsize+1);
			if (!keystr) {
				return 1;
			}
			memcpy(keystr, kbuf.dptr, kbuf.dsize);
			keystr[kbuf.dsize] = '\0';

			mem_ctx = talloc_init("validate_ctx");
			if (!mem_ctx) {
				SAFE_FREE(keystr);
				return 1;
			}

			ret = key_val[i].validate_data_fn(mem_ctx, keystr, dbuf, 
							  v_state);

			SAFE_FREE(keystr);
			talloc_destroy(mem_ctx);
			return ret;
		}
	}

	DEBUG(0,("cache_traverse_validate_fn: unknown cache entry\nkey :\n"));
	dump_data(0, (uint8 *)kbuf.dptr, kbuf.dsize);
	DEBUG(0,("data :\n"));
	dump_data(0, (uint8 *)dbuf.dptr, dbuf.dsize);
	v_state->unknown_key = true;
	v_state->success = false;
	return 1; /* terminate. */
}

static void validate_panic(const char *const why)
{
        DEBUG(0,("validating cache: would panic %s\n", why ));
	DEBUGADD(0, ("exiting instead (cache validation mode)\n"));
	exit(47);
}

/***********************************************************************
 Try and validate every entry in the winbindd cache. If we fail here,
 delete the cache tdb and return non-zero.
***********************************************************************/

int winbindd_validate_cache(void)
{
	int ret = -1;
	const char *tdb_path = cache_path("winbindd_cache.tdb");
	TDB_CONTEXT *tdb = NULL;

	DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
	smb_panic_fn = validate_panic;


	tdb = tdb_open_log(tdb_path, 
			   WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
			   ( lp_winbind_offline_logon() 
			     ? TDB_DEFAULT 
			     : TDB_DEFAULT | TDB_CLEAR_IF_FIRST ),
			   O_RDWR|O_CREAT, 
			   0600);
	if (!tdb) {
		DEBUG(0, ("winbindd_validate_cache: "
			  "error opening/initializing tdb\n"));
		goto done;
	}
	tdb_close(tdb);

	ret = tdb_validate_and_backup(tdb_path, cache_traverse_validate_fn);

	if (ret != 0) {
		DEBUG(10, ("winbindd_validate_cache: validation not successful.\n"));
		DEBUGADD(10, ("removing tdb %s.\n", tdb_path));
		unlink(tdb_path);
	}

done:
	DEBUG(10, ("winbindd_validate_cache: restoring panic function\n"));
	smb_panic_fn = smb_panic;
	return ret;
}

/***********************************************************************
 Try and validate every entry in the winbindd cache.
***********************************************************************/

int winbindd_validate_cache_nobackup(void)
{
	int ret = -1;
	const char *tdb_path = cache_path("winbindd_cache.tdb");

	DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
	smb_panic_fn = validate_panic;


	if (wcache == NULL || wcache->tdb == NULL) {
		ret = tdb_validate_open(tdb_path, cache_traverse_validate_fn);
	} else {
		ret = tdb_validate(wcache->tdb, cache_traverse_validate_fn);
	}

	if (ret != 0) {
		DEBUG(10, ("winbindd_validate_cache_nobackup: validation not "
			   "successful.\n"));
	}

	DEBUG(10, ("winbindd_validate_cache_nobackup: restoring panic "
		   "function\n"));
	smb_panic_fn = smb_panic;
	return ret;
}

bool winbindd_cache_validate_and_initialize(void)
{
	close_winbindd_cache();

	if (lp_winbind_offline_logon()) {
		if (winbindd_validate_cache() < 0) {
			DEBUG(0, ("winbindd cache tdb corrupt and no backup "
				  "could be restored.\n"));
		}
	}

	return initialize_winbindd_cache();
}

/*********************************************************************
 ********************************************************************/

static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
				       struct winbindd_tdc_domain **domains, 
				       size_t *num_domains )
{
	struct winbindd_tdc_domain *list = NULL;
	size_t idx;
	int i;
	bool set_only = false;

	/* don't allow duplicates */

	idx = *num_domains;
	list = *domains;

	for ( i=0; i< (*num_domains); i++ ) {
		if ( strequal( new_dom->name, list[i].domain_name ) ) {
			DEBUG(10,("add_wbdomain_to_tdc_array: Found existing record for %s\n",
				  new_dom->name));
			idx = i;
			set_only = true;

			break;
		}
	}

	if ( !set_only ) {
		if ( !*domains ) {
			list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, 1 );
			idx = 0;
		} else {
			list = TALLOC_REALLOC_ARRAY( *domains, *domains, 
						     struct winbindd_tdc_domain,  
						     (*num_domains)+1);
			idx = *num_domains;		
		}

		ZERO_STRUCT( list[idx] );
	}

	if ( !list )
		return false;

	list[idx].domain_name = talloc_strdup( list, new_dom->name );
	list[idx].dns_name = talloc_strdup( list, new_dom->alt_name );

	if ( !is_null_sid( &new_dom->sid ) ) {
		sid_copy( &list[idx].sid, &new_dom->sid );
	} else {
		sid_copy(&list[idx].sid, &global_sid_NULL);
	}

	if ( new_dom->domain_flags != 0x0 )
		list[idx].trust_flags = new_dom->domain_flags;	

	if ( new_dom->domain_type != 0x0 )
		list[idx].trust_type = new_dom->domain_type;

	if ( new_dom->domain_trust_attribs != 0x0 )
		list[idx].trust_attribs = new_dom->domain_trust_attribs;

	if ( !set_only ) {
		*domains = list;
		*num_domains = idx + 1;	
	}

	return true;
}

/*********************************************************************
 ********************************************************************/

static TDB_DATA make_tdc_key( const char *domain_name )
{
	char *keystr = NULL;
	TDB_DATA key = { NULL, 0 };

	if ( !domain_name ) {
		DEBUG(5,("make_tdc_key: Keyname workgroup is NULL!\n"));
		return key;
	}

	if (asprintf( &keystr, "TRUSTDOMCACHE/%s", domain_name ) == -1) {
		return key;
	}
	key = string_term_tdb_data(keystr);

	return key;	
}

/*********************************************************************
 ********************************************************************/

static int pack_tdc_domains( struct winbindd_tdc_domain *domains, 
			     size_t num_domains,
			     unsigned char **buf )
{
        unsigned char *buffer = NULL;
	int len = 0;
	int buflen = 0;
	int i = 0;

	DEBUG(10,("pack_tdc_domains: Packing %d trusted domains\n",
		  (int)num_domains));

	buflen = 0;

 again: 
	len = 0;

	/* Store the number of array items first */
	len += tdb_pack( buffer+len, buflen-len, "d", 
			 num_domains );

	/* now pack each domain trust record */
	for ( i=0; i<num_domains; i++ ) {

		fstring tmp;

		if ( buflen > 0 ) {
			DEBUG(10,("pack_tdc_domains: Packing domain %s (%s)\n",
				  domains[i].domain_name,
				  domains[i].dns_name ? domains[i].dns_name : "UNKNOWN" ));
		}

		len += tdb_pack( buffer+len, buflen-len, "fffddd",
				 domains[i].domain_name,
				 domains[i].dns_name,
				 sid_to_fstring(tmp, &domains[i].sid),
				 domains[i].trust_flags,
				 domains[i].trust_attribs,
				 domains[i].trust_type );
	}

	if ( buflen < len ) {
		SAFE_FREE(buffer);
		if ( (buffer = SMB_MALLOC_ARRAY(unsigned char, len)) == NULL ) {
			DEBUG(0,("pack_tdc_domains: failed to alloc buffer!\n"));
			buflen = -1;
			goto done;
		}
		buflen = len;
		goto again;
	}

	*buf = buffer;	

 done:	
	return buflen;	
}

/*********************************************************************
 ********************************************************************/

static size_t unpack_tdc_domains( unsigned char *buf, int buflen, 
				  struct winbindd_tdc_domain **domains )
{
	fstring domain_name, dns_name, sid_string;	
	uint32 type, attribs, flags;
	int num_domains;
	int len = 0;
	int i;
	struct winbindd_tdc_domain *list = NULL;

	/* get the number of domains */
	len += tdb_unpack( buf+len, buflen-len, "d", &num_domains);
	if ( len == -1 ) {
		DEBUG(5,("unpack_tdc_domains: Failed to unpack domain array\n"));		
		return 0;
	}

	list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, num_domains );
	if ( !list ) {
		DEBUG(0,("unpack_tdc_domains: Failed to talloc() domain list!\n"));
		return 0;		
	}

	for ( i=0; i<num_domains; i++ ) {
		len += tdb_unpack( buf+len, buflen-len, "fffddd",
				   domain_name,
				   dns_name,
				   sid_string,
				   &flags,
				   &attribs,
				   &type );

		if ( len == -1 ) {
			DEBUG(5,("unpack_tdc_domains: Failed to unpack domain array\n"));
			TALLOC_FREE( list );			
			return 0;
		}

		DEBUG(11,("unpack_tdc_domains: Unpacking domain %s (%s) "
			  "SID %s, flags = 0x%x, attribs = 0x%x, type = 0x%x\n",
			  domain_name, dns_name, sid_string,
			  flags, attribs, type));

		list[i].domain_name = talloc_strdup( list, domain_name );
		list[i].dns_name = talloc_strdup( list, dns_name );
		if ( !string_to_sid( &(list[i].sid), sid_string ) ) {			
			DEBUG(10,("unpack_tdc_domains: no SID for domain %s\n",
				  domain_name));
		}
		list[i].trust_flags = flags;
		list[i].trust_attribs = attribs;
		list[i].trust_type = type;
	}

	*domains = list;

	return num_domains;
}

/*********************************************************************
 ********************************************************************/

static bool wcache_tdc_store_list( struct winbindd_tdc_domain *domains, size_t num_domains )
{
	TDB_DATA key = make_tdc_key( lp_workgroup() );	 
	TDB_DATA data = { NULL, 0 };
	int ret;

	if ( !key.dptr )
		return false;

	/* See if we were asked to delete the cache entry */

	if ( !domains ) {
		ret = tdb_delete( wcache->tdb, key );
		goto done;
	}

	data.dsize = pack_tdc_domains( domains, num_domains, &data.dptr );

	if ( !data.dptr ) {
		ret = -1;
		goto done;
	}

	ret = tdb_store( wcache->tdb, key, data, 0 );

 done:
	SAFE_FREE( data.dptr );
	SAFE_FREE( key.dptr );

	return ( ret != -1 );	
}

/*********************************************************************
 ********************************************************************/

bool wcache_tdc_fetch_list( struct winbindd_tdc_domain **domains, size_t *num_domains )
{
	TDB_DATA key = make_tdc_key( lp_workgroup() );
	TDB_DATA data = { NULL, 0 };

	*domains = NULL;	
	*num_domains = 0;	

	if ( !key.dptr )
		return false;

	data = tdb_fetch( wcache->tdb, key );

	SAFE_FREE( key.dptr );

	if ( !data.dptr ) 
		return false;

	*num_domains = unpack_tdc_domains( data.dptr, data.dsize, domains );

	SAFE_FREE( data.dptr );

	if ( !*domains )
		return false;

	return true;
}

/*********************************************************************
 ********************************************************************/

bool wcache_tdc_add_domain( struct winbindd_domain *domain )
{
	struct winbindd_tdc_domain *dom_list = NULL;
	size_t num_domains = 0;
	bool ret = false;

	DEBUG(10,("wcache_tdc_add_domain: Adding domain %s (%s), SID %s, "
		  "flags = 0x%x, attributes = 0x%x, type = 0x%x\n",
		  domain->name, domain->alt_name, 
		  sid_string_dbg(&domain->sid),
		  domain->domain_flags,
		  domain->domain_trust_attribs,
		  domain->domain_type));	

	if ( !init_wcache() ) {
		return false;
	}

	/* fetch the list */

	wcache_tdc_fetch_list( &dom_list, &num_domains );

	/* add the new domain */

	if ( !add_wbdomain_to_tdc_array( domain, &dom_list, &num_domains ) ) {
		goto done;		
	}	

	/* pack the domain */

	if ( !wcache_tdc_store_list( dom_list, num_domains ) ) {
		goto done;		
	}

	/* Success */

	ret = true;
 done:
	TALLOC_FREE( dom_list );

	return ret;	
}

/*********************************************************************
 ********************************************************************/

struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const char *name )
{
	struct winbindd_tdc_domain *dom_list = NULL;
	size_t num_domains = 0;
	int i;
	struct winbindd_tdc_domain *d = NULL;	

	DEBUG(10,("wcache_tdc_fetch_domain: Searching for domain %s\n", name));

	if ( !init_wcache() ) {
		return false;
	}

	/* fetch the list */

	wcache_tdc_fetch_list( &dom_list, &num_domains );

	for ( i=0; i<num_domains; i++ ) {
		if ( strequal(name, dom_list[i].domain_name) ||
		     strequal(name, dom_list[i].dns_name) )
		{
			DEBUG(10,("wcache_tdc_fetch_domain: Found domain %s\n",
				  name));

			d = TALLOC_P( ctx, struct winbindd_tdc_domain );
			if ( !d )
				break;			

			d->domain_name = talloc_strdup( d, dom_list[i].domain_name );
			d->dns_name = talloc_strdup( d, dom_list[i].dns_name );
			sid_copy( &d->sid, &dom_list[i].sid );
			d->trust_flags   = dom_list[i].trust_flags;
			d->trust_type    = dom_list[i].trust_type;
			d->trust_attribs = dom_list[i].trust_attribs;

			break;
		}
	}

        TALLOC_FREE( dom_list );

	return d;	
}


/*********************************************************************
 ********************************************************************/

void wcache_tdc_clear( void )
{
	if ( !init_wcache() )
		return;

	wcache_tdc_store_list( NULL, 0 );

	return;	
}


/*********************************************************************
 ********************************************************************/

static void wcache_save_user_pwinfo(struct winbindd_domain *domain, 
				    NTSTATUS status,
				    const DOM_SID *user_sid,
				    const char *homedir,
				    const char *shell,
				    const char *gecos,
				    uint32 gid)
{
	struct cache_entry *centry;
	fstring tmp;

	if ( (centry = centry_start(domain, status)) == NULL )
		return;

	centry_put_string( centry, homedir );
	centry_put_string( centry, shell );
	centry_put_string( centry, gecos );
	centry_put_uint32( centry, gid );

	centry_end(centry, "NSS/PWINFO/%s", sid_to_fstring(tmp, user_sid) );

	DEBUG(10,("wcache_save_user_pwinfo: %s\n", sid_string_dbg(user_sid) ));

	centry_free(centry);
}

NTSTATUS nss_get_info_cached( struct winbindd_domain *domain, 
			      const DOM_SID *user_sid,
			      TALLOC_CTX *ctx,
			      ADS_STRUCT *ads, LDAPMessage *msg,
			      const char **homedir, const char **shell,
			      const char **gecos, gid_t *p_gid)
{
	struct winbind_cache *cache = get_cache(domain);
	struct cache_entry *centry = NULL;
	NTSTATUS nt_status;
	fstring tmp;

	if (!cache->tdb)
		goto do_query;

	centry = wcache_fetch(cache, domain, "NSS/PWINFO/%s",
			      sid_to_fstring(tmp, user_sid));

	if (!centry)
		goto do_query;

	*homedir = centry_string( centry, ctx );
	*shell   = centry_string( centry, ctx );
	*gecos   = centry_string( centry, ctx );
	*p_gid   = centry_uint32( centry );	

	centry_free(centry);

	DEBUG(10,("nss_get_info_cached: [Cached] - user_sid %s\n",
		  sid_string_dbg(user_sid)));

	return NT_STATUS_OK;

do_query:

	nt_status = nss_get_info( domain->name, user_sid, ctx, ads, msg, 
				  homedir, shell, gecos, p_gid );

	DEBUG(10, ("nss_get_info returned %s\n", nt_errstr(nt_status)));

	if ( NT_STATUS_IS_OK(nt_status) ) {
		DEBUG(10, ("result:\n\thomedir = '%s'\n", *homedir));
                DEBUGADD(10, ("\tshell = '%s'\n", *shell));
                DEBUGADD(10, ("\tgecos = '%s'\n", *gecos));
                DEBUGADD(10, ("\tgid = '%u'\n", (unsigned int)*p_gid));

		wcache_save_user_pwinfo( domain, nt_status, user_sid,
					 *homedir, *shell, *gecos, *p_gid );
	}	

	if ( NT_STATUS_EQUAL( nt_status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND ) ) {
		DEBUG(5,("nss_get_info_cached: Setting domain %s offline\n",
			 domain->name ));
		set_domain_offline( domain );
	}

	return nt_status;	
}


/* the cache backend methods are exposed via this structure */
struct winbindd_methods cache_methods = {
	true,
	query_user_list,
	enum_dom_groups,
	enum_local_groups,
	name_to_sid,
	sid_to_name,
	rids_to_names,
	query_user,
	lookup_usergroups,
	lookup_useraliases,
	lookup_groupmem,
	sequence_number,
	lockout_policy,
	password_policy,
	trusted_domains
};

static bool wcache_ndr_key(TALLOC_CTX *mem_ctx, char *domain_name,
			   uint32_t opnum, const DATA_BLOB *req,
			   TDB_DATA *pkey)
{
	char *key;
	size_t keylen;

	key = talloc_asprintf(mem_ctx, "NDR/%s/%d/", domain_name, (int)opnum);
	if (key == NULL) {
		return false;
	}
	keylen = talloc_get_size(key) - 1;

	key = talloc_realloc(mem_ctx, key, char, keylen + req->length);
	if (key == NULL) {
		return false;
	}
	memcpy(key + keylen, req->data, req->length);

	pkey->dptr = (uint8_t *)key;
	pkey->dsize = talloc_get_size(key);
	return true;
}

static bool wcache_opnum_cacheable(uint32_t opnum)
{
	switch (opnum) {
	case NDR_WBINT_PING:
	case NDR_WBINT_QUERYSEQUENCENUMBER:
	case NDR_WBINT_ALLOCATEUID:
	case NDR_WBINT_ALLOCATEGID:
	case NDR_WBINT_CHECKMACHINEACCOUNT:
	case NDR_WBINT_CHANGEMACHINEACCOUNT:
	case NDR_WBINT_PINGDC:
		return false;
	}
	return true;
}

bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
		      uint32_t opnum, const DATA_BLOB *req, DATA_BLOB *resp)
{
	TDB_DATA key, data;
	bool ret = false;

	if (!wcache_opnum_cacheable(opnum)) {
		return false;
	}

	if (wcache->tdb == NULL) {
		return false;
	}

	if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
		return false;
	}
	data = tdb_fetch(wcache->tdb, key);
	TALLOC_FREE(key.dptr);

	if (data.dptr == NULL) {
		return false;
	}
	if (data.dsize < 4) {
		goto fail;
	}

	if (!is_domain_offline(domain)) {
		uint32_t entry_seqnum, dom_seqnum, last_check;

		if (!wcache_fetch_seqnum(domain->name, &dom_seqnum,
					 &last_check)) {
			goto fail;
		}
		entry_seqnum = IVAL(data.dptr, 0);
		if (entry_seqnum != dom_seqnum) {
			DEBUG(10, ("Entry has wrong sequence number: %d\n",
				   (int)entry_seqnum));
			goto fail;
		}
	}

	resp->data = (uint8_t *)talloc_memdup(mem_ctx, data.dptr + 4,
					      data.dsize - 4);
	if (resp->data == NULL) {
		DEBUG(10, ("talloc failed\n"));
		goto fail;
	}
	resp->length = data.dsize - 4;

	ret = true;
fail:
	SAFE_FREE(data.dptr);
	return ret;
}

void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
		      const DATA_BLOB *req, const DATA_BLOB *resp)
{
	TDB_DATA key, data;
	uint32_t dom_seqnum, last_check;

	if (!wcache_opnum_cacheable(opnum)) {
		return;
	}

	if (wcache->tdb == NULL) {
		return;
	}

	if (!wcache_fetch_seqnum(domain->name, &dom_seqnum, &last_check)) {
		DEBUG(10, ("could not fetch seqnum for domain %s\n",
			   domain->name));
		return;
	}

	if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
		return;
	}

	data.dsize = resp->length + 4;
	data.dptr = talloc_array(key.dptr, uint8_t, data.dsize);
	if (data.dptr == NULL) {
		goto done;
	}

	SIVAL(data.dptr, 0, dom_seqnum);
	memcpy(data.dptr+4, resp->data, resp->length);

	tdb_store(wcache->tdb, key, data, 0);

done:
	TALLOC_FREE(key.dptr);
	return;
}