1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
|
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2014 Nexenta Systems, Inc. All rights reserved.
#
# Copyright (c) 2018, Joyent, Inc.
# Copyright 2022-2023 RackTop Systems, Inc.
PROG = idmapd
MANIFEST = idmap.xml
SERVEROBJS = \
adspriv_impl.o \
directory_provider_builtin.o \
directory_provider_nsswitch.o \
directory_provider_ad.o \
directory_server.o \
adutils.o \
dbutils.o \
idmap_config.o \
idmapd.o \
init.o \
idmap_lsa.o \
krb5_lookup.o \
nldaputils.o \
server.o \
wksids.o
GENOBJS = \
adspriv_srv.o \
rpc_svc.o
SERVERSRCS = $(SERVEROBJS:%.o=%.c)
GENSRCS = $(GENOBJS:%.o=%.c)
OBJS = $(SERVEROBJS) $(GENOBJS)
SRCS = $(SERVERSRCS)
POFILES = $(OBJS:%.o=%.po)
all : TARGET = all
install : TARGET = install
clean : TARGET = clean
clobber : TARGET = clobber
include ../../Makefile.cmd
include ../../Makefile.ctf
CERRWARN += -Wno-type-limits
CERRWARN += -Wno-switch
CERRWARN += $(CNOWARN_UNINIT)
# not linted
SMATCH=off
TEXT_DOMAIN = SUNW_OST_OSLIB
XGETTEXT = $(GNUXGETTEXT)
XGETFLAGS = --foreign-user --strict -n -E --width=72 \
--omit-header --keyword=directoryError:2 \
--language=C --force-po
CSTD = $(CSTD_GNU99)
POFILE = $(PROG)_all.po
RPC_MSGOUT_OPT = -DRPC_MSGOUT=idmap_rpc_msgout
ROOTMANIFESTDIR = $(ROOTSVCSYSTEM)
$(ROOTMANIFEST) : FILEMODE= 444
RPCSVC= ../../../uts/common/rpcsvc
ADS_CMN=../../../lib/libads/common
INCS += -I. -I../../../lib/libidmap/common \
-I../../../lib/libsldap/common \
-I../../../lib/libadutils/common \
-I $(ADS_CMN) \
-I$(RPCSVC) \
-I../../../lib/smbsrv/libsmb/common
# Should not have to do this, but the Kerberos includes are a mess.
INCS += -I $(ROOT)/usr/include/kerberosv5
$(OBJS) : CPPFLAGS += $(INCS) -D_REENTRANT
$(POFILE) : CPPFLAGS += $(INCS)
CFLAGS += $(CCVERBOSE)
$(NOT_RELEASE_BUILD)CPPFLAGS += -DIDMAPD_DEBUG
LDLIBS += \
-lsqlite-sys \
-lsecdb \
-lsocket \
-lnsl \
-lidmap \
-lscf \
-lsldap \
-lldap \
-luuid \
-ladutils \
-lads \
-lumem \
-lnvpair \
-luutil \
-L $(ROOT)/usr/lib/smbsrv \
-lsmb
rpc_svc.o : CFLAGS += $(RPC_MSGOUT_OPT)
LDFLAGS += -R /usr/lib/smbsrv
DIRMODE = 0755
FILEMODE = 0555
.KEEP_STATE:
.PARALLEL: $(OBJS)
all: $(PROG)
$(PROG): $(OBJS)
$(LINK.c) -o $@ $(OBJS) $(LDLIBS)
$(POST_PROCESS)
# Hammerhead: some .po files may not exist (pre-generated rpcgen stubs
# don't have translatable strings). Only cat files that exist.
$(POFILE):
$(RM) $(POFILE)
for f in $(POFILES); do [ -f $$f ] && cat $$f || true; done > $(POFILE)
install: all $(ROOTLIBPROG) $(ROOTMANIFEST)
check: $(CHKMANIFEST)
clean:
$(RM) $(OBJS)
@# Hammerhead: do not delete pre-generated $(GENSRCS)
RPCGENFLAGS = -CMN
adspriv_srv.o : adspriv_srv.c
# Hammerhead: pre-generated (rpcgen + GNU cpp truncation bug)
# adspriv_srv.c and rpc_svc.c are now committed source files.
rpc_svc.o : rpc_svc.c
include ../../Makefile.targ
/*
* This file and its contents are supplied under the terms of the
* Common Development and Distribution License ("CDDL"), version 1.0.
* You may only use this file in accordance with the terms of version
* 1.0 of the CDDL.
*
* A full copy of the text of the CDDL should have accompanied this
* source. A copy of the CDDL is also available via the Internet at
* http://www.illumos.org/license/CDDL.
*/
/*
* Copyright 2014 Nexenta Systems, Inc. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <syslog.h>
#include <rpc/rpc.h>
#include <sys/uuid.h>
#include <smb/ntstatus.h>
#include <synch.h>
#include <thread.h>
#include <arpa/inet.h>
#include <uuid/uuid.h>
#include "idmapd.h"
#include "libadutils.h"
#include "dsgetdc.h"
#include "ads_priv.h"
void adspriv_program_1(struct svc_req *, register SVCXPRT *);
SVCXPRT *dcl_xprt = NULL;
void
init_dc_locator(void)
{
int connmaxrec = 32 * 1024;
dcl_xprt = svc_door_create(adspriv_program_1,
ADSPRIV_PROGRAM, ADSPRIV_V1, connmaxrec);
if (dcl_xprt == NULL) {
syslog(LOG_ERR, "unable to create door RPC service");
return;
}
if (!svc_control(dcl_xprt, SVCSET_CONNMAXREC, &connmaxrec)) {
syslog(LOG_ERR, "unable to limit RPC request size");
}
}
void
fini_dc_locator(void)
{
if (dcl_xprt != NULL)
svc_destroy(dcl_xprt);
}
/*
* Functions called by the (generated) adspriv_srv.c
*/
/* ARGSUSED */
bool_t
adspriv_null_1_svc(void *result, struct svc_req *rqstp)
{
return (TRUE);
}
/* ARGSUSED */
bool_t
adspriv_forcerediscovery_1_svc(
DsForceRediscoveryArgs args,
int *res,
struct svc_req *sreq)
{
/* Ignoring args for now. */
idmap_cfg_force_rediscovery();
*res = 0;
return (TRUE);
}
/* ARGSUSED */
bool_t
adspriv_getdcname_1_svc(
DsGetDcNameArgs args,
DsGetDcNameRes *res,
struct svc_req *sreq)
{
uuid_t uuid;
adspriv_dcinfo *dci;
idmap_pg_config_t *pgcfg;
ad_disc_ds_t *ds;
char *s;
/* Init */
(void) memset(res, 0, sizeof (*res));
res->status = 0;
dci = &res->DsGetDcNameRes_u.res0;
if (args.Flags & DS_FORCE_REDISCOVERY)
idmap_cfg_force_rediscovery();
/*
* We normally should wait if discovery is running.
* Sort of mis-using the background flag as a way to
* skip the wait, until we really do background disc.
*/
if ((args.Flags & DS_BACKGROUND_ONLY) == 0) {
timespec_t tv = { 15, 0 };
int rc = 0;
int waited = 0;
(void) mutex_lock(&_idmapdstate.addisc_lk);
if (_idmapdstate.addisc_st != 0)
idmapdlog(LOG_DEBUG, "getdcname wait begin");
while (_idmapdstate.addisc_st != 0) {
waited++;
rc = cond_reltimedwait(&_idmapdstate.addisc_cv,
&_idmapdstate.addisc_lk, &tv);
if (rc == ETIME)
break;
}
(void) mutex_unlock(&_idmapdstate.addisc_lk);
if (rc == ETIME) {
/* Caller will replace this with DC not found. */
idmapdlog(LOG_ERR, "getdcname timeout");
res->status = NT_STATUS_CANT_WAIT;
return (TRUE);
}
if (waited) {
idmapdlog(LOG_DEBUG, "getdcname wait done");
}
}
RDLOCK_CONFIG();
pgcfg = &_idmapdstate.cfg->pgcfg;
if (pgcfg->domain_name == NULL) {
res->status = NT_STATUS_INVALID_SERVER_STATE;
goto out;
}
if (args.DomainName != NULL && args.DomainName[0] != '\0' &&
0 != strcasecmp(args.DomainName, pgcfg->domain_name)) {
/*
* They asked for a specific domain not our primary,
* which is not supported (and not needed).
*/
res->status = NT_STATUS_NO_SUCH_DOMAIN;
goto out;
}
if ((ds = pgcfg->domain_controller) == NULL) {
res->status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
goto out;
}
dci->dci_DcName = strdup(ds->host);
if (dci->dci_DcName == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
dci->dci_DcAddr = calloc(1, INET6_ADDRSTRLEN);
if (dci->dci_DcAddr == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
if (ad_disc_getnameinfo(dci->dci_DcAddr, INET6_ADDRSTRLEN,
&ds->addr) == 0)
dci->dci_AddrType = DS_INET_ADDRESS;
if ((s = pgcfg->domain_guid) != NULL &&
0 == uuid_parse(s, uuid)) {
(void) memcpy(dci->dci_guid, uuid, sizeof (uuid));
}
if ((s = pgcfg->domain_name) != NULL) {
dci->dci_DomainName = strdup(s);
if (dci->dci_DomainName == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
}
if ((s = pgcfg->forest_name) != NULL) {
dci->dci_DnsForestName = strdup(s);
if (dci->dci_DnsForestName == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
}
dci->dci_Flags = ds->flags;
dci->dci_DcSiteName = strdup(ds->site);
if (dci->dci_DcSiteName == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
if ((s = pgcfg->site_name) != NULL) {
dci->dci_ClientSiteName = strdup(s);
if (dci->dci_ClientSiteName == NULL) {
res->status = NT_STATUS_NO_MEMORY;
goto out;
}
}
/* Address in binary form too. */
(void) memcpy(&dci->dci_sockaddr,
&ds->addr, ADSPRIV_SOCKADDR_LEN);
out:
UNLOCK_CONFIG();
if (res->status != 0) {
/* Caller will free only if status == 0 */
xdr_free(xdr_adspriv_dcinfo, (char *)dci);
}
return (TRUE);
}
/* ARGSUSED */
int
adspriv_program_1_freeresult(SVCXPRT *xprt, xdrproc_t fun, caddr_t res)
{
xdr_free(fun, res);
return (TRUE);
}
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#include "ads_priv.h"
#include <stdio.h>
#include <stdlib.h> /* getenv, exit */
#include <signal.h>
#include <rpc/pmap_clnt.h> /* for pmap_unset */
#include <string.h> /* strcmp */
#include <unistd.h> /* setsid */
#include <sys/types.h>
#include <memory.h>
#include <stropts.h>
#include <sys/resource.h> /* rlimit */
#include <syslog.h>
#ifndef SIG_PF
#define SIG_PF void(*)(int)
#endif
#ifdef DEBUG
#define RPC_SVC_FG
#endif
#define _RPCSVC_CLOSEDOWN 120
/*
* Copyright 2014 Nexenta Systems, Inc. All rights reserved.
*/
/*
* from ads_priv.x
* Active Directory Services (ADS) Private interface between
* libads and the ADS deamon. (RPC over doors)
*/
/*
* Server side stubs for the ADS API
*/
extern int _rpcpmstart; /* Started by a port monitor ? */
/* States a server can be in wrt request */
#define _IDLE 0
#define _SERVED 1
/* LINTED static unused if no main */
static int _rpcsvcstate = _IDLE; /* Set when a request is serviced */
static int _rpcsvccount = 0; /* Number of requests being serviced */
extern mutex_t _svcstate_lock; /* lock for _rpcsvcstate, _rpcsvccount */
#if defined(RPC_MSGOUT)
extern void RPC_MSGOUT(const char *, ...);
#else /* defined(RPC_MSGOUT) */
static void
RPC_MSGOUT(const char *fmt, char *msg)
{
#ifdef RPC_SVC_FG
if (_rpcpmstart)
syslog(LOG_ERR, fmt, msg);
else {
(void) fprintf(stderr, fmt, msg);
(void) putc('\n', stderr);
}
#else
syslog(LOG_ERR, fmt, msg);
#endif
}
#endif /* defined(RPC_MSGOUT) */
/* ARGSUSED */
int
_adspriv_null_1(
void *argp,
void *result,
struct svc_req *rqstp)
{
return (adspriv_null_1_svc(result, rqstp));
}
int
_adspriv_forcerediscovery_1(
DsForceRediscoveryArgs *argp,
int *result,
struct svc_req *rqstp)
{
return (adspriv_forcerediscovery_1_svc(*argp, result, rqstp));
}
int
_adspriv_getdcname_1(
DsGetDcNameArgs *argp,
DsGetDcNameRes *result,
struct svc_req *rqstp)
{
return (adspriv_getdcname_1_svc(*argp, result, rqstp));
}
void
adspriv_program_1(struct svc_req *rqstp, register SVCXPRT *transp)
{
union {
DsForceRediscoveryArgs adspriv_forcerediscovery_1_arg;
DsGetDcNameArgs adspriv_getdcname_1_arg;
} argument;
union {
int adspriv_forcerediscovery_1_res;
DsGetDcNameRes adspriv_getdcname_1_res;
} result;
bool_t retval;
xdrproc_t _xdr_argument, _xdr_result;
bool_t (*local)(char *, void *, struct svc_req *);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount++;
(void) mutex_unlock(&_svcstate_lock);
switch (rqstp->rq_proc) {
case ADSPRIV_NULL:
_xdr_argument = (xdrproc_t)
xdr_void;
_xdr_result = (xdrproc_t)
xdr_void;
local = (bool_t (*) (char *, void *, struct svc_req *))
_adspriv_null_1;
break;
case ADSPRIV_ForceRediscovery:
_xdr_argument = (xdrproc_t)
xdr_DsForceRediscoveryArgs;
_xdr_result = (xdrproc_t)
xdr_int;
local = (bool_t (*) (char *, void *, struct svc_req *))
_adspriv_forcerediscovery_1;
break;
case ADSPRIV_GetDcName:
_xdr_argument = (xdrproc_t)
xdr_DsGetDcNameArgs;
_xdr_result = (xdrproc_t)
xdr_DsGetDcNameRes;
local = (bool_t (*) (char *, void *, struct svc_req *))
_adspriv_getdcname_1;
break;
default:
svcerr_noproc(transp);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
(void) memset((char *)&argument, 0, sizeof (argument));
if (!svc_getargs(transp, _xdr_argument, (caddr_t)&argument)) {
svcerr_decode(transp);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
retval = (bool_t)(*local)((char *)&argument, (void *)&result, rqstp);
if (_xdr_result && retval > 0 &&
!svc_sendreply(transp, _xdr_result, (char *)&result)) {
svcerr_systemerr(transp);
}
if (!svc_freeargs(transp, _xdr_argument, (caddr_t)&argument)) {
RPC_MSGOUT("%s",
"unable to free arguments");
exit(1);
}
if (_xdr_result != NULL) {
if (!adspriv_program_1_freeresult(transp, _xdr_result,
(caddr_t)&result))
RPC_MSGOUT("%s",
"unable to free results");
}
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Processes name2sid & sid2name batched lookups for a given user or
* computer from an AD Directory server using GSSAPI authentication
*/
#include <stdio.h>
#include <stdlib.h>
#include <alloca.h>
#include <string.h>
#include <strings.h>
#include <lber.h>
#include <ldap.h>
#include <sasl/sasl.h>
#include <string.h>
#include <ctype.h>
#include <pthread.h>
#include <synch.h>
#include <atomic.h>
#include <errno.h>
#include <assert.h>
#include <limits.h>
#include <time.h>
#include <sys/u8_textprep.h>
#include "libadutils.h"
#include "nldaputils.h"
#include "idmapd.h"
/* Attribute names and filter format strings */
#define SAN "sAMAccountName"
#define OBJSID "objectSid"
#define OBJCLASS "objectClass"
#define UIDNUMBER "uidNumber"
#define GIDNUMBER "gidNumber"
#define UIDNUMBERFILTER "(&(objectclass=user)(uidNumber=%u))"
#define GIDNUMBERFILTER "(&(objectclass=group)(gidNumber=%u))"
#define SANFILTER "(sAMAccountName=%s)"
#define OBJSIDFILTER "(|(objectSid=%s)(sIDHistory=%s))"
void idmap_ldap_res_search_cb(LDAP *ld, LDAPMessage **res, int rc,
int qid, void *argp);
/*
* A place to put the results of a batched (async) query
*
* There is one of these for every query added to a batch object
* (idmap_query_state, see below).
*/
typedef struct idmap_q {
/*
* data used for validating search result entries for name->SID
* lookups
*/
char *ecanonname; /* expected canon name */
char *edomain; /* expected domain name */
idmap_id_type esidtype; /* expected SID type */
/* results */
char **canonname; /* actual canon name */
char **domain; /* name of domain of object */
char **sid; /* stringified SID */
rid_t *rid; /* RID */
idmap_id_type *sid_type; /* user or group SID? */
char **unixname; /* unixname for name mapping */
char **dn; /* DN of entry */
char **attr; /* Attr for name mapping */
char **value; /* value for name mapping */
posix_id_t *pid; /* Posix ID found via IDMU */
idmap_retcode *rc;
adutils_rc ad_rc;
adutils_result_t *result;
/*
* The LDAP search entry result is placed here to be processed
* when the search done result is received.
*/
LDAPMessage *search_res; /* The LDAP search result */
} idmap_q_t;
/* Batch context structure; typedef is in header file */
struct idmap_query_state {
adutils_query_state_t *qs;
int qsize; /* Queue size */
uint32_t qcount; /* Number of queued requests */
const char *ad_unixuser_attr;
const char *ad_unixgroup_attr;
int directory_based_mapping; /* enum */
char *default_domain;
idmap_q_t queries[1]; /* array of query results */
};
static pthread_t reaperid = 0;
/*
* Keep connection management simple for now, extend or replace later
* with updated libsldap code.
*/
#define ADREAPERSLEEP 60
/*
* Idle connection reaping side of connection management
*
* Every minute wake up and look for connections that have been idle for
* five minutes or more and close them.
*/
/*ARGSUSED*/
static
void *
adreaper(void *arg __unused)
{
timespec_t ts;
ts.tv_sec = ADREAPERSLEEP;
ts.tv_nsec = 0;
for (;;) {
/*
* nanosleep(3C) is thread-safe (no SIGALRM) and more
* portable than usleep(3C)
*/
(void) nanosleep(&ts, NULL);
adutils_reap_idle_connections();
}
return (NULL);
}
/*
* Take ad_host_config_t information, create a ad_host_t,
* populate it and add it to the list of hosts.
*/
int
idmap_add_ds(adutils_ad_t *ad, const char *host, int port)
{
int ret = -1;
if (adutils_add_ds(ad, host, port) == ADUTILS_SUCCESS)
ret = 0;
/* Start reaper if it doesn't exist */
if (ret == 0 && reaperid == 0)
(void) pthread_create(&reaperid, NULL, adreaper, NULL);
return (ret);
}
static
idmap_retcode
map_adrc2idmaprc(adutils_rc adrc)
{
switch (adrc) {
case ADUTILS_SUCCESS:
return (IDMAP_SUCCESS);
case ADUTILS_ERR_NOTFOUND:
return (IDMAP_ERR_NOTFOUND);
case ADUTILS_ERR_MEMORY:
return (IDMAP_ERR_MEMORY);
case ADUTILS_ERR_DOMAIN:
return (IDMAP_ERR_DOMAIN);
case ADUTILS_ERR_OTHER:
return (IDMAP_ERR_OTHER);
case ADUTILS_ERR_RETRIABLE_NET_ERR:
return (IDMAP_ERR_RETRIABLE_NET_ERR);
default:
return (IDMAP_ERR_INTERNAL);
}
/* NOTREACHED */
}
idmap_retcode
idmap_lookup_batch_start(adutils_ad_t *ad, int nqueries,
int directory_based_mapping, const char *default_domain,
idmap_query_state_t **state)
{
idmap_query_state_t *new_state;
adutils_rc rc;
*state = NULL;
assert(ad != NULL);
new_state = calloc(1, sizeof (idmap_query_state_t) +
(nqueries - 1) * sizeof (idmap_q_t));
if (new_state == NULL)
return (IDMAP_ERR_MEMORY);
if ((rc = adutils_lookup_batch_start(ad, nqueries,
idmap_ldap_res_search_cb, new_state, &new_state->qs))
!= ADUTILS_SUCCESS) {
idmap_lookup_release_batch(&new_state);
return (map_adrc2idmaprc(rc));
}
new_state->default_domain = strdup(default_domain);
if (new_state->default_domain == NULL) {
idmap_lookup_release_batch(&new_state);
return (IDMAP_ERR_MEMORY);
}
new_state->directory_based_mapping = directory_based_mapping;
new_state->qsize = nqueries;
*state = new_state;
return (IDMAP_SUCCESS);
}
/*
* Set unixuser_attr and unixgroup_attr for AD-based name mapping
*/
void
idmap_lookup_batch_set_unixattr(idmap_query_state_t *state,
const char *unixuser_attr, const char *unixgroup_attr)
{
state->ad_unixuser_attr = unixuser_attr;
state->ad_unixgroup_attr = unixgroup_attr;
}
/*
* Take parsed attribute values from a search result entry and check if
* it is the result that was desired and, if so, set the result fields
* of the given idmap_q_t.
*
* Except for dn and attr, all strings are consumed, either by transferring
* them over into the request results (where the caller will eventually free
* them) or by freeing them here. Note that this aligns with the "const"
* declarations below.
*/
static
void
idmap_setqresults(
idmap_q_t *q,
char *san,
const char *dn,
const char *attr,
char *value,
char *sid,
rid_t rid,
int sid_type,
char *unixname,
posix_id_t pid)
{
char *domain;
int err1;
assert(dn != NULL);
if ((domain = adutils_dn2dns(dn)) == NULL)
goto out;
if (q->ecanonname != NULL && san != NULL) {
/* Check that this is the canonname that we were looking for */
if (u8_strcmp(q->ecanonname, san, 0,
U8_STRCMP_CI_LOWER, /* no normalization, for now */
U8_UNICODE_LATEST, &err1) != 0 || err1 != 0)
goto out;
}
if (q->edomain != NULL) {
/* Check that this is the domain that we were looking for */
if (!domain_eq(q->edomain, domain))
goto out;
}
/* Copy the DN and attr and value */
if (q->dn != NULL)
*q->dn = strdup(dn);
if (q->attr != NULL && attr != NULL)
*q->attr = strdup(attr);
if (q->value != NULL && value != NULL) {
*q->value = value;
value = NULL;
}
/* Set results */
if (q->sid) {
*q->sid = sid;
sid = NULL;
}
if (q->rid)
*q->rid = rid;
if (q->sid_type)
*q->sid_type = sid_type;
if (q->unixname) {
*q->unixname = unixname;
unixname = NULL;
}
if (q->domain != NULL) {
*q->domain = domain;
domain = NULL;
}
if (q->canonname != NULL) {
/*
* The caller may be replacing the given winname by its
* canonical name and therefore free any old name before
* overwriting the field by the canonical name.
*/
free(*q->canonname);
*q->canonname = san;
san = NULL;
}
if (q->pid != NULL && pid != IDMAP_SENTINEL_PID) {
*q->pid = pid;
}
q->ad_rc = ADUTILS_SUCCESS;
out:
/* Free unused attribute values */
free(san);
free(sid);
free(domain);
free(unixname);
free(value);
}
#define BVAL_CASEEQ(bv, str) \
(((*(bv))->bv_len == (sizeof (str) - 1)) && \
strncasecmp((*(bv))->bv_val, str, (*(bv))->bv_len) == 0)
/*
* Extract the class of the result entry. Returns 1 on success, 0 on
* failure.
*/
static
int
idmap_bv_objclass2sidtype(BerValue **bvalues, int *sid_type)
{
BerValue **cbval;
*sid_type = IDMAP_SID;
if (bvalues == NULL)
return (0);
/*
* We consider Computer to be a subclass of User, so we can just
* ignore Computer entries and pay attention to the accompanying
* User entries.
*/
for (cbval = bvalues; *cbval != NULL; cbval++) {
if (BVAL_CASEEQ(cbval, "group")) {
*sid_type = IDMAP_GSID;
break;
} else if (BVAL_CASEEQ(cbval, "user")) {
*sid_type = IDMAP_USID;
break;
}
/*
* "else if (*sid_type = IDMAP_USID)" then this is a
* new sub-class of user -- what to do with it??
*/
}
return (1);
}
/*
* Handle a given search result entry
*/
static
void
idmap_extract_object(idmap_query_state_t *state, idmap_q_t *q,
LDAPMessage *res, LDAP *ld)
{
BerValue **bvalues;
const char *attr = NULL;
char *value = NULL;
char *unix_name = NULL;
char *dn;
char *san = NULL;
char *sid = NULL;
rid_t rid = 0;
int sid_type;
int ok;
posix_id_t pid = IDMAP_SENTINEL_PID;
assert(q->rc != NULL);
assert(q->domain == NULL || *q->domain == NULL);
if ((dn = ldap_get_dn(ld, res)) == NULL)
return;
bvalues = ldap_get_values_len(ld, res, OBJCLASS);
if (bvalues == NULL) {
/*
* Didn't find objectclass. Something's wrong with our
* AD data.
*/
idmapdlog(LOG_ERR, "%s has no %s", dn, OBJCLASS);
goto out;
}
ok = idmap_bv_objclass2sidtype(bvalues, &sid_type);
ldap_value_free_len(bvalues);
if (!ok) {
/*
* Didn't understand objectclass. Something's wrong with our
* AD data.
*/
idmapdlog(LOG_ERR, "%s has unexpected %s", dn, OBJCLASS);
goto out;
}
if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU &&
q->pid != NULL) {
if (sid_type == IDMAP_USID)
attr = UIDNUMBER;
else if (sid_type == IDMAP_GSID)
attr = GIDNUMBER;
if (attr != NULL) {
bvalues = ldap_get_values_len(ld, res, attr);
if (bvalues != NULL) {
value = adutils_bv_str(bvalues[0]);
if (!adutils_bv_uint(bvalues[0], &pid)) {
idmapdlog(LOG_ERR,
"%s has Invalid %s value \"%s\"",
dn, attr, value);
}
ldap_value_free_len(bvalues);
}
}
}
if (state->directory_based_mapping == DIRECTORY_MAPPING_NAME &&
q->unixname != NULL) {
/*
* If the caller has requested unixname then determine the
* AD attribute name that will have the unixname, and retrieve
* its value.
*/
idmap_id_type esidtype;
/*
* Determine the target type.
*
* If the caller specified one, use that. Otherwise, give the
* same type that as we found for the Windows user.
*/
esidtype = q->esidtype;
if (esidtype == IDMAP_SID)
esidtype = sid_type;
if (esidtype == IDMAP_USID)
attr = state->ad_unixuser_attr;
else if (esidtype == IDMAP_GSID)
attr = state->ad_unixgroup_attr;
if (attr != NULL) {
bvalues = ldap_get_values_len(ld, res, attr);
if (bvalues != NULL) {
unix_name = adutils_bv_str(bvalues[0]);
ldap_value_free_len(bvalues);
value = strdup(unix_name);
}
}
}
bvalues = ldap_get_values_len(ld, res, SAN);
if (bvalues != NULL) {
san = adutils_bv_str(bvalues[0]);
ldap_value_free_len(bvalues);
}
if (q->sid != NULL) {
bvalues = ldap_get_values_len(ld, res, OBJSID);
if (bvalues != NULL) {
sid = adutils_bv_objsid2sidstr(bvalues[0], &rid);
ldap_value_free_len(bvalues);
}
}
idmap_setqresults(q, san, dn,
attr, value,
sid, rid, sid_type,
unix_name, pid);
out:
ldap_memfree(dn);
}
void
idmap_ldap_res_search_cb(LDAP *ld, LDAPMessage **res, int rc, int qid,
void *argp)
{
idmap_query_state_t *state = (idmap_query_state_t *)argp;
idmap_q_t *q = &(state->queries[qid]);
switch (rc) {
case LDAP_RES_SEARCH_RESULT:
if (q->search_res != NULL) {
idmap_extract_object(state, q, q->search_res, ld);
(void) ldap_msgfree(q->search_res);
q->search_res = NULL;
} else
q->ad_rc = ADUTILS_ERR_NOTFOUND;
break;
case LDAP_RES_SEARCH_ENTRY:
if (q->search_res == NULL) {
q->search_res = *res;
*res = NULL;
}
break;
default:
break;
}
}
static
void
idmap_cleanup_batch(idmap_query_state_t *batch)
{
int i;
for (i = 0; i < batch->qcount; i++) {
if (batch->queries[i].ecanonname != NULL)
free(batch->queries[i].ecanonname);
batch->queries[i].ecanonname = NULL;
if (batch->queries[i].edomain != NULL)
free(batch->queries[i].edomain);
batch->queries[i].edomain = NULL;
}
}
/*
* This routine frees the idmap_query_state_t structure
*/
void
idmap_lookup_release_batch(idmap_query_state_t **state)
{
if (state == NULL || *state == NULL)
return;
adutils_lookup_batch_release(&(*state)->qs);
idmap_cleanup_batch(*state);
free((*state)->default_domain);
free(*state);
*state = NULL;
}
idmap_retcode
idmap_lookup_batch_end(idmap_query_state_t **state)
{
adutils_rc ad_rc;
int i;
idmap_query_state_t *id_qs = *state;
ad_rc = adutils_lookup_batch_end(&id_qs->qs);
/*
* Map adutils rc to idmap_retcode in each
* query because consumers in dbutils.c
* expects idmap_retcode.
*/
for (i = 0; i < id_qs->qcount; i++) {
*id_qs->queries[i].rc =
map_adrc2idmaprc(id_qs->queries[i].ad_rc);
}
idmap_lookup_release_batch(state);
return (map_adrc2idmaprc(ad_rc));
}
/*
* Send one prepared search, queue up msgid, process what results are
* available
*/
static
idmap_retcode
idmap_batch_add1(idmap_query_state_t *state, const char *filter,
char *ecanonname, char *edomain, idmap_id_type esidtype,
char **dn, char **attr, char **value,
char **canonname, char **dname,
char **sid, rid_t *rid, idmap_id_type *sid_type, char **unixname,
posix_id_t *pid,
idmap_retcode *rc)
{
adutils_rc ad_rc;
int qid, i;
idmap_q_t *q;
char *attrs[20]; /* Plenty */
qid = atomic_inc_32_nv(&state->qcount) - 1;
q = &(state->queries[qid]);
assert(qid < state->qsize);
/*
* Remember the expected canonname, domainname and unix type
* so we can check the results * against it
*/
q->ecanonname = ecanonname;
q->edomain = edomain;
q->esidtype = esidtype;
/* Remember where to put the results */
q->canonname = canonname;
q->sid = sid;
q->domain = dname;
q->rid = rid;
q->sid_type = sid_type;
q->rc = rc;
q->unixname = unixname;
q->dn = dn;
q->attr = attr;
q->value = value;
q->pid = pid;
/* Add attributes that are not always needed */
i = 0;
attrs[i++] = SAN;
attrs[i++] = OBJSID;
attrs[i++] = OBJCLASS;
if (unixname != NULL) {
/* Add unixuser/unixgroup attribute names to the attrs list */
if (esidtype != IDMAP_GSID &&
state->ad_unixuser_attr != NULL)
attrs[i++] = (char *)state->ad_unixuser_attr;
if (esidtype != IDMAP_USID &&
state->ad_unixgroup_attr != NULL)
attrs[i++] = (char *)state->ad_unixgroup_attr;
}
if (pid != NULL) {
if (esidtype != IDMAP_GSID)
attrs[i++] = UIDNUMBER;
if (esidtype != IDMAP_USID)
attrs[i++] = GIDNUMBER;
}
attrs[i] = NULL;
/*
* Provide sane defaults for the results in case we never hear
* back from the DS before closing the connection.
*
* In particular we default the result to indicate a retriable
* error. The first complete matching result entry will cause
* this to be set to IDMAP_SUCCESS, and the end of the results
* for this search will cause this to indicate "not found" if no
* result entries arrived or no complete ones matched the lookup
* we were doing.
*/
*rc = IDMAP_ERR_RETRIABLE_NET_ERR;
if (sid_type != NULL)
*sid_type = IDMAP_SID;
if (sid != NULL)
*sid = NULL;
if (dname != NULL)
*dname = NULL;
if (rid != NULL)
*rid = 0;
if (dn != NULL)
*dn = NULL;
if (attr != NULL)
*attr = NULL;
if (value != NULL)
*value = NULL;
/*
* Don't set *canonname to NULL because it may be pointing to the
* given winname. Later on if we get a canonical name from AD the
* old name if any will be freed before assigning the new name.
*/
/*
* Invoke the mother of all APIs i.e. the adutils API
*/
ad_rc = adutils_lookup_batch_add(state->qs, filter,
(const char **)attrs,
edomain, &q->result, &q->ad_rc);
return (map_adrc2idmaprc(ad_rc));
}
idmap_retcode
idmap_name2sid_batch_add1(idmap_query_state_t *state,
const char *name, const char *dname, idmap_id_type esidtype,
char **dn, char **attr, char **value,
char **canonname, char **sid, rid_t *rid,
idmap_id_type *sid_type, char **unixname,
posix_id_t *pid, idmap_retcode *rc)
{
idmap_retcode retcode;
char *filter, *s_name;
char *ecanonname, *edomain; /* expected canonname */
/*
* Strategy: search the global catalog for user/group by
* sAMAccountName = user/groupname with "" as the base DN and by
* userPrincipalName = user/groupname@domain. The result
* entries will be checked to conform to the name and domain
* name given here. The DN, sAMAccountName, userPrincipalName,
* objectSid and objectClass of the result entries are all we
* need to figure out which entries match the lookup, the SID of
* the user/group and whether it is a user or a group.
*/
if ((ecanonname = strdup(name)) == NULL)
return (IDMAP_ERR_MEMORY);
if (dname == NULL || *dname == '\0') {
/* 'name' not qualified and dname not given */
dname = state->default_domain;
edomain = strdup(dname);
if (edomain == NULL) {
free(ecanonname);
return (IDMAP_ERR_MEMORY);
}
} else {
if ((edomain = strdup(dname)) == NULL) {
free(ecanonname);
return (IDMAP_ERR_MEMORY);
}
}
if (!adutils_lookup_check_domain(state->qs, dname)) {
free(ecanonname);
free(edomain);
return (IDMAP_ERR_DOMAIN_NOTFOUND);
}
s_name = sanitize_for_ldap_filter(name);
if (s_name == NULL) {
free(ecanonname);
free(edomain);
return (IDMAP_ERR_MEMORY);
}
/* Assemble filter */
(void) asprintf(&filter, SANFILTER, s_name);
if (s_name != name)
free(s_name);
if (filter == NULL) {
free(ecanonname);
free(edomain);
return (IDMAP_ERR_MEMORY);
}
retcode = idmap_batch_add1(state, filter, ecanonname, edomain,
esidtype, dn, attr, value, canonname, NULL, sid, rid, sid_type,
unixname, pid, rc);
free(filter);
return (retcode);
}
idmap_retcode
idmap_sid2name_batch_add1(idmap_query_state_t *state,
const char *sid, const rid_t *rid, idmap_id_type esidtype,
char **dn, char **attr, char **value,
char **name, char **dname, idmap_id_type *sid_type,
char **unixname, posix_id_t *pid, idmap_retcode *rc)
{
idmap_retcode retcode;
int ret;
char *filter;
char cbinsid[ADUTILS_MAXHEXBINSID + 1];
/*
* Strategy: search [the global catalog] for user/group by
* objectSid = SID with empty base DN. The DN, sAMAccountName
* and objectClass of the result are all we need to figure out
* the name of the SID and whether it is a user, a group or a
* computer.
*/
if (!adutils_lookup_check_sid_prefix(state->qs, sid))
return (IDMAP_ERR_DOMAIN_NOTFOUND);
ret = adutils_txtsid2hexbinsid(sid, rid, &cbinsid[0], sizeof (cbinsid));
if (ret != 0)
return (IDMAP_ERR_SID);
/* Assemble filter */
(void) asprintf(&filter, OBJSIDFILTER, cbinsid, cbinsid);
if (filter == NULL)
return (IDMAP_ERR_MEMORY);
retcode = idmap_batch_add1(state, filter, NULL, NULL, esidtype,
dn, attr, value, name, dname, NULL, NULL, sid_type, unixname,
pid, rc);
free(filter);
return (retcode);
}
idmap_retcode
idmap_unixname2sid_batch_add1(idmap_query_state_t *state,
const char *unixname, int is_user, int is_wuser,
char **dn, char **attr, char **value,
char **sid, rid_t *rid, char **name,
char **dname, idmap_id_type *sid_type, idmap_retcode *rc)
{
idmap_retcode retcode;
char *filter, *s_unixname;
const char *attrname;
/* Get unixuser or unixgroup AD attribute name */
attrname = (is_user) ?
state->ad_unixuser_attr : state->ad_unixgroup_attr;
if (attrname == NULL)
return (IDMAP_ERR_NOTFOUND);
s_unixname = sanitize_for_ldap_filter(unixname);
if (s_unixname == NULL)
return (IDMAP_ERR_MEMORY);
/* Assemble filter */
(void) asprintf(&filter, "(&(objectclass=%s)(%s=%s))",
is_wuser ? "user" : "group", attrname, s_unixname);
if (s_unixname != unixname)
free(s_unixname);
if (filter == NULL) {
return (IDMAP_ERR_MEMORY);
}
retcode = idmap_batch_add1(state, filter, NULL, NULL,
IDMAP_POSIXID, dn, NULL, NULL, name, dname, sid, rid, sid_type,
NULL, NULL, rc);
if (retcode == IDMAP_SUCCESS && attr != NULL) {
if ((*attr = strdup(attrname)) == NULL)
retcode = IDMAP_ERR_MEMORY;
}
if (retcode == IDMAP_SUCCESS && value != NULL) {
if ((*value = strdup(unixname)) == NULL)
retcode = IDMAP_ERR_MEMORY;
}
free(filter);
return (retcode);
}
idmap_retcode
idmap_pid2sid_batch_add1(idmap_query_state_t *state,
posix_id_t pid, int is_user,
char **dn, char **attr, char **value,
char **sid, rid_t *rid, char **name,
char **dname, idmap_id_type *sid_type, idmap_retcode *rc)
{
idmap_retcode retcode;
char *filter;
const char *attrname;
/* Assemble filter */
if (is_user) {
(void) asprintf(&filter, UIDNUMBERFILTER, pid);
attrname = UIDNUMBER;
} else {
(void) asprintf(&filter, GIDNUMBERFILTER, pid);
attrname = GIDNUMBER;
}
if (filter == NULL)
return (IDMAP_ERR_MEMORY);
retcode = idmap_batch_add1(state, filter, NULL, NULL,
IDMAP_POSIXID, dn, NULL, NULL, name, dname, sid, rid, sid_type,
NULL, NULL, rc);
if (retcode == IDMAP_SUCCESS && attr != NULL) {
if ((*attr = strdup(attrname)) == NULL)
retcode = IDMAP_ERR_MEMORY;
}
if (retcode == IDMAP_SUCCESS && value != NULL) {
(void) asprintf(value, "%u", pid);
if (*value == NULL)
retcode = IDMAP_ERR_MEMORY;
}
free(filter);
return (retcode);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
*/
#ifndef _ADUTILS_H
#define _ADUTILS_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Processes name2sid & sid2name lookups for a given user or computer
* from an AD Difrectory server using GSSAPI authentication
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <lber.h>
#include <ldap.h>
#include <sasl/sasl.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <time.h>
#include <thread.h>
#include <synch.h>
#include <rpcsvc/idmap_prot.h>
#include "libadutils.h"
#include <sys/idmap.h>
/*
* idmapd interfaces stolen? from other idmapd code?
*/
typedef uint32_t rid_t;
typedef uid_t posix_id_t;
typedef struct idmap_query_state idmap_query_state_t;
int idmap_add_ds(adutils_ad_t *ad, const char *host, int port);
/*
* Batch lookups
*
* Start a batch, add queries to the batch one by one (the output
* pointers should all differ, so that a query's results don't clobber
* any other's), end the batch to wait for replies for all outstanding
* queries. The output parameters of each query are initialized to NULL
* or -1 as appropriate.
*
* LDAP searches are sent one by one without waiting (i.e., blocking)
* for replies. Replies are handled as soon as they are available.
* Missing replies are waited for only when idmap_lookup_batch_end() is
* called.
*
* If an add1 function returns != 0 then abort the batch by calling
* idmap_lookup_batch_end(), but note that some queries may have been
* answered, so check the result code of each query.
*/
/* Start a batch of lookups */
idmap_retcode idmap_lookup_batch_start(adutils_ad_t *ad, int nqueries,
int directory_based_mapping, const char *default_domain,
idmap_query_state_t **state);
/* End a batch and release its idmap_query_state_t object */
idmap_retcode idmap_lookup_batch_end(idmap_query_state_t **state);
/* Abandon a batch and release its idmap_query_state_t object */
void idmap_lookup_release_batch(idmap_query_state_t **state);
/*
* Add a name->SID lookup
*
* - 'dname' is optional; if NULL or empty string then 'name' has to be
* a user/group name qualified wih a domainname (e.g., foo@domain),
* else the 'name' must not be qualified and the domainname must be
* passed in 'dname'.
*
* - if 'rid' is NULL then the output SID string will include the last
* RID, else it won't and the last RID value will be stored in *rid.
*
* The caller must free() *sid.
*/
idmap_retcode idmap_name2sid_batch_add1(idmap_query_state_t *state,
const char *name, const char *dname, idmap_id_type esidtype,
char **dn, char **attr, char **value, char **canonname,
char **sid, rid_t *rid, idmap_id_type *sid_type,
char **unixname,
posix_id_t *pid, idmap_retcode *rc);
/*
* Add a SID->name lookup
*
* - 'rid' is optional; if NULL then 'sid' is expected to have the
* user/group RID present, else 'sid' is expected not to have it, and
* *rid will be used to qualify the given 'sid'
*
* - 'dname' is optional; if NULL then the fully qualified user/group
* name will be stored in *name, else the domain name will be stored in
* *dname and the user/group name will be stored in *name without a
* domain qualifier.
*
* The caller must free() *name and *dname (if present).
*/
idmap_retcode idmap_sid2name_batch_add1(idmap_query_state_t *state,
const char *sid, const rid_t *rid, idmap_id_type esidtype,
char **dn, char **attr, char **value, char **name,
char **dname, idmap_id_type *sid_type, char **unixname,
posix_id_t *pid, idmap_retcode *rc);
/*
* Add a unixname->SID lookup
*/
idmap_retcode idmap_unixname2sid_batch_add1(idmap_query_state_t *state,
const char *unixname, int is_user, int is_wuser,
char **dn, char **attr, char **value, char **sid, rid_t *rid,
char **name, char **dname, idmap_id_type *sid_type,
idmap_retcode *rc);
/*
* Add a PID->SID lookup
*/
idmap_retcode idmap_pid2sid_batch_add1(idmap_query_state_t *state,
posix_id_t pid, int is_user,
char **dn, char **attr, char **value, char **sid, rid_t *rid,
char **name, char **dname, idmap_id_type *sid_type,
idmap_retcode *rc);
/*
* Set unixname attribute names for the batch for AD-based name mapping
*/
void idmap_lookup_batch_set_unixattr(idmap_query_state_t *state,
const char *unixuser_attr, const char *unixgroup_attr);
#ifdef __cplusplus
}
#endif
#endif /* _ADUTILS_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2016 Nexenta Systems, Inc. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
* Copyright 2025 Bill Sommerfeld
*/
/*
* Database related utility routines
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <rpc/rpc.h>
#include <sys/sid.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <pthread.h>
#include <assert.h>
#include <sys/u8_textprep.h>
#include <alloca.h>
#include <libuutil.h>
#include <note.h>
#include "idmapd.h"
#include "adutils.h"
#include "string.h"
#include "idmap_priv.h"
#include "schema.h"
#include "nldaputils.h"
#include "idmap_lsa.h"
static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
sqlite_vm **, int *, int, const char ***);
static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
const char *, char **, char **, idmap_rid_t *, idmap_id_type *);
#define EMPTY_NAME(name) (*name == 0 || strcmp(name, "\"\"") == 0)
#define DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
#define AVOID_NAMESERVICE(req)\
(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
#define ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
typedef enum init_db_option {
FAIL_IF_CORRUPT = 0,
REMOVE_IF_CORRUPT = 1
} init_db_option_t;
/*
* Thread specific data to hold the database handles so that the
* databases are not opened and closed for every request. It also
* contains the sqlite busy handler structure.
*/
struct idmap_busy {
const char *name;
const int *delays;
int delay_size;
int total;
int sec;
};
typedef struct idmap_tsd {
sqlite *db_db;
sqlite *cache_db;
struct idmap_busy cache_busy;
struct idmap_busy db_busy;
} idmap_tsd_t;
/*
* Flags to indicate how local the directory we're consulting is.
* If neither is set, it means the directory belongs to a remote forest.
*/
#define DOMAIN_IS_LOCAL 0x01
#define FOREST_IS_LOCAL 0x02
static const int cache_delay_table[] =
{ 1, 2, 5, 10, 15, 20, 25, 30, 35, 40,
50, 50, 60, 70, 80, 90, 100};
static const int db_delay_table[] =
{ 5, 10, 15, 20, 30, 40, 55, 70, 100};
static pthread_key_t idmap_tsd_key;
void
idmap_tsd_destroy(void *key)
{
idmap_tsd_t *tsd = (idmap_tsd_t *)key;
if (tsd) {
if (tsd->db_db)
(void) sqlite_close(tsd->db_db);
if (tsd->cache_db)
(void) sqlite_close(tsd->cache_db);
free(tsd);
}
}
void
idmap_init_tsd_key(void)
{
int rc;
rc = pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy);
assert(rc == 0);
}
idmap_tsd_t *
idmap_get_tsd(void)
{
idmap_tsd_t *tsd;
if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
/* No thread specific data so create it */
if ((tsd = malloc(sizeof (*tsd))) != NULL) {
/* Initialize thread specific data */
(void) memset(tsd, 0, sizeof (*tsd));
/* save the trhread specific data */
if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
/* Can't store key */
free(tsd);
tsd = NULL;
}
} else {
tsd = NULL;
}
}
return (tsd);
}
/*
* A simple wrapper around u8_textprep_str() that returns the Unicode
* lower-case version of some string. The result must be freed.
*/
char *
tolower_u8(const char *s)
{
char *res = NULL;
char *outs;
size_t inlen, outlen, inbytesleft, outbytesleft;
int rc, err;
/*
* u8_textprep_str() does not allocate memory. The input and
* output buffers may differ in size (though that would be more
* likely when normalization is done). We have to loop over it...
*
* To improve the chances that we can avoid looping we add 10
* bytes of output buffer room the first go around.
*/
inlen = inbytesleft = strlen(s);
outlen = outbytesleft = inlen + 10;
if ((res = malloc(outlen)) == NULL)
return (NULL);
outs = res;
while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
&outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
err == E2BIG) {
if ((res = realloc(res, outlen + inbytesleft)) == NULL)
return (NULL);
/* adjust input/output buffer pointers */
s += (inlen - inbytesleft);
outs = res + outlen - outbytesleft;
/* adjust outbytesleft and outlen */
outlen += inbytesleft;
outbytesleft += inbytesleft;
}
if (rc < 0) {
free(res);
res = NULL;
return (NULL);
}
res[outlen - outbytesleft] = '\0';
return (res);
}
static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
const char *while_doing);
/*
* Initialize 'dbname' using 'sql'
*/
static
int
init_db_instance(const char *dbname, int version,
const char *detect_version_sql, char * const *sql,
init_db_option_t opt, int *created, int *upgraded)
{
int rc, curr_version;
int tries = 1;
int prio = LOG_NOTICE;
sqlite *db = NULL;
char *errmsg = NULL;
*created = 0;
*upgraded = 0;
if (opt == REMOVE_IF_CORRUPT)
tries = 3;
rinse_repeat:
if (tries == 0) {
idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
return (-1);
}
if (tries-- == 1)
/* Last try, log errors */
prio = LOG_ERR;
db = sqlite_open(dbname, 0600, &errmsg);
if (db == NULL) {
idmapdlog(prio, "Error creating database %s (%s)",
dbname, CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
if (opt == REMOVE_IF_CORRUPT)
(void) unlink(dbname);
goto rinse_repeat;
}
sqlite_busy_timeout(db, 3000);
/* Detect current version of schema in the db, if any */
curr_version = 0;
if (detect_version_sql != NULL) {
char *end, **results;
int nrow;
#ifdef IDMAPD_DEBUG
(void) fprintf(stderr, "Schema version detection SQL: %s\n",
detect_version_sql);
#endif /* IDMAPD_DEBUG */
rc = sqlite_get_table(db, detect_version_sql, &results,
&nrow, NULL, &errmsg);
if (rc != SQLITE_OK) {
idmapdlog(prio,
"Error detecting schema version of db %s (%s)",
dbname, errmsg);
sqlite_freemem(errmsg);
sqlite_free_table(results);
sqlite_close(db);
return (-1);
}
if (nrow != 1) {
idmapdlog(prio,
"Error detecting schema version of db %s", dbname);
sqlite_close(db);
sqlite_free_table(results);
return (-1);
}
curr_version = strtol(results[1], &end, 10);
sqlite_free_table(results);
}
if (curr_version < 0) {
if (opt == REMOVE_IF_CORRUPT)
(void) unlink(dbname);
goto rinse_repeat;
}
if (curr_version == version)
goto done;
/* Install or upgrade schema */
#ifdef IDMAPD_DEBUG
(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
sql[curr_version]);
#endif /* IDMAPD_DEBUG */
rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
(curr_version == 0) ? "installing schema" : "upgrading schema");
if (rc != 0) {
idmapdlog(prio, "Error %s schema for db %s", dbname,
(curr_version == 0) ? "installing schema" :
"upgrading schema");
if (opt == REMOVE_IF_CORRUPT)
(void) unlink(dbname);
goto rinse_repeat;
}
*upgraded = (curr_version > 0);
*created = (curr_version == 0);
done:
(void) sqlite_close(db);
return (0);
}
/*
* This is the SQLite database busy handler that retries the SQL
* operation until it is successful.
*/
int
idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
{
struct idmap_busy *busy = arg;
int delay;
struct timespec rqtp;
if (count == 1) {
busy->total = 0;
busy->sec = 2;
}
if (busy->total > 1000 * busy->sec) {
idmapdlog(LOG_DEBUG,
"Thread %d waited %d sec for the %s database",
pthread_self(), busy->sec, busy->name);
busy->sec++;
}
if (count <= busy->delay_size) {
delay = busy->delays[count-1];
} else {
delay = busy->delays[busy->delay_size - 1];
}
busy->total += delay;
rqtp.tv_sec = 0;
rqtp.tv_nsec = MSEC2NSEC(delay);
(void) nanosleep(&rqtp, NULL);
return (1);
}
/*
* Get the database handle
*/
idmap_retcode
get_db_handle(sqlite **db)
{
char *errmsg;
idmap_tsd_t *tsd;
/*
* Retrieve the db handle from thread-specific storage
* If none exists, open and store in thread-specific storage.
*/
if ((tsd = idmap_get_tsd()) == NULL) {
idmapdlog(LOG_ERR,
"Error getting thread specific data for %s", IDMAP_DBNAME);
return (IDMAP_ERR_MEMORY);
}
if (tsd->db_db == NULL) {
tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
if (tsd->db_db == NULL) {
idmapdlog(LOG_ERR, "Error opening database %s (%s)",
IDMAP_DBNAME, CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
return (IDMAP_ERR_DB);
}
tsd->db_busy.name = IDMAP_DBNAME;
tsd->db_busy.delays = db_delay_table;
tsd->db_busy.delay_size = sizeof (db_delay_table) /
sizeof (int);
sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
&tsd->db_busy);
}
*db = tsd->db_db;
return (IDMAP_SUCCESS);
}
/*
* Force next get_db_handle to reopen.
* Called after DB errors.
*/
void
kill_db_handle(sqlite *db)
{
idmap_tsd_t *tsd;
sqlite *t;
if (db == NULL)
return;
if ((tsd = idmap_get_tsd()) == NULL)
return;
if ((t = tsd->db_db) == NULL)
return;
assert(t == db);
tsd->db_db = NULL;
(void) sqlite_close(t);
}
/*
* Get the cache handle
*/
idmap_retcode
get_cache_handle(sqlite **cache)
{
char *errmsg;
idmap_tsd_t *tsd;
/*
* Retrieve the db handle from thread-specific storage
* If none exists, open and store in thread-specific storage.
*/
if ((tsd = idmap_get_tsd()) == NULL) {
idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
IDMAP_DBNAME);
return (IDMAP_ERR_MEMORY);
}
if (tsd->cache_db == NULL) {
tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
if (tsd->cache_db == NULL) {
idmapdlog(LOG_ERR, "Error opening database %s (%s)",
IDMAP_CACHENAME, CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
return (IDMAP_ERR_DB);
}
tsd->cache_busy.name = IDMAP_CACHENAME;
tsd->cache_busy.delays = cache_delay_table;
tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
sizeof (int);
sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
&tsd->cache_busy);
}
*cache = tsd->cache_db;
return (IDMAP_SUCCESS);
}
/*
* Force next get_cache_handle to reopen.
* Called after DB errors.
*/
void
kill_cache_handle(sqlite *db)
{
idmap_tsd_t *tsd;
sqlite *t;
if (db == NULL)
return;
if ((tsd = idmap_get_tsd()) == NULL)
return;
if ((t = tsd->cache_db) == NULL)
return;
assert(t == db);
tsd->cache_db = NULL;
(void) sqlite_close(t);
}
/*
* Initialize cache and db
*/
int
init_dbs(void)
{
char *sql[4];
int created, upgraded;
/* name-based mappings; probably OK to blow away in a pinch(?) */
sql[0] = DB_INSTALL_SQL;
sql[1] = DB_UPGRADE_FROM_v1_SQL;
sql[2] = NULL;
if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
FAIL_IF_CORRUPT, &created, &upgraded) < 0)
return (-1);
/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
sql[0] = CACHE_INSTALL_SQL;
sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
sql[3] = NULL;
if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
return (-1);
/*
* TODO: If cache DB NOT created, get MAX PID for allocids(), eg.
* sql = "SELECT MAX(pid) as max_pid FROM idmap_cache;"
* sqlite_get_table(db, sql, &results, &nrow, NULL, &errmsg);
*
* However, the allocids() system call does not currently allow
* for this kind of initialization. Until that's dealt with,
* use of a persistent idmap cache DB cannot work.
*/
/* This becomes the "flush" flag for allocids() */
_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
return (0);
}
/*
* Finalize databases
*/
void
fini_dbs(void)
{
}
/*
* This table is a listing of status codes that will be returned to the
* client when a SQL command fails with the corresponding error message.
*/
static msg_table_t sqlmsgtable[] = {
{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
"columns unixname, is_user, u2w_order are not unique"},
{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
"columns winname, windomain, is_user, is_wuser, w2u_order are not"
" unique"},
{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
{-1, NULL}
};
/*
* idmapd's version of string2stat to map SQLite messages to
* status codes
*/
idmap_retcode
idmapd_string2stat(const char *msg)
{
int i;
for (i = 0; sqlmsgtable[i].msg; i++) {
if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
return (sqlmsgtable[i].retcode);
}
return (IDMAP_ERR_OTHER);
}
/*
* Executes some SQL in a transaction.
*
* Returns 0 on success, -1 if it failed but the rollback succeeded, -2
* if the rollback failed.
*/
static
int
sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
const char *while_doing)
{
char *errmsg = NULL;
int rc;
rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
if (rc != SQLITE_OK) {
idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
"while %s (%s)", errmsg, while_doing, dbname);
sqlite_freemem(errmsg);
return (-1);
}
rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
if (rc != SQLITE_OK) {
idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
while_doing, dbname);
sqlite_freemem(errmsg);
errmsg = NULL;
goto rollback;
}
rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
if (rc == SQLITE_OK) {
sqlite_freemem(errmsg);
return (0);
}
idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
errmsg, while_doing, dbname);
sqlite_freemem(errmsg);
errmsg = NULL;
rollback:
rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
if (rc != SQLITE_OK) {
idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
errmsg, while_doing, dbname);
sqlite_freemem(errmsg);
return (-2);
}
sqlite_freemem(errmsg);
return (-1);
}
/*
* Execute the given SQL statment without using any callbacks
*/
idmap_retcode
sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
{
char *errmsg = NULL;
int r;
idmap_retcode retcode;
r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
if (r != SQLITE_OK) {
idmapdlog(LOG_ERR, "Database error on %s while executing %s "
"(%s)", dbname, sql, CHECK_NULL(errmsg));
switch (r) {
case SQLITE_BUSY:
case SQLITE_LOCKED:
assert(0);
retcode = IDMAP_ERR_INTERNAL;
break;
case SQLITE_NOMEM:
retcode = IDMAP_ERR_MEMORY;
break;
case SQLITE_FULL:
retcode = IDMAP_ERR_DB;
break;
default:
retcode = idmapd_string2stat(errmsg);
break;
}
if (errmsg != NULL)
sqlite_freemem(errmsg);
return (retcode);
}
return (IDMAP_SUCCESS);
}
/*
* Generate expression that can be used in WHERE statements.
* Examples:
* <prefix> <col> <op> <value> <suffix>
* "" "unixuser" "=" "foo" "AND"
*/
idmap_retcode
gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
{
char *s_windomain = NULL, *s_winname = NULL;
char *s_unixname = NULL;
char *dir;
char *lower_winname;
int retcode = IDMAP_SUCCESS;
if (out == NULL)
return (IDMAP_ERR_ARG);
if (!EMPTY_STRING(rule->windomain)) {
s_windomain = sqlite_mprintf("AND windomain = %Q ",
rule->windomain);
if (s_windomain == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
if (!EMPTY_STRING(rule->winname)) {
if ((lower_winname = tolower_u8(rule->winname)) == NULL)
lower_winname = rule->winname;
s_winname = sqlite_mprintf(
"AND winname = %Q AND is_wuser = %d ",
lower_winname, rule->is_wuser ? 1 : 0);
if (lower_winname != rule->winname)
free(lower_winname);
if (s_winname == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
if (!EMPTY_STRING(rule->unixname)) {
s_unixname = sqlite_mprintf(
"AND unixname = %Q AND is_user = %d ",
rule->unixname, rule->is_user ? 1 : 0);
if (s_unixname == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
switch (rule->direction) {
case IDMAP_DIRECTION_BI:
dir = "AND w2u_order > 0 AND u2w_order > 0";
break;
case IDMAP_DIRECTION_W2U:
dir = "AND w2u_order > 0"
" AND (u2w_order = 0 OR u2w_order ISNULL)";
break;
case IDMAP_DIRECTION_U2W:
dir = "AND u2w_order > 0"
" AND (w2u_order = 0 OR w2u_order ISNULL)";
break;
default:
dir = "";
break;
}
*out = sqlite_mprintf("%s %s %s %s",
s_windomain ? s_windomain : "",
s_winname ? s_winname : "",
s_unixname ? s_unixname : "",
dir);
if (*out == NULL) {
retcode = IDMAP_ERR_MEMORY;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
out:
if (s_windomain != NULL)
sqlite_freemem(s_windomain);
if (s_winname != NULL)
sqlite_freemem(s_winname);
if (s_unixname != NULL)
sqlite_freemem(s_unixname);
return (retcode);
}
/*
* Generate and execute SQL statement for LIST RPC calls
*/
idmap_retcode
process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
int flag, list_svc_cb cb, void *result)
{
list_cb_data_t cb_data;
char *errmsg = NULL;
int r;
idmap_retcode retcode = IDMAP_ERR_INTERNAL;
(void) memset(&cb_data, 0, sizeof (cb_data));
cb_data.result = result;
cb_data.limit = limit;
cb_data.flag = flag;
r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
switch (r) {
case SQLITE_OK:
retcode = IDMAP_SUCCESS;
break;
default:
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Database error on %s while executing "
"%s (%s)", dbname, sql, CHECK_NULL(errmsg));
break;
}
if (errmsg != NULL)
sqlite_freemem(errmsg);
return (retcode);
}
/*
* This routine is called by callbacks that process the results of
* LIST RPC calls to validate data and to allocate memory for
* the result array.
*/
idmap_retcode
validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
int ncol, uchar_t **list, size_t valsize)
{
size_t nsize;
void *tmplist;
if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
return (IDMAP_NEXT);
if (argc < ncol || argv == NULL) {
idmapdlog(LOG_ERR, "Invalid data");
return (IDMAP_ERR_INTERNAL);
}
/* alloc in bulk to reduce number of reallocs */
if (cb_data->next >= cb_data->len) {
nsize = (cb_data->len + SIZE_INCR) * valsize;
tmplist = realloc(*list, nsize);
if (tmplist == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (IDMAP_ERR_MEMORY);
}
*list = tmplist;
(void) memset(*list + (cb_data->len * valsize), 0,
SIZE_INCR * valsize);
cb_data->len += SIZE_INCR;
}
return (IDMAP_SUCCESS);
}
static
idmap_retcode
get_namerule_order(char *winname, char *windomain, char *unixname,
int direction, int is_diagonal, int *w2u_order, int *u2w_order)
{
*w2u_order = 0;
*u2w_order = 0;
/*
* Windows to UNIX lookup order:
* 1. winname@domain (or winname) to ""
* 2. winname@domain (or winname) to unixname
* 3. winname@* to ""
* 4. winname@* to unixname
* 5. *@domain (or *) to *
* 6. *@domain (or *) to ""
* 7. *@domain (or *) to unixname
* 8. *@* to *
* 9. *@* to ""
* 10. *@* to unixname
*
* winname is a special case of winname@domain when domain is the
* default domain. Similarly * is a special case of *@domain when
* domain is the default domain.
*
* Note that "" has priority over specific names because "" inhibits
* mappings and traditionally deny rules always had higher priority.
*/
if (direction != IDMAP_DIRECTION_U2W) {
/* bi-directional or from windows to unix */
if (winname == NULL)
return (IDMAP_ERR_W2U_NAMERULE);
else if (unixname == NULL)
return (IDMAP_ERR_W2U_NAMERULE);
else if (EMPTY_NAME(winname))
return (IDMAP_ERR_W2U_NAMERULE);
else if (*winname == '*' && windomain && *windomain == '*') {
if (*unixname == '*')
*w2u_order = 8;
else if (EMPTY_NAME(unixname))
*w2u_order = 9;
else /* unixname == name */
*w2u_order = 10;
} else if (*winname == '*') {
if (*unixname == '*')
*w2u_order = 5;
else if (EMPTY_NAME(unixname))
*w2u_order = 6;
else /* name */
*w2u_order = 7;
} else if (windomain != NULL && *windomain == '*') {
/* winname == name */
if (*unixname == '*')
return (IDMAP_ERR_W2U_NAMERULE);
else if (EMPTY_NAME(unixname))
*w2u_order = 3;
else /* name */
*w2u_order = 4;
} else {
/* winname == name && windomain == null or name */
if (*unixname == '*')
return (IDMAP_ERR_W2U_NAMERULE);
else if (EMPTY_NAME(unixname))
*w2u_order = 1;
else /* name */
*w2u_order = 2;
}
}
/*
* 1. unixname to "", non-diagonal
* 2. unixname to winname@domain (or winname), non-diagonal
* 3. unixname to "", diagonal
* 4. unixname to winname@domain (or winname), diagonal
* 5. * to *@domain (or *), non-diagonal
* 5. * to *@domain (or *), diagonal
* 7. * to ""
* 8. * to winname@domain (or winname)
* 9. * to "", non-diagonal
* 10. * to winname@domain (or winname), diagonal
*/
if (direction != IDMAP_DIRECTION_W2U) {
int diagonal = is_diagonal ? 1 : 0;
/* bi-directional or from unix to windows */
if (unixname == NULL || EMPTY_NAME(unixname))
return (IDMAP_ERR_U2W_NAMERULE);
else if (winname == NULL)
return (IDMAP_ERR_U2W_NAMERULE);
else if (windomain != NULL && *windomain == '*')
return (IDMAP_ERR_U2W_NAMERULE);
else if (*unixname == '*') {
if (*winname == '*')
*u2w_order = 5 + diagonal;
else if (EMPTY_NAME(winname))
*u2w_order = 7 + 2 * diagonal;
else
*u2w_order = 8 + 2 * diagonal;
} else {
if (*winname == '*')
return (IDMAP_ERR_U2W_NAMERULE);
else if (EMPTY_NAME(winname))
*u2w_order = 1 + 2 * diagonal;
else
*u2w_order = 2 + 2 * diagonal;
}
}
return (IDMAP_SUCCESS);
}
/*
* Generate and execute SQL statement to add name-based mapping rule
*/
idmap_retcode
add_namerule(sqlite *db, idmap_namerule *rule)
{
char *sql = NULL;
idmap_stat retcode;
char *dom = NULL;
char *name;
int w2u_order, u2w_order;
char w2ubuf[11], u2wbuf[11];
char *canonname = NULL;
char *canondomain = NULL;
retcode = get_namerule_order(rule->winname, rule->windomain,
rule->unixname, rule->direction,
rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
if (retcode != IDMAP_SUCCESS)
goto out;
if (w2u_order)
(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
if (u2w_order)
(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
/*
* For the triggers on namerules table to work correctly:
* 1) Use NULL instead of 0 for w2u_order and u2w_order
* 2) Use "" instead of NULL for "no domain"
*/
name = rule->winname;
dom = rule->windomain;
RDLOCK_CONFIG();
if (lookup_wksids_name2sid(name, dom,
&canonname, &canondomain,
NULL, NULL, NULL) == IDMAP_SUCCESS) {
name = canonname;
dom = canondomain;
} else if (EMPTY_STRING(dom)) {
if (_idmapdstate.cfg->pgcfg.default_domain)
dom = _idmapdstate.cfg->pgcfg.default_domain;
else
dom = "";
}
sql = sqlite_mprintf("INSERT into namerules "
"(is_user, is_wuser, windomain, winname_display, is_nt4, "
"unixname, w2u_order, u2w_order) "
"VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
name, rule->is_nt4 ? 1 : 0, rule->unixname,
w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
UNLOCK_CONFIG();
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
if (retcode == IDMAP_ERR_OTHER)
retcode = IDMAP_ERR_CFG;
out:
free(canonname);
free(canondomain);
if (sql != NULL)
sqlite_freemem(sql);
return (retcode);
}
/*
* Flush name-based mapping rules
*/
idmap_retcode
flush_namerules(sqlite *db)
{
idmap_stat retcode;
retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
return (retcode);
}
/*
* Generate and execute SQL statement to remove a name-based mapping rule
*/
idmap_retcode
rm_namerule(sqlite *db, idmap_namerule *rule)
{
char *sql = NULL;
idmap_stat retcode;
char *expr = NULL;
if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
return (IDMAP_SUCCESS);
retcode = gen_sql_expr_from_rule(rule, &expr);
if (retcode != IDMAP_SUCCESS)
goto out;
sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s;", expr);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
out:
if (expr != NULL)
sqlite_freemem(expr);
if (sql != NULL)
sqlite_freemem(sql);
return (retcode);
}
/*
* Compile the given SQL query and step just once.
*
* Input:
* db - db handle
* sql - SQL statement
*
* Output:
* vm - virtual SQL machine
* ncol - number of columns in the result
* values - column values
*
* Return values:
* IDMAP_SUCCESS
* IDMAP_ERR_NOTFOUND
* IDMAP_ERR_INTERNAL
*/
static
idmap_retcode
sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
int reqcol, const char ***values)
{
char *errmsg = NULL;
int r;
if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
return (IDMAP_ERR_INTERNAL);
}
r = sqlite_step(*vm, ncol, values, NULL);
assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
if (r == SQLITE_ROW) {
if (ncol != NULL && *ncol < reqcol) {
(void) sqlite_finalize(*vm, NULL);
*vm = NULL;
return (IDMAP_ERR_INTERNAL);
}
/* Caller will call finalize after using the results */
return (IDMAP_SUCCESS);
} else if (r == SQLITE_DONE) {
(void) sqlite_finalize(*vm, NULL);
*vm = NULL;
return (IDMAP_ERR_NOTFOUND);
}
(void) sqlite_finalize(*vm, &errmsg);
*vm = NULL;
idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
return (IDMAP_ERR_INTERNAL);
}
/*
* Load config in the state.
*
* nm_siduid and nm_sidgid fields:
* state->nm_siduid represents mode used by sid2uid and uid2sid
* requests for directory-based name mappings. Similarly,
* state->nm_sidgid represents mode used by sid2gid and gid2sid
* requests.
*
* sid2uid/uid2sid:
* none -> directory_based_mapping != DIRECTORY_MAPPING_NAME
* AD-mode -> !nldap_winname_attr && ad_unixuser_attr
* nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
* mixed-mode -> nldap_winname_attr && ad_unixuser_attr
*
* sid2gid/gid2sid:
* none -> directory_based_mapping != DIRECTORY_MAPPING_NAME
* AD-mode -> !nldap_winname_attr && ad_unixgroup_attr
* nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
* mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
*/
idmap_retcode
load_cfg_in_state(lookup_state_t *state)
{
state->nm_siduid = IDMAP_NM_NONE;
state->nm_sidgid = IDMAP_NM_NONE;
RDLOCK_CONFIG();
state->eph_map_unres_sids = 0;
if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
state->eph_map_unres_sids = 1;
state->id_cache_timeout =
_idmapdstate.cfg->pgcfg.id_cache_timeout;
state->name_cache_timeout =
_idmapdstate.cfg->pgcfg.name_cache_timeout;
state->directory_based_mapping =
_idmapdstate.cfg->pgcfg.directory_based_mapping;
if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
state->defdom =
strdup(_idmapdstate.cfg->pgcfg.default_domain);
if (state->defdom == NULL) {
UNLOCK_CONFIG();
return (IDMAP_ERR_MEMORY);
}
} else {
UNLOCK_CONFIG();
return (IDMAP_SUCCESS);
}
if (_idmapdstate.cfg->pgcfg.directory_based_mapping !=
DIRECTORY_MAPPING_NAME) {
UNLOCK_CONFIG();
return (IDMAP_SUCCESS);
}
if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
state->nm_siduid =
(_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
state->nm_sidgid =
(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
} else {
state->nm_siduid =
(_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
? IDMAP_NM_AD : IDMAP_NM_NONE;
state->nm_sidgid =
(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
? IDMAP_NM_AD : IDMAP_NM_NONE;
}
if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
state->ad_unixuser_attr =
strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
if (state->ad_unixuser_attr == NULL) {
UNLOCK_CONFIG();
return (IDMAP_ERR_MEMORY);
}
}
if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
state->ad_unixgroup_attr =
strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
if (state->ad_unixgroup_attr == NULL) {
UNLOCK_CONFIG();
return (IDMAP_ERR_MEMORY);
}
}
if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
state->nldap_winname_attr =
strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
if (state->nldap_winname_attr == NULL) {
UNLOCK_CONFIG();
return (IDMAP_ERR_MEMORY);
}
}
UNLOCK_CONFIG();
return (IDMAP_SUCCESS);
}
/*
* Set the rule with specified values.
* All the strings are copied.
*/
static void
idmap_namerule_set(idmap_namerule *rule, const char *windomain,
const char *winname, const char *unixname, boolean_t is_user,
boolean_t is_wuser, boolean_t is_nt4, int direction)
{
/*
* Only update if they differ because we have to free
* and duplicate the strings
*/
if (rule->windomain == NULL || windomain == NULL ||
strcmp(rule->windomain, windomain) != 0) {
if (rule->windomain != NULL) {
free(rule->windomain);
rule->windomain = NULL;
}
if (windomain != NULL)
rule->windomain = strdup(windomain);
}
if (rule->winname == NULL || winname == NULL ||
strcmp(rule->winname, winname) != 0) {
if (rule->winname != NULL) {
free(rule->winname);
rule->winname = NULL;
}
if (winname != NULL)
rule->winname = strdup(winname);
}
if (rule->unixname == NULL || unixname == NULL ||
strcmp(rule->unixname, unixname) != 0) {
if (rule->unixname != NULL) {
free(rule->unixname);
rule->unixname = NULL;
}
if (unixname != NULL)
rule->unixname = strdup(unixname);
}
rule->is_user = is_user;
rule->is_wuser = is_wuser;
rule->is_nt4 = is_nt4;
rule->direction = direction;
}
/*
* Lookup well-known SIDs table either by winname or by SID.
*
* If the given winname or SID is a well-known SID then we set is_wksid
* variable and then proceed to see if the SID has a hard mapping to
* a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
* fixed ephemeral ids). The direction flag indicates whether we have
* a mapping; UNDEF indicates that we do not.
*
* If we find a mapping then we return success, except for the
* special case of IDMAP_SENTINEL_PID which indicates an inhibited mapping.
*
* If we find a matching entry, but no mapping, we supply SID, name, and type
* information and return "not found". Higher layers will probably
* do ephemeral mapping.
*
* If we do not find a match, we return "not found" and leave the question
* to higher layers.
*/
static
idmap_retcode
lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *is_wksid)
{
const wksids_table_t *wksid;
*is_wksid = 0;
assert(req->id1.idmap_id_u.sid.prefix != NULL ||
req->id1name != NULL);
if (req->id1.idmap_id_u.sid.prefix != NULL) {
wksid = find_wksid_by_sid(req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid, res->id.idtype);
} else {
wksid = find_wksid_by_name(req->id1name, req->id1domain,
res->id.idtype);
}
if (wksid == NULL)
return (IDMAP_ERR_NOTFOUND);
/* Found matching entry. */
/* Fill in name if it was not already there. */
if (req->id1name == NULL) {
req->id1name = strdup(wksid->winname);
if (req->id1name == NULL)
return (IDMAP_ERR_MEMORY);
}
/* Fill in SID if it was not already there */
if (req->id1.idmap_id_u.sid.prefix == NULL) {
if (wksid->sidprefix != NULL) {
req->id1.idmap_id_u.sid.prefix =
strdup(wksid->sidprefix);
} else {
RDLOCK_CONFIG();
req->id1.idmap_id_u.sid.prefix =
strdup(_idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
}
if (req->id1.idmap_id_u.sid.prefix == NULL)
return (IDMAP_ERR_MEMORY);
req->id1.idmap_id_u.sid.rid = wksid->rid;
}
/* Fill in the canonical domain if not already there */
if (req->id1domain == NULL) {
const char *dom;
RDLOCK_CONFIG();
if (wksid->domain != NULL)
dom = wksid->domain;
else
dom = _idmapdstate.hostname;
req->id1domain = strdup(dom);
UNLOCK_CONFIG();
if (req->id1domain == NULL)
return (IDMAP_ERR_MEMORY);
}
*is_wksid = 1;
req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
req->id1.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
if (res->id.idtype == IDMAP_POSIXID) {
res->id.idtype = wksid->is_wuser ? IDMAP_UID : IDMAP_GID;
}
if (wksid->direction == IDMAP_DIRECTION_UNDEF) {
/*
* We don't have a mapping
* (But note that we may have supplied SID, name, or type
* information.)
*/
return (IDMAP_ERR_NOTFOUND);
}
/*
* We have an explicit mapping.
*/
if (wksid->pid == IDMAP_SENTINEL_PID) {
/*
* ... which is that mapping is inhibited.
*/
return (IDMAP_ERR_NOMAPPING);
}
switch (res->id.idtype) {
case IDMAP_UID:
res->id.idmap_id_u.uid = wksid->pid;
break;
case IDMAP_GID:
res->id.idmap_id_u.gid = wksid->pid;
break;
default:
/* IDMAP_POSIXID is eliminated above */
return (IDMAP_ERR_NOTSUPPORTED);
}
res->direction = wksid->direction;
res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
res->info.src = IDMAP_MAP_SRC_HARD_CODED;
return (IDMAP_SUCCESS);
}
/*
* Look for an entry mapping a PID to a SID.
*
* Note that direction=UNDEF entries do not specify a mapping,
* and that IDMAP_SENTINEL_PID entries represent either an inhibited
* mapping or an ephemeral mapping. We don't handle either here;
* they are filtered out by find_wksid_by_pid.
*/
static
idmap_retcode
lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
{
const wksids_table_t *wksid;
wksid = find_wksid_by_pid(req->id1.idmap_id_u.uid, is_user);
if (wksid == NULL)
return (IDMAP_ERR_NOTFOUND);
if (res->id.idtype == IDMAP_SID) {
res->id.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
}
res->id.idmap_id_u.sid.rid = wksid->rid;
if (wksid->sidprefix != NULL) {
res->id.idmap_id_u.sid.prefix =
strdup(wksid->sidprefix);
} else {
RDLOCK_CONFIG();
res->id.idmap_id_u.sid.prefix =
strdup(_idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
}
if (res->id.idmap_id_u.sid.prefix == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (IDMAP_ERR_MEMORY);
}
/* Fill in name if it was not already there. */
if (req->id2name == NULL) {
req->id2name = strdup(wksid->winname);
if (req->id2name == NULL)
return (IDMAP_ERR_MEMORY);
}
/* Fill in the canonical domain if not already there */
if (req->id2domain == NULL) {
const char *dom;
RDLOCK_CONFIG();
if (wksid->domain != NULL)
dom = wksid->domain;
else
dom = _idmapdstate.hostname;
req->id2domain = strdup(dom);
UNLOCK_CONFIG();
if (req->id2domain == NULL)
return (IDMAP_ERR_MEMORY);
}
res->direction = wksid->direction;
res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
res->info.src = IDMAP_MAP_SRC_HARD_CODED;
return (IDMAP_SUCCESS);
}
/*
* Look up a name in the wksids list, matching name and, if supplied, domain,
* and extract data.
*
* Given:
* name Windows user name
* domain Windows domain name (or NULL)
*
* Return: Error code
*
* *canonname canonical name (if canonname non-NULL) [1]
* *canondomain canonical domain (if canondomain non-NULL) [1]
* *sidprefix SID prefix (if sidprefix non-NULL) [1]
* *rid RID (if rid non-NULL) [2]
* *type Type (if type non-NULL) [2]
*
* [1] malloc'ed, NULL on error
* [2] Undefined on error
*/
idmap_retcode
lookup_wksids_name2sid(
const char *name,
const char *domain,
char **canonname,
char **canondomain,
char **sidprefix,
idmap_rid_t *rid,
idmap_id_type *type)
{
const wksids_table_t *wksid;
if (sidprefix != NULL)
*sidprefix = NULL;
if (canonname != NULL)
*canonname = NULL;
if (canondomain != NULL)
*canondomain = NULL;
wksid = find_wksid_by_name(name, domain, IDMAP_POSIXID);
if (wksid == NULL)
return (IDMAP_ERR_NOTFOUND);
if (sidprefix != NULL) {
if (wksid->sidprefix != NULL) {
*sidprefix = strdup(wksid->sidprefix);
} else {
RDLOCK_CONFIG();
*sidprefix = strdup(
_idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
}
if (*sidprefix == NULL)
goto nomem;
}
if (rid != NULL)
*rid = wksid->rid;
if (canonname != NULL) {
*canonname = strdup(wksid->winname);
if (*canonname == NULL)
goto nomem;
}
if (canondomain != NULL) {
if (wksid->domain != NULL) {
*canondomain = strdup(wksid->domain);
} else {
RDLOCK_CONFIG();
*canondomain = strdup(_idmapdstate.hostname);
UNLOCK_CONFIG();
}
if (*canondomain == NULL)
goto nomem;
}
if (type != NULL)
*type = (wksid->is_wuser) ?
IDMAP_USID : IDMAP_GSID;
return (IDMAP_SUCCESS);
nomem:
idmapdlog(LOG_ERR, "Out of memory");
if (sidprefix != NULL) {
free(*sidprefix);
*sidprefix = NULL;
}
if (canonname != NULL) {
free(*canonname);
*canonname = NULL;
}
if (canondomain != NULL) {
free(*canondomain);
*canondomain = NULL;
}
return (IDMAP_ERR_MEMORY);
}
static
idmap_retcode
lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
{
char *end;
char *sql = NULL;
const char **values;
sqlite_vm *vm = NULL;
int ncol, is_user;
uid_t pid;
time_t curtime, exp;
idmap_retcode retcode;
char *is_user_string, *lower_name;
/* Current time */
errno = 0;
if ((curtime = time(NULL)) == (time_t)-1) {
idmapdlog(LOG_ERR, "Failed to get current time (%s)",
strerror(errno));
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
switch (res->id.idtype) {
case IDMAP_UID:
is_user_string = "1";
break;
case IDMAP_GID:
is_user_string = "0";
break;
case IDMAP_POSIXID:
/* the non-diagonal mapping */
is_user_string = "is_wuser";
break;
default:
retcode = IDMAP_ERR_NOTSUPPORTED;
goto out;
}
/* SQL to lookup the cache */
if (req->id1.idmap_id_u.sid.prefix != NULL) {
sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
"unixname, u2w, is_wuser, "
"map_type, map_dn, map_attr, map_value, "
"map_windomain, map_winname, map_unixname, map_is_nt4 "
"FROM idmap_cache WHERE is_user = %s AND "
"sidprefix = %Q AND rid = %u AND w2u = 1 AND "
"(pid >= 2147483648 OR "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d));",
is_user_string, req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid, curtime);
} else if (req->id1name != NULL) {
if ((lower_name = tolower_u8(req->id1name)) == NULL)
lower_name = req->id1name;
sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
"unixname, u2w, is_wuser, "
"map_type, map_dn, map_attr, map_value, "
"map_windomain, map_winname, map_unixname, map_is_nt4 "
"FROM idmap_cache WHERE is_user = %s AND "
"winname = %Q AND windomain = %Q AND w2u = 1 AND "
"(pid >= 2147483648 OR "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d));",
is_user_string, lower_name, req->id1domain,
curtime);
if (lower_name != req->id1name)
free(lower_name);
} else {
retcode = IDMAP_ERR_ARG;
goto out;
}
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
14, &values);
sqlite_freemem(sql);
if (retcode == IDMAP_ERR_NOTFOUND) {
goto out;
} else if (retcode == IDMAP_SUCCESS) {
/* sanity checks */
if (values[0] == NULL || values[1] == NULL) {
retcode = IDMAP_ERR_CACHE;
goto out;
}
pid = strtoul(values[0], &end, 10);
is_user = strncmp(values[1], "0", 2) ? 1 : 0;
if (is_user) {
res->id.idtype = IDMAP_UID;
res->id.idmap_id_u.uid = pid;
} else {
res->id.idtype = IDMAP_GID;
res->id.idmap_id_u.gid = pid;
}
/*
* We may have an expired ephemeral mapping. Consider
* the expired entry as valid if we are not going to
* perform name-based mapping. But do not renew the
* expiration.
* If we will be doing name-based mapping then store the
* ephemeral pid in the result so that we can use it
* if we end up doing dynamic mapping again.
*/
if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
!AVOID_NAMESERVICE(req) &&
IDMAP_ID_IS_EPHEMERAL(pid) && values[2] != NULL) {
exp = strtoll(values[2], &end, 10);
if (exp && exp <= curtime) {
/* Store the ephemeral pid */
res->direction = IDMAP_DIRECTION_BI;
req->direction |= is_user
? _IDMAP_F_EXP_EPH_UID
: _IDMAP_F_EXP_EPH_GID;
retcode = IDMAP_ERR_NOTFOUND;
}
}
}
out:
if (retcode == IDMAP_SUCCESS) {
if (values[4] != NULL)
res->direction =
(strtol(values[4], &end, 10) == 0)?
IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
else
res->direction = IDMAP_DIRECTION_W2U;
if (values[3] != NULL) {
if (req->id2name != NULL)
free(req->id2name);
req->id2name = strdup(values[3]);
if (req->id2name == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
}
}
req->id1.idtype = strncmp(values[5], "0", 2) ?
IDMAP_USID : IDMAP_GSID;
if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
res->info.src = IDMAP_MAP_SRC_CACHE;
res->info.how.map_type = strtoul(values[6], &end, 10);
switch (res->info.how.map_type) {
case IDMAP_MAP_TYPE_DS_AD:
res->info.how.idmap_how_u.ad.dn =
strdup(values[7]);
res->info.how.idmap_how_u.ad.attr =
strdup(values[8]);
res->info.how.idmap_how_u.ad.value =
strdup(values[9]);
break;
case IDMAP_MAP_TYPE_DS_NLDAP:
res->info.how.idmap_how_u.nldap.dn =
strdup(values[7]);
res->info.how.idmap_how_u.nldap.attr =
strdup(values[8]);
res->info.how.idmap_how_u.nldap.value =
strdup(values[9]);
break;
case IDMAP_MAP_TYPE_RULE_BASED:
res->info.how.idmap_how_u.rule.windomain =
strdup(values[10]);
res->info.how.idmap_how_u.rule.winname =
strdup(values[11]);
res->info.how.idmap_how_u.rule.unixname =
strdup(values[12]);
res->info.how.idmap_how_u.rule.is_nt4 =
strtoul(values[13], &end, 1);
res->info.how.idmap_how_u.rule.is_user =
is_user;
res->info.how.idmap_how_u.rule.is_wuser =
strtoul(values[5], &end, 1);
break;
case IDMAP_MAP_TYPE_EPHEMERAL:
break;
case IDMAP_MAP_TYPE_LOCAL_SID:
break;
case IDMAP_MAP_TYPE_KNOWN_SID:
break;
case IDMAP_MAP_TYPE_IDMU:
res->info.how.idmap_how_u.idmu.dn =
strdup(values[7]);
res->info.how.idmap_how_u.idmu.attr =
strdup(values[8]);
res->info.how.idmap_how_u.idmu.value =
strdup(values[9]);
break;
default:
/* Unknown mapping type */
assert(FALSE);
}
}
}
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
return (retcode);
}
/*
* Previous versions used two enumerations for representing types.
* One of those has largely been eliminated, but was used in the
* name cache table and so during an upgrade might still be visible.
* In addition, the test suite prepopulates the cache with these values.
*
* This function translates those old values into the new values.
*
* This code deliberately does not use symbolic values for the legacy
* values. This is the *only* place where they should be used.
*/
static
idmap_id_type
xlate_legacy_type(int type)
{
switch (type) {
case -1004: /* _IDMAP_T_USER */
return (IDMAP_USID);
case -1005: /* _IDMAP_T_GROUP */
return (IDMAP_GSID);
default:
return (type);
}
NOTE(NOTREACHED)
}
static
idmap_retcode
lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
char **canonname, char **canondomain, idmap_id_type *type)
{
char *end;
char *sql = NULL;
const char **values;
sqlite_vm *vm = NULL;
int ncol;
time_t curtime;
idmap_retcode retcode = IDMAP_SUCCESS;
/* Get current time */
errno = 0;
if ((curtime = time(NULL)) == (time_t)-1) {
idmapdlog(LOG_ERR, "Failed to get current time (%s)",
strerror(errno));
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
/* SQL to lookup the cache */
sql = sqlite_mprintf("SELECT canon_name, domain, type "
"FROM name_cache WHERE "
"sidprefix = %Q AND rid = %u AND "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d);",
sidprefix, rid, curtime);
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
sqlite_freemem(sql);
if (retcode == IDMAP_SUCCESS) {
if (type != NULL) {
if (values[2] == NULL) {
retcode = IDMAP_ERR_CACHE;
goto out;
}
*type = xlate_legacy_type(strtol(values[2], &end, 10));
}
if (canonname != NULL && values[0] != NULL) {
if ((*canonname = strdup(values[0])) == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
if (canondomain != NULL && values[1] != NULL) {
if ((*canondomain = strdup(values[1])) == NULL) {
if (canonname != NULL) {
free(*canonname);
*canonname = NULL;
}
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
}
out:
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
return (retcode);
}
/*
* Given SID, find winname using name_cache OR
* Given winname, find SID using name_cache.
* Used when mapping win to unix i.e. req->id1 is windows id and
* req->id2 is unix id
*/
static
idmap_retcode
lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
{
idmap_id_type type = -1;
idmap_retcode retcode;
char *sidprefix = NULL;
idmap_rid_t rid;
char *name = NULL, *domain = NULL;
/* Done if we've both sid and winname */
if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL) {
/* Don't bother TRACE()ing, too boring */
return (IDMAP_SUCCESS);
}
if (req->id1.idmap_id_u.sid.prefix != NULL) {
/* Lookup sid to winname */
retcode = lookup_cache_sid2name(cache,
req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
} else {
/* Lookup winame to sid */
retcode = lookup_cache_name2sid(cache, req->id1name,
req->id1domain, &name, &sidprefix, &rid, &type);
}
if (retcode != IDMAP_SUCCESS) {
if (retcode == IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Not found in name cache");
} else {
TRACE(req, res, "Name cache lookup error=%d", retcode);
}
free(name);
free(domain);
free(sidprefix);
return (retcode);
}
req->id1.idtype = type;
req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
/*
* If we found canonical names or domain, use them instead of
* the existing values.
*/
if (name != NULL) {
free(req->id1name);
req->id1name = name;
}
if (domain != NULL) {
free(req->id1domain);
req->id1domain = domain;
}
if (req->id1.idmap_id_u.sid.prefix == NULL) {
req->id1.idmap_id_u.sid.prefix = sidprefix;
req->id1.idmap_id_u.sid.rid = rid;
}
TRACE(req, res, "Found in name cache");
return (retcode);
}
static int
ad_lookup_batch_int(lookup_state_t *state, idmap_mapping_batch *batch,
idmap_ids_res *result, adutils_ad_t *dir, int how_local,
int *num_processed)
{
idmap_retcode retcode;
int i, num_queued, is_wuser, is_user;
int next_request;
int retries = 0, esidtype;
char **unixname;
idmap_mapping *req;
idmap_id_res *res;
idmap_query_state_t *qs = NULL;
idmap_how *how;
char **dn, **attr, **value;
*num_processed = 0;
/*
* Since req->id2.idtype is unused, we will use it here
* to retrieve the value of sid_type. But it needs to be
* reset to IDMAP_NONE before we return to prevent xdr
* from mis-interpreting req->id2 when it tries to free
* the input argument. Other option is to allocate an
* array of integers and use it instead for the batched
* call. But why un-necessarily allocate memory. That may
* be an option if req->id2.idtype cannot be re-used in
* future.
*
* Similarly, we use req->id2.idmap_id_u.uid to return
* uidNumber or gidNumber supplied by IDMU, and reset it
* back to IDMAP_SENTINEL_PID when we're done. Note that
* the query always puts the result in req->id2.idmap_id_u.uid,
* not .gid.
*/
retry:
retcode = idmap_lookup_batch_start(dir, state->ad_nqueries,
state->directory_based_mapping,
state->defdom,
&qs);
if (retcode != IDMAP_SUCCESS) {
if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
retries++ < ADUTILS_DEF_NUM_RETRIES)
goto retry;
degrade_svc(1, "failed to create batch for AD lookup");
goto out;
}
num_queued = 0;
restore_svc();
if (how_local & FOREST_IS_LOCAL) {
/*
* Directory based name mapping is only performed within the
* joined forest. We don't trust other "trusted"
* forests to provide DS-based name mapping information because
* AD's definition of "cross-forest trust" does not encompass
* this sort of behavior.
*/
idmap_lookup_batch_set_unixattr(qs,
state->ad_unixuser_attr, state->ad_unixgroup_attr);
}
for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
req = &batch->idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
how = &res->info.how;
retcode = IDMAP_SUCCESS;
req->id2.idtype = IDMAP_NONE;
req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
/* Skip if no AD lookup required */
if (!(req->direction & _IDMAP_F_LOOKUP_AD))
continue;
/* Skip if we've already tried and gotten a "not found" */
if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD)
continue;
/* Skip if we've already either succeeded or failed */
if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
continue;
if (IS_ID_SID(req->id1)) {
/* win2unix request: */
posix_id_t *pid = NULL;
unixname = dn = attr = value = NULL;
esidtype = IDMAP_SID;
if (state->directory_based_mapping ==
DIRECTORY_MAPPING_NAME &&
req->id2name == NULL) {
if (res->id.idtype == IDMAP_UID &&
AD_OR_MIXED(state->nm_siduid)) {
esidtype = IDMAP_USID;
unixname = &req->id2name;
} else if (res->id.idtype == IDMAP_GID &&
AD_OR_MIXED(state->nm_sidgid)) {
esidtype = IDMAP_GSID;
unixname = &req->id2name;
} else if (AD_OR_MIXED(state->nm_siduid) ||
AD_OR_MIXED(state->nm_sidgid)) {
unixname = &req->id2name;
}
if (unixname != NULL) {
/*
* Get how info for DS-based name
* mapping only if AD or MIXED
* mode is enabled.
*/
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how->map_type = IDMAP_MAP_TYPE_DS_AD;
dn = &how->idmap_how_u.ad.dn;
attr = &how->idmap_how_u.ad.attr;
value = &how->idmap_how_u.ad.value;
}
} else if (state->directory_based_mapping ==
DIRECTORY_MAPPING_IDMU &&
(how_local & DOMAIN_IS_LOCAL)) {
/*
* Ensure that we only do IDMU processing
* when querying the domain we've joined.
*/
pid = &req->id2.idmap_id_u.uid;
/*
* Get how info for IDMU based mapping.
*/
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how->map_type = IDMAP_MAP_TYPE_IDMU;
dn = &how->idmap_how_u.idmu.dn;
attr = &how->idmap_how_u.idmu.attr;
value = &how->idmap_how_u.idmu.value;
}
if (req->id1.idmap_id_u.sid.prefix != NULL) {
/* Lookup AD by SID */
retcode = idmap_sid2name_batch_add1(
qs, req->id1.idmap_id_u.sid.prefix,
&req->id1.idmap_id_u.sid.rid, esidtype,
dn, attr, value,
(req->id1name == NULL) ?
&req->id1name : NULL,
(req->id1domain == NULL) ?
&req->id1domain : NULL,
&req->id2.idtype, unixname,
pid,
&res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
} else {
/* Lookup AD by winname */
assert(req->id1name != NULL);
retcode = idmap_name2sid_batch_add1(
qs, req->id1name, req->id1domain,
esidtype,
dn, attr, value,
&req->id1name,
&req->id1.idmap_id_u.sid.prefix,
&req->id1.idmap_id_u.sid.rid,
&req->id2.idtype, unixname,
pid,
&res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
}
} else if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1)) {
/* unix2win request: */
if (res->id.idmap_id_u.sid.prefix != NULL &&
req->id2name != NULL) {
/* Already have SID and winname. done */
res->retcode = IDMAP_SUCCESS;
continue;
}
if (res->id.idmap_id_u.sid.prefix != NULL) {
/*
* SID but no winname -- lookup AD by
* SID to get winname.
* how info is not needed here because
* we are not retrieving unixname from
* AD.
*/
retcode = idmap_sid2name_batch_add1(
qs, res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
IDMAP_POSIXID,
NULL, NULL, NULL,
&req->id2name,
&req->id2domain, &req->id2.idtype,
NULL, NULL, &res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
} else if (req->id2name != NULL) {
/*
* winname but no SID -- lookup AD by
* winname to get SID.
* how info is not needed here because
* we are not retrieving unixname from
* AD.
*/
retcode = idmap_name2sid_batch_add1(
qs, req->id2name, req->id2domain,
IDMAP_POSIXID,
NULL, NULL, NULL, NULL,
&res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
&req->id2.idtype, NULL,
NULL,
&res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
} else if (state->directory_based_mapping ==
DIRECTORY_MAPPING_IDMU &&
(how_local & DOMAIN_IS_LOCAL)) {
assert(req->id1.idmap_id_u.uid !=
IDMAP_SENTINEL_PID);
is_user = IS_ID_UID(req->id1);
if (res->id.idtype == IDMAP_USID)
is_wuser = 1;
else if (res->id.idtype == IDMAP_GSID)
is_wuser = 0;
else
is_wuser = is_user;
/* IDMU can't do diagonal mappings */
if (is_user != is_wuser)
continue;
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how->map_type = IDMAP_MAP_TYPE_IDMU;
retcode = idmap_pid2sid_batch_add1(
qs, req->id1.idmap_id_u.uid, is_user,
&how->idmap_how_u.ad.dn,
&how->idmap_how_u.ad.attr,
&how->idmap_how_u.ad.value,
&res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
&req->id2name, &req->id2domain,
&req->id2.idtype, &res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
} else if (req->id1name != NULL) {
/*
* No SID and no winname but we've unixname.
* Lookup AD by unixname to get SID.
*/
is_user = (IS_ID_UID(req->id1)) ? 1 : 0;
if (res->id.idtype == IDMAP_USID)
is_wuser = 1;
else if (res->id.idtype == IDMAP_GSID)
is_wuser = 0;
else
is_wuser = is_user;
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how->map_type = IDMAP_MAP_TYPE_DS_AD;
retcode = idmap_unixname2sid_batch_add1(
qs, req->id1name, is_user, is_wuser,
&how->idmap_how_u.ad.dn,
&how->idmap_how_u.ad.attr,
&how->idmap_how_u.ad.value,
&res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
&req->id2name, &req->id2domain,
&req->id2.idtype, &res->retcode);
if (retcode == IDMAP_SUCCESS)
num_queued++;
}
}
if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
retcode = IDMAP_SUCCESS;
} else if (retcode != IDMAP_SUCCESS) {
break;
}
} /* End of for loop */
if (retcode == IDMAP_SUCCESS) {
/* add keeps track if we added an entry to the batch */
if (num_queued > 0)
retcode = idmap_lookup_batch_end(&qs);
else
idmap_lookup_release_batch(&qs);
} else {
idmap_lookup_release_batch(&qs);
num_queued = 0;
next_request = i + 1;
}
if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
retries++ < ADUTILS_DEF_NUM_RETRIES)
goto retry;
else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
degrade_svc(1, "some AD lookups timed out repeatedly");
if (retcode != IDMAP_SUCCESS) {
/* Mark any unproccessed requests for an other AD */
for (i = next_request; i < batch->idmap_mapping_batch_len;
i++) {
req = &batch->idmap_mapping_batch_val[i];
req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
}
}
if (retcode != IDMAP_SUCCESS)
idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
out:
/*
* This loop does the following:
* 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
* 2. Reset req->id2.idtype to IDMAP_NONE
* 3. If batch_start or batch_add failed then set the status
* of each request marked for AD lookup to that error.
* 4. Evaluate the type of the AD object (i.e. user or group)
* and update the idtype in request.
*/
for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
idmap_id_type type;
uid_t posix_id;
req = &batch->idmap_mapping_batch_val[i];
type = req->id2.idtype;
req->id2.idtype = IDMAP_NONE;
posix_id = req->id2.idmap_id_u.uid;
req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
res = &result->ids.ids_val[i];
/*
* If it didn't need AD lookup, ignore it.
*/
if (!(req->direction & _IDMAP_F_LOOKUP_AD))
continue;
/*
* If we deferred it this time, reset for the next
* AD server.
*/
if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD) {
req->direction &= ~_IDMAP_F_LOOKUP_OTHER_AD;
continue;
}
/* Count number processed */
(*num_processed)++;
/* Reset AD lookup flag */
req->direction &= ~(_IDMAP_F_LOOKUP_AD);
/*
* If batch_start or batch_add failed then set the
* status of each request marked for AD lookup to
* that error.
*/
if (retcode != IDMAP_SUCCESS) {
res->retcode = retcode;
continue;
}
if (res->retcode == IDMAP_ERR_NOTFOUND) {
/* Nothing found - remove the preset info */
idmap_how_clear(&res->info.how);
}
if (IS_ID_SID(req->id1)) {
if (res->retcode == IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Not found in AD");
continue;
}
if (res->retcode != IDMAP_SUCCESS) {
TRACE(req, res, "AD lookup error=%d",
res->retcode);
continue;
}
/* Evaluate result type */
switch (type) {
case IDMAP_USID:
if (res->id.idtype == IDMAP_POSIXID)
res->id.idtype = IDMAP_UID;
/*
* We found a user. If we got information
* from IDMU and we were expecting a user,
* copy the id.
*/
if (posix_id != IDMAP_SENTINEL_PID &&
res->id.idtype == IDMAP_UID) {
res->id.idmap_id_u.uid = posix_id;
res->direction = IDMAP_DIRECTION_BI;
res->info.how.map_type =
IDMAP_MAP_TYPE_IDMU;
res->info.src = IDMAP_MAP_SRC_NEW;
}
req->id1.idtype = IDMAP_USID;
break;
case IDMAP_GSID:
if (res->id.idtype == IDMAP_POSIXID)
res->id.idtype = IDMAP_GID;
/*
* We found a group. If we got information
* from IDMU and we were expecting a group,
* copy the id.
*/
if (posix_id != IDMAP_SENTINEL_PID &&
res->id.idtype == IDMAP_GID) {
res->id.idmap_id_u.gid = posix_id;
res->direction = IDMAP_DIRECTION_BI;
res->info.how.map_type =
IDMAP_MAP_TYPE_IDMU;
res->info.src = IDMAP_MAP_SRC_NEW;
}
req->id1.idtype = IDMAP_GSID;
break;
default:
res->retcode = IDMAP_ERR_SID;
break;
}
TRACE(req, res, "Found in AD");
if (res->retcode == IDMAP_SUCCESS &&
req->id1name != NULL &&
(req->id2name == NULL ||
res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID) &&
NLDAP_MODE(res->id.idtype, state)) {
req->direction |= _IDMAP_F_LOOKUP_NLDAP;
state->nldap_nqueries++;
}
} else if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1)) {
if (res->retcode != IDMAP_SUCCESS) {
if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
res->id.idmap_id_u.sid.prefix == NULL &&
req->id2name == NULL) {
/*
* If AD lookup by unixname or pid
* failed with non fatal error
* then clear the error (ie set
* res->retcode to success).
* This allows the next pass to
* process other mapping
* mechanisms for this request.
*/
if (res->retcode ==
IDMAP_ERR_NOTFOUND) {
/* This is not an error */
res->retcode = IDMAP_SUCCESS;
TRACE(req, res,
"Not found in AD");
} else {
TRACE(req, res,
"AD lookup error (ignored)");
res->retcode = IDMAP_SUCCESS;
}
} else {
TRACE(req, res, "AD lookup error");
}
continue;
}
/* Evaluate result type */
switch (type) {
case IDMAP_USID:
case IDMAP_GSID:
if (res->id.idtype == IDMAP_SID)
res->id.idtype = type;
break;
default:
res->retcode = IDMAP_ERR_SID;
break;
}
TRACE(req, res, "Found in AD");
}
}
return (retcode);
}
/*
* Batch AD lookups
*/
idmap_retcode
ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
idmap_ids_res *result)
{
idmap_retcode retcode;
int i, j;
idmap_mapping *req;
idmap_id_res *res;
int num_queries;
int num_processed;
if (state->ad_nqueries == 0)
return (IDMAP_SUCCESS);
for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
req = &batch->idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
/* Skip if not marked for AD lookup or already in error. */
if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
res->retcode != IDMAP_SUCCESS)
continue;
/* Init status */
res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
}
RDLOCK_CONFIG();
num_queries = state->ad_nqueries;
if (_idmapdstate.num_gcs == 0 && _idmapdstate.num_dcs == 0) {
/* Case of no ADs */
retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
req = &batch->idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
if (!(req->direction & _IDMAP_F_LOOKUP_AD))
continue;
req->direction &= ~(_IDMAP_F_LOOKUP_AD);
res->retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
}
goto out;
}
if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
for (i = 0; i < _idmapdstate.num_dcs && num_queries > 0; i++) {
retcode = ad_lookup_batch_int(state, batch,
result, _idmapdstate.dcs[i],
i == 0 ? DOMAIN_IS_LOCAL|FOREST_IS_LOCAL : 0,
&num_processed);
num_queries -= num_processed;
}
}
for (i = 0; i < _idmapdstate.num_gcs && num_queries > 0; i++) {
retcode = ad_lookup_batch_int(state, batch, result,
_idmapdstate.gcs[i],
i == 0 ? FOREST_IS_LOCAL : 0,
&num_processed);
num_queries -= num_processed;
}
/*
* There are no more ADs to try. Return errors for any
* remaining requests.
*/
if (num_queries > 0) {
for (j = 0; j < batch->idmap_mapping_batch_len; j++) {
req = &batch->idmap_mapping_batch_val[j];
res = &result->ids.ids_val[j];
if (!(req->direction & _IDMAP_F_LOOKUP_AD))
continue;
req->direction &= ~(_IDMAP_F_LOOKUP_AD);
res->retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
}
}
out:
UNLOCK_CONFIG();
/* AD lookups done. Reset state->ad_nqueries and return */
state->ad_nqueries = 0;
return (retcode);
}
/*
* Convention when processing win2unix requests:
*
* Windows identity:
* req->id1name =
* winname if given otherwise winname found will be placed
* here.
* req->id1domain =
* windomain if given otherwise windomain found will be
* placed here.
* req->id1.idtype =
* Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
* be set to IDMAP_USID/GSID depending upon whether the
* given SID is user or group respectively. The user/group-ness
* is determined either when looking up well-known SIDs table OR
* if the SID is found in namecache OR by ad_lookup_batch().
* req->id1..sid.[prefix, rid] =
* SID if given otherwise SID found will be placed here.
*
* Unix identity:
* req->id2name =
* unixname found will be placed here.
* req->id2domain =
* NOT USED
* res->id.idtype =
* Target type initialized from req->id2.idtype. If
* it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
* will be placed here.
* res->id..[uid or gid] =
* UID/GID found will be placed here.
*
* Others:
* res->retcode =
* Return status for this request will be placed here.
* res->direction =
* Direction found will be placed here. Direction
* meaning whether the resultant mapping is valid
* only from win2unix or bi-directional.
* req->direction =
* INTERNAL USE. Used by idmapd to set various
* flags (_IDMAP_F_xxxx) to aid in processing
* of the request.
* req->id2.idtype =
* INTERNAL USE. Initially this is the requested target
* type and is used to initialize res->id.idtype.
* ad_lookup_batch() uses this field temporarily to store
* sid_type obtained by the batched AD lookups and after
* use resets it to IDMAP_NONE to prevent xdr from
* mis-interpreting the contents of req->id2.
* req->id2.idmap_id_u.uid =
* INTERNAL USE. If the AD lookup finds IDMU data
* (uidNumber or gidNumber, depending on the type of
* the entry), it's left here.
*/
/*
* This function does the following:
* 1. Lookup well-known SIDs table.
* 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
* 3. Lookup cache.
* 4. Check if the client does not want new mapping to be allocated
* in which case this pass is the final pass.
* 5. Set AD lookup flag if it determines that the next stage needs
* to do AD lookup.
*/
idmap_retcode
sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
idmap_id_res *res)
{
idmap_retcode retcode;
int wksid;
/* Initialize result */
res->id.idtype = req->id2.idtype;
res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
res->direction = IDMAP_DIRECTION_UNDEF;
wksid = 0;
if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
/* They have to give us *something* to work with! */
if (req->id1name == NULL) {
retcode = IDMAP_ERR_ARG;
goto out;
}
/* sanitize sidprefix */
free(req->id1.idmap_id_u.sid.prefix);
req->id1.idmap_id_u.sid.prefix = NULL;
/* Allow for a fully-qualified name in the "name" parameter */
if (req->id1domain == NULL) {
char *p;
p = strchr(req->id1name, '@');
if (p != NULL) {
char *q;
q = req->id1name;
req->id1name = uu_strndup(q, p - req->id1name);
req->id1domain = strdup(p+1);
free(q);
if (req->id1name == NULL ||
req->id1domain == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
}
}
/* Lookup well-known SIDs table */
retcode = lookup_wksids_sid2pid(req, res, &wksid);
if (retcode == IDMAP_SUCCESS) {
/* Found a well-known account with a hardwired mapping */
TRACE(req, res, "Hardwired mapping");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res,
"Well-known account lookup failed, code %d", retcode);
goto out;
}
if (wksid) {
/* Found a well-known account, but no mapping */
TRACE(req, res, "Well-known account");
} else {
TRACE(req, res, "Not a well-known account");
/* Check if this is a localsid */
retcode = lookup_localsid2pid(req, res);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Local SID");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res,
"Local SID lookup error=%d", retcode);
goto out;
}
TRACE(req, res, "Not a local SID");
if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
retcode = IDMAP_ERR_NONE_GENERATED;
goto out;
}
}
/*
* If this is a name-based request and we don't have a domain,
* use the default domain. Note that the well-known identity
* cases will have supplied a SID prefix already, and that we
* don't (yet?) support looking up a local user through a Windows
* style name.
*/
if (req->id1.idmap_id_u.sid.prefix == NULL &&
req->id1name != NULL && req->id1domain == NULL) {
if (state->defdom == NULL) {
retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
goto out;
}
req->id1domain = strdup(state->defdom);
if (req->id1domain == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
TRACE(req, res, "Added default domain");
}
/* Lookup cache */
retcode = lookup_cache_sid2pid(state->cache, req, res);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Found in mapping cache");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Mapping cache lookup error=%d", retcode);
goto out;
}
TRACE(req, res, "Not found in mapping cache");
if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
retcode = IDMAP_ERR_NONE_GENERATED;
goto out;
}
/*
* Failed to find non-expired entry in cache. Next step is
* to determine if this request needs to be batched for AD lookup.
*
* At this point we have either sid or winname or both. If we don't
* have both then lookup name_cache for the sid or winname
* whichever is missing. If not found then this request will be
* batched for AD lookup.
*/
retcode = lookup_name_cache(state->cache, req, res);
if (retcode == IDMAP_SUCCESS) {
if (res->id.idtype == IDMAP_POSIXID) {
if (req->id1.idtype == IDMAP_USID)
res->id.idtype = IDMAP_UID;
else
res->id.idtype = IDMAP_GID;
}
} else if (retcode != IDMAP_ERR_NOTFOUND)
goto out;
if (_idmapdstate.cfg->pgcfg.use_lsa &&
_idmapdstate.cfg->pgcfg.domain_name != NULL) {
/*
* If we don't have both name and SID, try looking up the
* entry with LSA.
*/
if (req->id1.idmap_id_u.sid.prefix != NULL &&
req->id1name == NULL) {
retcode = lookup_lsa_by_sid(
req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid,
&req->id1name, &req->id1domain, &req->id1.idtype);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Found with LSA");
} else if (retcode == IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Not found with LSA");
} else {
TRACE(req, res, "LSA error %d", retcode);
goto out;
}
} else if (req->id1name != NULL &&
req->id1.idmap_id_u.sid.prefix == NULL) {
char *canonname;
char *canondomain;
retcode = lookup_lsa_by_name(
req->id1name, req->id1domain,
&req->id1.idmap_id_u.sid.prefix,
&req->id1.idmap_id_u.sid.rid,
&canonname, &canondomain,
&req->id1.idtype);
if (retcode == IDMAP_SUCCESS) {
free(req->id1name);
req->id1name = canonname;
free(req->id1domain);
req->id1domain = canondomain;
TRACE(req, res, "Found with LSA");
} else if (retcode == IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Not found with LSA");
} else {
TRACE(req, res, "LSA error %d", retcode);
goto out;
}
}
}
/*
* Set the flag to indicate that we are not done yet so that
* subsequent passes considers this request for name-based
* mapping and ephemeral mapping.
*/
state->sid2pid_done = FALSE;
req->direction |= _IDMAP_F_NOTDONE;
/*
* Even if we have both sid and winname, we still may need to batch
* this request for AD lookup if we don't have unixname and
* directory-based name mapping (AD or mixed) is enabled.
* We avoid AD lookup for well-known SIDs because they don't have
* regular AD objects.
*/
if (retcode != IDMAP_SUCCESS ||
(!wksid && req->id2name == NULL &&
AD_OR_MIXED_MODE(res->id.idtype, state)) ||
(!wksid && res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID &&
state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)) {
retcode = IDMAP_SUCCESS;
req->direction |= _IDMAP_F_LOOKUP_AD;
state->ad_nqueries++;
} else if (NLDAP_MODE(res->id.idtype, state)) {
req->direction |= _IDMAP_F_LOOKUP_NLDAP;
state->nldap_nqueries++;
}
out:
res->retcode = idmap_stat4prot(retcode);
/*
* If we are done and there was an error then set fallback pid
* in the result.
*/
if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
res->id.idmap_id_u.uid = UID_NOBODY;
return (retcode);
}
/*
* Generate SID using the following convention
* <machine-sid-prefix>-<1000 + uid>
* <machine-sid-prefix>-<2^31 + gid>
*/
static
idmap_retcode
generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
int fallback)
{
free(res->id.idmap_id_u.sid.prefix);
res->id.idmap_id_u.sid.prefix = NULL;
/*
* Diagonal mapping for localSIDs not supported because of the
* way we generate localSIDs.
*/
if (is_user && res->id.idtype == IDMAP_GSID)
return (IDMAP_ERR_NOTGROUP);
if (!is_user && res->id.idtype == IDMAP_USID)
return (IDMAP_ERR_NOTUSER);
/* Skip 1000 UIDs */
if (is_user &&
req->id1.idmap_id_u.uid + LOCALRID_UID_MIN > LOCALRID_UID_MAX)
return (IDMAP_ERR_NOMAPPING);
RDLOCK_CONFIG();
/*
* machine_sid is never NULL because if it is we won't be here.
* No need to assert because strdup(NULL) will core anyways.
*/
res->id.idmap_id_u.sid.prefix =
strdup(_idmapdstate.cfg->pgcfg.machine_sid);
if (res->id.idmap_id_u.sid.prefix == NULL) {
UNLOCK_CONFIG();
idmapdlog(LOG_ERR, "Out of memory");
return (IDMAP_ERR_MEMORY);
}
UNLOCK_CONFIG();
res->id.idmap_id_u.sid.rid =
(is_user) ? req->id1.idmap_id_u.uid + LOCALRID_UID_MIN :
req->id1.idmap_id_u.gid + LOCALRID_GID_MIN;
res->direction = IDMAP_DIRECTION_BI;
if (res->id.idtype == IDMAP_SID)
res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
if (!fallback) {
res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
}
/*
* Don't update name_cache because local sids don't have
* valid windows names.
*/
req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
return (IDMAP_SUCCESS);
}
static
idmap_retcode
lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
{
char *sidprefix;
uint32_t rid;
int s;
/*
* If the sidprefix == localsid then UID = last RID - 1000 or
* GID = last RID - 2^31.
*/
if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
/* This means we are looking up by winname */
return (IDMAP_ERR_NOTFOUND);
rid = req->id1.idmap_id_u.sid.rid;
RDLOCK_CONFIG();
s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
UNLOCK_CONFIG();
/*
* If the given sidprefix does not match machine_sid then this is
* not a local SID.
*/
if (s != 0)
return (IDMAP_ERR_NOTFOUND);
switch (res->id.idtype) {
case IDMAP_UID:
if (rid < LOCALRID_UID_MIN || rid > LOCALRID_UID_MAX)
return (IDMAP_ERR_ARG);
res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
break;
case IDMAP_GID:
if (rid < LOCALRID_GID_MIN)
return (IDMAP_ERR_ARG);
res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
break;
case IDMAP_POSIXID:
if (rid >= LOCALRID_GID_MIN) {
res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
res->id.idtype = IDMAP_GID;
} else if (rid >= LOCALRID_UID_MIN) {
res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
res->id.idtype = IDMAP_UID;
} else {
return (IDMAP_ERR_ARG);
}
break;
default:
return (IDMAP_ERR_NOTSUPPORTED);
}
res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
return (IDMAP_SUCCESS);
}
/*
* Name service lookup by unixname to get pid
*/
static
idmap_retcode
ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
{
struct passwd pwd, *pwdp;
struct group grp, *grpp;
char *buf;
static size_t pwdbufsiz = 0;
static size_t grpbufsiz = 0;
switch (id->idtype) {
case IDMAP_UID:
if (pwdbufsiz == 0)
pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
buf = alloca(pwdbufsiz);
pwdp = getpwnam_r(name, &pwd, buf, pwdbufsiz);
if (pwdp == NULL && errno == 0 && lower_name != NULL &&
name != lower_name && strcmp(name, lower_name) != 0)
pwdp = getpwnam_r(lower_name, &pwd, buf, pwdbufsiz);
if (pwdp == NULL) {
if (errno == 0)
return (IDMAP_ERR_NOTFOUND);
else
return (IDMAP_ERR_INTERNAL);
}
id->idmap_id_u.uid = pwd.pw_uid;
break;
case IDMAP_GID:
if (grpbufsiz == 0)
grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
buf = alloca(grpbufsiz);
grpp = getgrnam_r(name, &grp, buf, grpbufsiz);
if (grpp == NULL && errno == 0 && lower_name != NULL &&
name != lower_name && strcmp(name, lower_name) != 0)
grpp = getgrnam_r(lower_name, &grp, buf, grpbufsiz);
if (grpp == NULL) {
if (errno == 0)
return (IDMAP_ERR_NOTFOUND);
else
return (IDMAP_ERR_INTERNAL);
}
id->idmap_id_u.gid = grp.gr_gid;
break;
default:
return (IDMAP_ERR_ARG);
}
return (IDMAP_SUCCESS);
}
/*
* Name service lookup by pid to get unixname
*/
static
idmap_retcode
ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
{
struct passwd pwd;
struct group grp;
char *buf;
static size_t pwdbufsiz = 0;
static size_t grpbufsiz = 0;
if (is_user) {
if (pwdbufsiz == 0)
pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
buf = alloca(pwdbufsiz);
errno = 0;
if (getpwuid_r(pid, &pwd, buf, pwdbufsiz) == NULL) {
if (errno == 0)
return (IDMAP_ERR_NOTFOUND);
else
return (IDMAP_ERR_INTERNAL);
}
*unixname = strdup(pwd.pw_name);
} else {
if (grpbufsiz == 0)
grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
buf = alloca(grpbufsiz);
errno = 0;
if (getgrgid_r(pid, &grp, buf, grpbufsiz) == NULL) {
if (errno == 0)
return (IDMAP_ERR_NOTFOUND);
else
return (IDMAP_ERR_INTERNAL);
}
*unixname = strdup(grp.gr_name);
}
if (*unixname == NULL)
return (IDMAP_ERR_MEMORY);
return (IDMAP_SUCCESS);
}
/*
* Name-based mapping
*
* Case 1: If no rule matches do ephemeral
*
* Case 2: If rule matches and unixname is "" then return no mapping.
*
* Case 3: If rule matches and unixname is specified then lookup name
* service using the unixname. If unixname not found then return no mapping.
*
* Case 4: If rule matches and unixname is * then lookup name service
* using winname as the unixname. If unixname not found then process
* other rules using the lookup order. If no other rule matches then do
* ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
* This allows us to specify a fallback unixname per _domain_ or no mapping
* instead of the default behaviour of doing ephemeral mapping.
*
* Example 1:
* *@sfbay == *
* If looking up windows users foo@sfbay and foo does not exists in
* the name service then foo@sfbay will be mapped to an ephemeral id.
*
* Example 2:
* *@sfbay == *
* *@sfbay => guest
* If looking up windows users foo@sfbay and foo does not exists in
* the name service then foo@sfbay will be mapped to guest.
*
* Example 3:
* *@sfbay == *
* *@sfbay => ""
* If looking up windows users foo@sfbay and foo does not exists in
* the name service then we will return no mapping for foo@sfbay.
*
*/
static
idmap_retcode
name_based_mapping_sid2pid(lookup_state_t *state,
idmap_mapping *req, idmap_id_res *res)
{
const char *unixname, *windomain;
char *sql = NULL, *errmsg = NULL, *lower_winname = NULL;
idmap_retcode retcode;
char *end, *lower_unixname, *winname;
const char **values;
sqlite_vm *vm = NULL;
int ncol, r, is_user, is_wuser;
idmap_namerule *rule = &res->info.how.idmap_how_u.rule;
int direction;
const char *me = "name_based_mapping_sid2pid";
assert(req->id1name != NULL); /* We have winname */
assert(req->id2name == NULL); /* We don't have unixname */
winname = req->id1name;
windomain = req->id1domain;
switch (req->id1.idtype) {
case IDMAP_USID:
is_wuser = 1;
break;
case IDMAP_GSID:
is_wuser = 0;
break;
default:
idmapdlog(LOG_ERR, "%s: Unable to determine if the "
"given Windows id is user or group.", me);
return (IDMAP_ERR_INTERNAL);
}
switch (res->id.idtype) {
case IDMAP_UID:
is_user = 1;
break;
case IDMAP_GID:
is_user = 0;
break;
case IDMAP_POSIXID:
is_user = is_wuser;
res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
break;
}
if (windomain == NULL)
windomain = "";
if ((lower_winname = tolower_u8(winname)) == NULL)
lower_winname = winname; /* hope for the best */
sql = sqlite_mprintf(
"SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
"FROM namerules WHERE "
"w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
"(winname = %Q OR winname = '*') AND "
"(windomain = %Q OR windomain = '*') "
"ORDER BY w2u_order ASC;",
is_user, is_wuser, lower_winname, windomain);
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "%s: database error (%s)", me,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
goto out;
}
for (;;) {
r = sqlite_step(vm, &ncol, &values, NULL);
assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
if (r == SQLITE_ROW) {
if (ncol < 5) {
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
TRACE(req, res, "Matching rule: %s@%s -> %s",
values[2] == NULL ? "(null)" : values[2],
values[3] == NULL ? "(null)" : values[3],
values[0] == NULL ? "(null)" : values[0]);
if (values[0] == NULL) {
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
if (values[1] != NULL)
direction =
(strtol(values[1], &end, 10) == 0)?
IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
else
direction = IDMAP_DIRECTION_W2U;
if (EMPTY_NAME(values[0])) {
TRACE(req, res, "Mapping inhibited");
idmap_namerule_set(rule, values[3], values[2],
values[0], is_user, is_wuser,
strtol(values[4], &end, 10),
direction);
retcode = IDMAP_ERR_NOMAPPING;
goto out;
}
if (values[0][0] == '*') {
unixname = winname;
lower_unixname = lower_winname;
} else {
unixname = values[0];
lower_unixname = NULL;
}
retcode = ns_lookup_byname(unixname, lower_unixname,
&res->id);
if (retcode == IDMAP_SUCCESS) {
break;
} else if (retcode == IDMAP_ERR_NOTFOUND) {
if (values[0][0] == '*') {
TRACE(req, res,
"%s not found, continuing",
unixname);
/* Case 4 */
continue;
} else {
TRACE(req, res,
"%s not found, error", unixname);
/* Case 3 */
idmap_namerule_set(rule, values[3],
values[2], values[0], is_user,
is_wuser,
strtol(values[4], &end, 10),
direction);
retcode = IDMAP_ERR_NOMAPPING;
}
} else {
TRACE(req, res, "Looking up %s error=%d",
unixname, retcode);
}
goto out;
} else if (r == SQLITE_DONE) {
TRACE(req, res, "No matching rule");
retcode = IDMAP_ERR_NOTFOUND;
goto out;
} else {
(void) sqlite_finalize(vm, &errmsg);
vm = NULL;
idmapdlog(LOG_ERR, "%s: database error (%s)", me,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
}
/* Found */
if (values[1] != NULL)
res->direction =
(strtol(values[1], &end, 10) == 0)?
IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
else
res->direction = IDMAP_DIRECTION_W2U;
req->id2name = strdup(unixname);
if (req->id2name == NULL) {
retcode = IDMAP_ERR_MEMORY;
goto out;
}
TRACE(req, res, "UNIX name found");
idmap_namerule_set(rule, values[3], values[2],
values[0], is_user, is_wuser, strtol(values[4], &end, 10),
res->direction);
out:
if (retcode != IDMAP_SUCCESS &&
retcode != IDMAP_ERR_NOTFOUND &&
retcode != IDMAP_ERR_NOMAPPING) {
TRACE(req, res, "Rule processing error, code=%d", retcode);
}
if (sql != NULL)
sqlite_freemem(sql);
if (retcode != IDMAP_ERR_NOTFOUND) {
res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
res->info.src = IDMAP_MAP_SRC_NEW;
}
if (lower_winname != NULL && lower_winname != winname)
free(lower_winname);
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
return (retcode);
}
static
int
get_next_eph_uid(uid_t *next_uid)
{
uid_t uid;
gid_t gid;
int err;
*next_uid = (uid_t)-1;
pthread_mutex_lock(&_idmapdstate.id_lock);
uid = _idmapdstate.next_uid++;
if (uid >= _idmapdstate.limit_uid) {
if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0) {
pthread_mutex_unlock(&_idmapdstate.id_lock);
return (err);
}
_idmapdstate.limit_uid = uid + 8192;
_idmapdstate.next_uid = uid + 1;
}
pthread_mutex_unlock(&_idmapdstate.id_lock);
*next_uid = uid;
return (0);
}
static
int
get_next_eph_gid(gid_t *next_gid)
{
uid_t uid;
gid_t gid;
int err;
*next_gid = (uid_t)-1;
pthread_mutex_lock(&_idmapdstate.id_lock);
gid = _idmapdstate.next_gid++;
if (gid >= _idmapdstate.limit_gid) {
if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0) {
pthread_mutex_unlock(&_idmapdstate.id_lock);
return (err);
}
_idmapdstate.limit_gid = gid + 8192;
_idmapdstate.next_gid = gid + 1;
}
pthread_mutex_unlock(&_idmapdstate.id_lock);
*next_gid = gid;
return (0);
}
static
int
gethash(const char *str, uint32_t num, uint_t htsize)
{
uint_t hval, i, len;
if (str == NULL)
return (0);
for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
hval += str[i];
hval += (hval << 10);
hval ^= (hval >> 6);
}
for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
hval += str[i];
hval += (hval << 10);
hval ^= (hval >> 6);
}
hval += (hval << 3);
hval ^= (hval >> 11);
hval += (hval << 15);
return (hval % htsize);
}
static
int
get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
uid_t *pid)
{
uint_t next, key;
uint_t htsize = state->sid_history_size;
idmap_sid *sid;
next = gethash(prefix, rid, htsize);
while (next != htsize) {
key = state->sid_history[next].key;
if (key == htsize)
return (0);
sid = &state->batch->idmap_mapping_batch_val[key].id1.
idmap_id_u.sid;
if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
*pid = state->result->ids.ids_val[key].id.
idmap_id_u.uid;
return (1);
}
next = state->sid_history[next].next;
}
return (0);
}
static
void
add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
{
uint_t hash, next;
uint_t htsize = state->sid_history_size;
hash = next = gethash(prefix, rid, htsize);
while (state->sid_history[next].key != htsize) {
next++;
next %= htsize;
}
state->sid_history[next].key = state->curpos;
if (hash == next)
return;
state->sid_history[next].next = state->sid_history[hash].next;
state->sid_history[hash].next = next;
}
void
cleanup_lookup_state(lookup_state_t *state)
{
free(state->sid_history);
free(state->ad_unixuser_attr);
free(state->ad_unixgroup_attr);
free(state->nldap_winname_attr);
free(state->defdom);
}
/* ARGSUSED */
static
idmap_retcode
dynamic_ephemeral_mapping(lookup_state_t *state,
idmap_mapping *req, idmap_id_res *res)
{
uid_t next_pid;
res->direction = IDMAP_DIRECTION_BI;
if (IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
res->info.src = IDMAP_MAP_SRC_CACHE;
return (IDMAP_SUCCESS);
}
if (state->sid_history != NULL &&
get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid, &next_pid)) {
res->id.idmap_id_u.uid = next_pid;
res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
res->info.src = IDMAP_MAP_SRC_NEW;
return (IDMAP_SUCCESS);
}
if (res->id.idtype == IDMAP_UID) {
if (get_next_eph_uid(&next_pid) != 0)
return (IDMAP_ERR_INTERNAL);
res->id.idmap_id_u.uid = next_pid;
} else {
if (get_next_eph_gid(&next_pid) != 0)
return (IDMAP_ERR_INTERNAL);
res->id.idmap_id_u.gid = next_pid;
}
res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
res->info.src = IDMAP_MAP_SRC_NEW;
if (state->sid_history != NULL)
add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid);
return (IDMAP_SUCCESS);
}
idmap_retcode
sid2pid_second_pass(lookup_state_t *state,
idmap_mapping *req, idmap_id_res *res)
{
idmap_retcode retcode;
idmap_retcode retcode2;
/* Check if second pass is needed */
if (ARE_WE_DONE(req->direction))
return (res->retcode);
/* Get status from previous pass */
retcode = res->retcode;
if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
!EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
EMPTY_STRING(req->id1name)) {
/*
* We are asked to map an unresolvable SID to a UID or
* GID, but, which? We'll treat all unresolvable SIDs
* as users unless the caller specified which of a UID
* or GID they want.
*/
if (req->id1.idtype == IDMAP_SID)
req->id1.idtype = IDMAP_USID;
if (res->id.idtype == IDMAP_POSIXID) {
res->id.idtype = IDMAP_UID;
TRACE(req, res, "Assume unresolvable SID is user");
} else if (res->id.idtype == IDMAP_UID) {
TRACE(req, res, "Must map unresolvable SID to user");
} else if (res->id.idtype == IDMAP_GID) {
TRACE(req, res, "Must map unresolvable SID to group");
}
goto do_eph;
}
if (retcode != IDMAP_SUCCESS)
goto out;
/*
* There are two ways we might get here with a Posix ID:
* - It could be from an expired ephemeral cache entry.
* - It could be from IDMU.
* If it's from IDMU, we need to look up the name, for name-based
* requests and the cache.
*/
if (!IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid) &&
res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
if (req->id2name == NULL) {
/*
* If the lookup fails, go ahead anyway.
* The general UNIX rule is that it's OK to
* have a UID or GID that isn't in the
* name service.
*/
retcode2 = ns_lookup_bypid(res->id.idmap_id_u.uid,
res->id.idtype == IDMAP_UID, &req->id2name);
if (IDMAP_ERROR(retcode2)) {
TRACE(req, res,
"Getting UNIX name, error=%d (ignored)",
retcode2);
} else {
TRACE(req, res, "Found UNIX name");
}
}
goto out;
}
/*
* If directory-based name mapping is enabled then the unixname
* may already have been retrieved from the AD object (AD-mode or
* mixed-mode) or from native LDAP object (nldap-mode) -- done.
*/
if (req->id2name != NULL) {
assert(res->id.idtype != IDMAP_POSIXID);
if (AD_MODE(res->id.idtype, state))
res->direction = IDMAP_DIRECTION_BI;
else if (NLDAP_MODE(res->id.idtype, state))
res->direction = IDMAP_DIRECTION_BI;
else if (MIXED_MODE(res->id.idtype, state))
res->direction = IDMAP_DIRECTION_W2U;
/*
* Special case: (1) If the ad_unixuser_attr and
* ad_unixgroup_attr uses the same attribute
* name and (2) if this is a diagonal mapping
* request and (3) the unixname has been retrieved
* from the AD object -- then we ignore it and fallback
* to name-based mapping rules and ephemeral mapping
*
* Example:
* Properties:
* config/ad_unixuser_attr = "unixname"
* config/ad_unixgroup_attr = "unixname"
* AD user object:
* dn: cn=bob ...
* objectclass: user
* sam: bob
* unixname: bob1234
* AD group object:
* dn: cn=winadmins ...
* objectclass: group
* sam: winadmins
* unixname: unixadmins
*
* In this example whether "unixname" refers to a unixuser
* or unixgroup depends upon the AD object.
*
* $idmap show -c winname:bob gid
* AD lookup by "samAccountName=bob" for
* "ad_unixgroup_attr (i.e unixname)" for directory-based
* mapping would get "bob1234" which is not what we want.
* Now why not getgrnam_r("bob1234") and use it if it
* is indeed a unixgroup? That's because Unix can have
* users and groups with the same name and we clearly
* don't know the intention of the admin here.
* Therefore we ignore this and fallback to name-based
* mapping rules or ephemeral mapping.
*/
if ((AD_MODE(res->id.idtype, state) ||
MIXED_MODE(res->id.idtype, state)) &&
state->ad_unixuser_attr != NULL &&
state->ad_unixgroup_attr != NULL &&
strcasecmp(state->ad_unixuser_attr,
state->ad_unixgroup_attr) == 0 &&
((req->id1.idtype == IDMAP_USID &&
res->id.idtype == IDMAP_GID) ||
(req->id1.idtype == IDMAP_GSID &&
res->id.idtype == IDMAP_UID))) {
TRACE(req, res, "Ignoring UNIX name found in AD");
free(req->id2name);
req->id2name = NULL;
res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
/* fallback */
} else {
if (res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
retcode = ns_lookup_byname(req->id2name,
NULL, &res->id);
if (retcode != IDMAP_SUCCESS) {
/*
* If ns_lookup_byname() fails that
* means the unixname (req->id2name),
* which was obtained from the AD
* object by directory-based mapping,
* is not a valid Unix user/group and
* therefore we return the error to the
* client instead of doing rule-based
* mapping or ephemeral mapping. This
* way the client can detect the issue.
*/
TRACE(req, res,
"UNIX lookup error=%d", retcode);
goto out;
}
TRACE(req, res, "UNIX lookup");
}
goto out;
}
}
/* Free any mapping info from Directory based mapping */
if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
idmap_how_clear(&res->info.how);
/*
* If we don't have unixname then evaluate local name-based
* mapping rules.
*/
retcode = name_based_mapping_sid2pid(state, req, res);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Rule-based mapping");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Rule-based mapping error=%d", retcode);
goto out;
}
do_eph:
/* If not found, do ephemeral mapping */
retcode = dynamic_ephemeral_mapping(state, req, res);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Ephemeral mapping");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res, "Ephemeral mapping error=%d", retcode);
goto out;
}
out:
res->retcode = idmap_stat4prot(retcode);
if (res->retcode != IDMAP_SUCCESS) {
req->direction = _IDMAP_F_DONE;
res->id.idmap_id_u.uid = UID_NOBODY;
}
if (!ARE_WE_DONE(req->direction))
state->sid2pid_done = FALSE;
return (retcode);
}
idmap_retcode
update_cache_pid2sid(lookup_state_t *state,
idmap_mapping *req, idmap_id_res *res)
{
char *sql = NULL;
idmap_retcode retcode;
idmap_retcode retcode2;
char *map_dn = NULL;
char *map_attr = NULL;
char *map_value = NULL;
char *map_windomain = NULL;
char *map_winname = NULL;
char *map_unixname = NULL;
int map_is_nt4 = FALSE;
/* Check if we need to cache anything */
if (ARE_WE_DONE(req->direction))
return (IDMAP_SUCCESS);
/* We don't cache negative entries */
if (res->retcode != IDMAP_SUCCESS)
return (IDMAP_SUCCESS);
assert(res->direction != IDMAP_DIRECTION_UNDEF);
assert(req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID);
assert(res->id.idtype != IDMAP_SID);
/*
* If we've gotten to this point and we *still* don't know the
* unixname, well, we'd like to have it now for the cache.
*
* If we truly always need it for the cache, we should probably
* look it up once at the beginning, rather than "at need" in
* several places as is now done. However, it's not really clear
* that we *do* need it in the cache; there's a decent argument
* that the cache should contain only SIDs and PIDs, so we'll
* leave our options open by doing it "at need" here too.
*
* If we can't find it... c'est la vie.
*/
if (req->id1name == NULL) {
retcode2 = ns_lookup_bypid(req->id1.idmap_id_u.uid,
req->id1.idtype == IDMAP_UID, &req->id1name);
if (retcode2 == IDMAP_SUCCESS)
TRACE(req, res, "Found UNIX name");
else
TRACE(req, res, "Getting UNIX name error=%d", retcode2);
}
assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
switch (res->info.how.map_type) {
case IDMAP_MAP_TYPE_DS_AD:
map_dn = res->info.how.idmap_how_u.ad.dn;
map_attr = res->info.how.idmap_how_u.ad.attr;
map_value = res->info.how.idmap_how_u.ad.value;
break;
case IDMAP_MAP_TYPE_DS_NLDAP:
map_dn = res->info.how.idmap_how_u.nldap.dn;
map_attr = res->info.how.idmap_how_u.nldap.attr;
map_value = res->info.how.idmap_how_u.nldap.value;
break;
case IDMAP_MAP_TYPE_RULE_BASED:
map_windomain = res->info.how.idmap_how_u.rule.windomain;
map_winname = res->info.how.idmap_how_u.rule.winname;
map_unixname = res->info.how.idmap_how_u.rule.unixname;
map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
break;
case IDMAP_MAP_TYPE_EPHEMERAL:
break;
case IDMAP_MAP_TYPE_LOCAL_SID:
break;
case IDMAP_MAP_TYPE_IDMU:
map_dn = res->info.how.idmap_how_u.idmu.dn;
map_attr = res->info.how.idmap_how_u.idmu.attr;
map_value = res->info.how.idmap_how_u.idmu.value;
break;
default:
/* Don't cache other mapping types */
assert(FALSE);
}
/*
* Using NULL for u2w instead of 0 so that our trigger allows
* the same pid to be the destination in multiple entries
*/
sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
"(sidprefix, rid, windomain, canon_winname, pid, unixname, "
"is_user, is_wuser, expiration, w2u, u2w, "
"map_type, map_dn, map_attr, map_value, map_windomain, "
"map_winname, map_unixname, map_is_nt4) "
"VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
"strftime('%%s','now') + %u, %q, 1, "
"%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
(res->id.idtype == IDMAP_USID) ? 1 : 0,
state->id_cache_timeout,
(res->direction == 0) ? "1" : NULL,
res->info.how.map_type, map_dn, map_attr, map_value,
map_windomain, map_winname, map_unixname, map_is_nt4);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
if (retcode != IDMAP_SUCCESS)
goto out;
state->pid2sid_done = FALSE;
sqlite_freemem(sql);
sql = NULL;
/* Check if we need to update namecache */
if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
goto out;
if (req->id2name == NULL)
goto out;
sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
"(sidprefix, rid, canon_name, domain, type, expiration) "
"VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + %u); ",
res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
req->id2name, req->id2domain,
res->id.idtype, state->name_cache_timeout);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
out:
if (sql != NULL)
sqlite_freemem(sql);
return (retcode);
}
idmap_retcode
update_cache_sid2pid(lookup_state_t *state,
idmap_mapping *req, idmap_id_res *res)
{
char *sql = NULL;
idmap_retcode retcode;
int is_eph_user;
char *map_dn = NULL;
char *map_attr = NULL;
char *map_value = NULL;
char *map_windomain = NULL;
char *map_winname = NULL;
char *map_unixname = NULL;
int map_is_nt4 = FALSE;
/* Check if we need to cache anything */
if (ARE_WE_DONE(req->direction))
return (IDMAP_SUCCESS);
/* We don't cache negative entries */
if (res->retcode != IDMAP_SUCCESS)
return (IDMAP_SUCCESS);
if (req->direction & _IDMAP_F_EXP_EPH_UID)
is_eph_user = 1;
else if (req->direction & _IDMAP_F_EXP_EPH_GID)
is_eph_user = 0;
else
is_eph_user = -1;
if (is_eph_user >= 0 &&
!IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
sql = sqlite_mprintf("UPDATE idmap_cache "
"SET w2u = 0 WHERE "
"sidprefix = %Q AND rid = %u AND w2u = 1 AND "
"pid >= 2147483648 AND is_user = %d;",
req->id1.idmap_id_u.sid.prefix,
req->id1.idmap_id_u.sid.rid,
is_eph_user);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
if (retcode != IDMAP_SUCCESS)
goto out;
sqlite_freemem(sql);
sql = NULL;
}
assert(res->direction != IDMAP_DIRECTION_UNDEF);
assert(res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID);
switch (res->info.how.map_type) {
case IDMAP_MAP_TYPE_DS_AD:
map_dn = res->info.how.idmap_how_u.ad.dn;
map_attr = res->info.how.idmap_how_u.ad.attr;
map_value = res->info.how.idmap_how_u.ad.value;
break;
case IDMAP_MAP_TYPE_DS_NLDAP:
map_dn = res->info.how.idmap_how_u.nldap.dn;
map_attr = res->info.how.idmap_how_u.ad.attr;
map_value = res->info.how.idmap_how_u.nldap.value;
break;
case IDMAP_MAP_TYPE_RULE_BASED:
map_windomain = res->info.how.idmap_how_u.rule.windomain;
map_winname = res->info.how.idmap_how_u.rule.winname;
map_unixname = res->info.how.idmap_how_u.rule.unixname;
map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
break;
case IDMAP_MAP_TYPE_EPHEMERAL:
break;
case IDMAP_MAP_TYPE_IDMU:
map_dn = res->info.how.idmap_how_u.idmu.dn;
map_attr = res->info.how.idmap_how_u.idmu.attr;
map_value = res->info.how.idmap_how_u.idmu.value;
break;
default:
/* Don't cache other mapping types */
assert(FALSE);
}
sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
"(sidprefix, rid, windomain, canon_winname, pid, unixname, "
"is_user, is_wuser, expiration, w2u, u2w, "
"map_type, map_dn, map_attr, map_value, map_windomain, "
"map_winname, map_unixname, map_is_nt4) "
"VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
"strftime('%%s','now') + %u, 1, %q, "
"%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
(req->id1domain != NULL) ? req->id1domain : "", req->id1name,
res->id.idmap_id_u.uid, req->id2name,
(res->id.idtype == IDMAP_UID) ? 1 : 0,
(req->id1.idtype == IDMAP_USID) ? 1 : 0,
state->id_cache_timeout,
(res->direction == 0) ? "1" : NULL,
res->info.how.map_type, map_dn, map_attr, map_value,
map_windomain, map_winname, map_unixname, map_is_nt4);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
if (retcode != IDMAP_SUCCESS)
goto out;
state->sid2pid_done = FALSE;
sqlite_freemem(sql);
sql = NULL;
/* Check if we need to update namecache */
if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
goto out;
if (EMPTY_STRING(req->id1name))
goto out;
sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
"(sidprefix, rid, canon_name, domain, type, expiration) "
"VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + %u); ",
req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
req->id1name, req->id1domain,
req->id1.idtype, state->name_cache_timeout);
if (sql == NULL) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
out:
if (sql != NULL)
sqlite_freemem(sql);
return (retcode);
}
static
idmap_retcode
lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
int is_user)
{
char *end;
char *sql = NULL;
const char **values;
sqlite_vm *vm = NULL;
int ncol;
idmap_retcode retcode = IDMAP_SUCCESS;
time_t curtime;
idmap_id_type idtype;
/* Current time */
errno = 0;
if ((curtime = time(NULL)) == (time_t)-1) {
idmapdlog(LOG_ERR, "Failed to get current time (%s)",
strerror(errno));
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
/* SQL to lookup the cache by pid or by unixname */
if (req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
sql = sqlite_mprintf("SELECT sidprefix, rid, "
"canon_winname, windomain, w2u, is_wuser, "
"map_type, map_dn, map_attr, map_value, map_windomain, "
"map_winname, map_unixname, map_is_nt4 "
"FROM idmap_cache WHERE "
"pid = %u AND u2w = 1 AND is_user = %d AND "
"(pid >= 2147483648 OR "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d));",
req->id1.idmap_id_u.uid, is_user, curtime);
} else if (req->id1name != NULL) {
sql = sqlite_mprintf("SELECT sidprefix, rid, "
"canon_winname, windomain, w2u, is_wuser, "
"map_type, map_dn, map_attr, map_value, map_windomain, "
"map_winname, map_unixname, map_is_nt4 "
"FROM idmap_cache WHERE "
"unixname = %Q AND u2w = 1 AND is_user = %d AND "
"(pid >= 2147483648 OR "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d));",
req->id1name, is_user, curtime);
} else {
retcode = IDMAP_ERR_ARG;
goto out;
}
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
retcode = sql_compile_n_step_once(
cache, sql, &vm, &ncol, 14, &values);
sqlite_freemem(sql);
if (retcode == IDMAP_ERR_NOTFOUND)
goto out;
else if (retcode == IDMAP_SUCCESS) {
/* sanity checks */
if (values[0] == NULL || values[1] == NULL) {
retcode = IDMAP_ERR_CACHE;
goto out;
}
switch (res->id.idtype) {
case IDMAP_SID:
case IDMAP_USID:
case IDMAP_GSID:
idtype = strtol(values[5], &end, 10) == 1
? IDMAP_USID : IDMAP_GSID;
if (res->id.idtype == IDMAP_USID &&
idtype != IDMAP_USID) {
retcode = IDMAP_ERR_NOTUSER;
goto out;
} else if (res->id.idtype == IDMAP_GSID &&
idtype != IDMAP_GSID) {
retcode = IDMAP_ERR_NOTGROUP;
goto out;
}
res->id.idtype = idtype;
res->id.idmap_id_u.sid.rid =
strtoul(values[1], &end, 10);
res->id.idmap_id_u.sid.prefix = strdup(values[0]);
if (res->id.idmap_id_u.sid.prefix == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
if (values[4] != NULL)
res->direction =
(strtol(values[4], &end, 10) == 0)?
IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
else
res->direction = IDMAP_DIRECTION_U2W;
if (values[2] == NULL)
break;
req->id2name = strdup(values[2]);
if (req->id2name == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
if (values[3] == NULL)
break;
req->id2domain = strdup(values[3]);
if (req->id2domain == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
break;
default:
retcode = IDMAP_ERR_NOTSUPPORTED;
break;
}
if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
res->info.src = IDMAP_MAP_SRC_CACHE;
res->info.how.map_type = strtoul(values[6], &end, 10);
switch (res->info.how.map_type) {
case IDMAP_MAP_TYPE_DS_AD:
res->info.how.idmap_how_u.ad.dn =
strdup(values[7]);
res->info.how.idmap_how_u.ad.attr =
strdup(values[8]);
res->info.how.idmap_how_u.ad.value =
strdup(values[9]);
break;
case IDMAP_MAP_TYPE_DS_NLDAP:
res->info.how.idmap_how_u.nldap.dn =
strdup(values[7]);
res->info.how.idmap_how_u.nldap.attr =
strdup(values[8]);
res->info.how.idmap_how_u.nldap.value =
strdup(values[9]);
break;
case IDMAP_MAP_TYPE_RULE_BASED:
res->info.how.idmap_how_u.rule.windomain =
strdup(values[10]);
res->info.how.idmap_how_u.rule.winname =
strdup(values[11]);
res->info.how.idmap_how_u.rule.unixname =
strdup(values[12]);
res->info.how.idmap_how_u.rule.is_nt4 =
strtoul(values[13], &end, 10);
res->info.how.idmap_how_u.rule.is_user =
is_user;
res->info.how.idmap_how_u.rule.is_wuser =
strtol(values[5], &end, 10);
break;
case IDMAP_MAP_TYPE_EPHEMERAL:
break;
case IDMAP_MAP_TYPE_LOCAL_SID:
break;
case IDMAP_MAP_TYPE_KNOWN_SID:
break;
case IDMAP_MAP_TYPE_IDMU:
res->info.how.idmap_how_u.idmu.dn =
strdup(values[7]);
res->info.how.idmap_how_u.idmu.attr =
strdup(values[8]);
res->info.how.idmap_how_u.idmu.value =
strdup(values[9]);
break;
default:
/* Unknown mapping type */
assert(FALSE);
}
}
}
out:
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
return (retcode);
}
/*
* Given:
* cache sqlite handle
* name Windows user name
* domain Windows domain name
*
* Return: Error code
*
* *canonname Canonical name (if canonname is non-NULL) [1]
* *sidprefix SID prefix [1]
* *rid RID
* *type Type of name
*
* [1] malloc'ed, NULL on error
*/
static
idmap_retcode
lookup_cache_name2sid(
sqlite *cache,
const char *name,
const char *domain,
char **canonname,
char **sidprefix,
idmap_rid_t *rid,
idmap_id_type *type)
{
char *end, *lower_name;
char *sql;
const char **values;
sqlite_vm *vm = NULL;
int ncol;
time_t curtime;
idmap_retcode retcode;
*sidprefix = NULL;
if (canonname != NULL)
*canonname = NULL;
/* Get current time */
errno = 0;
if ((curtime = time(NULL)) == (time_t)-1) {
idmapdlog(LOG_ERR, "Failed to get current time (%s)",
strerror(errno));
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
/* SQL to lookup the cache */
if ((lower_name = tolower_u8(name)) == NULL)
lower_name = (char *)name;
sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
"FROM name_cache WHERE name = %Q AND domain = %Q AND "
"(expiration = 0 OR expiration ISNULL OR "
"expiration > %d);", lower_name, domain, curtime);
if (lower_name != name)
free(lower_name);
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
sqlite_freemem(sql);
if (retcode != IDMAP_SUCCESS)
goto out;
if (type != NULL) {
if (values[2] == NULL) {
retcode = IDMAP_ERR_CACHE;
goto out;
}
*type = xlate_legacy_type(strtol(values[2], &end, 10));
}
if (values[0] == NULL || values[1] == NULL) {
retcode = IDMAP_ERR_CACHE;
goto out;
}
if (canonname != NULL) {
assert(values[3] != NULL);
*canonname = strdup(values[3]);
if (*canonname == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
}
*sidprefix = strdup(values[0]);
if (*sidprefix == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
*rid = strtoul(values[1], &end, 10);
retcode = IDMAP_SUCCESS;
out:
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
if (retcode != IDMAP_SUCCESS) {
free(*sidprefix);
*sidprefix = NULL;
if (canonname != NULL) {
free(*canonname);
*canonname = NULL;
}
}
return (retcode);
}
static
idmap_retcode
ad_lookup_by_winname(lookup_state_t *state,
const char *name, const char *domain, int esidtype,
char **dn, char **attr, char **value, char **canonname,
char **sidprefix, idmap_rid_t *rid, idmap_id_type *wintype,
char **unixname)
{
int retries;
idmap_query_state_t *qs = NULL;
idmap_retcode rc, retcode;
int i;
int found_ad = 0;
RDLOCK_CONFIG();
if (_idmapdstate.num_gcs > 0) {
for (i = 0; i < _idmapdstate.num_gcs && !found_ad; i++) {
retries = 0;
retry:
retcode = idmap_lookup_batch_start(
_idmapdstate.gcs[i],
1,
_idmapdstate.cfg->pgcfg.directory_based_mapping,
_idmapdstate.cfg->pgcfg.default_domain,
&qs);
if (retcode != IDMAP_SUCCESS) {
if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
retries++ < ADUTILS_DEF_NUM_RETRIES)
goto retry;
degrade_svc(1, "failed to create request for "
"AD lookup by winname");
UNLOCK_CONFIG();
return (retcode);
}
restore_svc();
if (state != NULL && i == 0) {
/*
* Directory based name mapping is only
* performed within the joined forest (i == 0).
* We don't trust other "trusted" forests to
* provide DS-based name mapping information
* because AD's definition of "cross-forest
* trust" does not encompass this sort of
* behavior.
*/
idmap_lookup_batch_set_unixattr(qs,
state->ad_unixuser_attr,
state->ad_unixgroup_attr);
}
retcode = idmap_name2sid_batch_add1(qs, name, domain,
esidtype, dn, attr, value, canonname, sidprefix,
rid, wintype, unixname, NULL, &rc);
if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
idmap_lookup_release_batch(&qs);
continue;
}
found_ad = 1;
if (retcode != IDMAP_SUCCESS)
idmap_lookup_release_batch(&qs);
else
retcode = idmap_lookup_batch_end(&qs);
if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
retries++ < ADUTILS_DEF_NUM_RETRIES)
goto retry;
else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
degrade_svc(1,
"some AD lookups timed out repeatedly");
}
} else {
/* No AD case */
retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
}
UNLOCK_CONFIG();
if (retcode != IDMAP_SUCCESS) {
idmapdlog(LOG_NOTICE,
"AD lookup of winname %s@%s failed, error code %d",
name == NULL ? "(null)" : name,
domain == NULL ? "(null)" : domain,
retcode);
return (retcode);
}
return (rc);
}
/*
* Given:
* cache sqlite handle to cache
* name Windows user name
* domain Windows domain name
* local_only if true, don't try AD lookups
*
* Returns: Error code
*
* *canonname Canonical name (if non-NULL) [1]
* *canondomain Canonical domain (if non-NULL) [1]
* *sidprefix SID prefix [1]
* *rid RID
* *req Request (direction is updated)
*
* [1] malloc'ed, NULL on error
*/
idmap_retcode
lookup_name2sid(
sqlite *cache,
const char *name,
const char *domain,
int want_wuser,
char **canonname,
char **canondomain,
char **sidprefix,
idmap_rid_t *rid,
idmap_id_type *type,
idmap_mapping *req,
int local_only)
{
idmap_retcode retcode;
*sidprefix = NULL;
if (canonname != NULL)
*canonname = NULL;
if (canondomain != NULL)
*canondomain = NULL;
/* Lookup well-known SIDs table */
retcode = lookup_wksids_name2sid(name, domain, canonname, canondomain,
sidprefix, rid, type);
if (retcode == IDMAP_SUCCESS) {
req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
return (retcode);
}
/* Lookup cache */
retcode = lookup_cache_name2sid(cache, name, domain, canonname,
sidprefix, rid, type);
if (retcode == IDMAP_SUCCESS) {
req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
return (retcode);
}
/*
* The caller may be using this function to determine if this
* request needs to be marked for AD lookup or not
* (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
* function to AD lookup now.
*/
if (local_only)
return (retcode);
if (_idmapdstate.cfg->pgcfg.use_lsa &&
_idmapdstate.cfg->pgcfg.domain_name != NULL &&
name != NULL && *sidprefix == NULL) {
retcode = lookup_lsa_by_name(name, domain,
sidprefix, rid,
canonname, canondomain,
type);
if (retcode == IDMAP_SUCCESS)
goto out;
else if (retcode != IDMAP_ERR_NOTFOUND)
return (retcode);
}
/* Lookup AD */
retcode = ad_lookup_by_winname(NULL, name, domain, IDMAP_POSIXID,
NULL, NULL, NULL, canonname, sidprefix, rid, type, NULL);
if (retcode != IDMAP_SUCCESS)
return (retcode);
out:
/*
* Entry found (cache or Windows lookup)
*/
if (want_wuser == 1 && *type != IDMAP_USID)
retcode = IDMAP_ERR_NOTUSER;
else if (want_wuser == 0 && *type != IDMAP_GSID)
retcode = IDMAP_ERR_NOTGROUP;
else if (want_wuser == -1) {
/*
* Caller wants to know if its user or group
* Verify that it's one or the other.
*/
if (*type != IDMAP_USID && *type != IDMAP_GSID)
retcode = IDMAP_ERR_SID;
}
if (retcode == IDMAP_SUCCESS) {
/*
* If we were asked for a canonical domain and none
* of the searches have provided one, assume it's the
* supplied domain.
*/
if (canondomain != NULL && *canondomain == NULL) {
*canondomain = strdup(domain);
if (*canondomain == NULL)
retcode = IDMAP_ERR_MEMORY;
}
}
if (retcode != IDMAP_SUCCESS) {
free(*sidprefix);
*sidprefix = NULL;
if (canonname != NULL) {
free(*canonname);
*canonname = NULL;
}
if (canondomain != NULL) {
free(*canondomain);
*canondomain = NULL;
}
}
return (retcode);
}
static
idmap_retcode
name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
int is_user, idmap_mapping *req, idmap_id_res *res)
{
const char *winname, *windomain;
char *canonname;
char *canondomain;
char *sql = NULL, *errmsg = NULL;
idmap_retcode retcode;
char *end;
const char **values;
sqlite_vm *vm = NULL;
int ncol, r;
int want_wuser;
const char *me = "name_based_mapping_pid2sid";
idmap_namerule *rule = &res->info.how.idmap_how_u.rule;
int direction;
assert(unixname != NULL); /* We have unixname */
assert(req->id2name == NULL); /* We don't have winname */
assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
sql = sqlite_mprintf(
"SELECT winname_display, windomain, w2u_order, "
"is_wuser, unixname, is_nt4 "
"FROM namerules WHERE "
"u2w_order > 0 AND is_user = %d AND "
"(unixname = %Q OR unixname = '*') "
"ORDER BY u2w_order ASC;", is_user, unixname);
if (sql == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
retcode = IDMAP_ERR_MEMORY;
goto out;
}
if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
retcode = IDMAP_ERR_INTERNAL;
idmapdlog(LOG_ERR, "%s: database error (%s)", me,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
goto out;
}
for (;;) {
r = sqlite_step(vm, &ncol, &values, NULL);
assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
if (r == SQLITE_ROW) {
if (ncol < 6) {
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
TRACE(req, res, "Matching rule: %s -> %s@%s",
values[4] == NULL ? "(null)" : values[4],
values[0] == NULL ? "(null)" : values[0],
values[1] == NULL ? "(null)" : values[1]);
if (values[0] == NULL) {
/* values [1] and [2] can be null */
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
if (values[2] != NULL)
direction =
(strtol(values[2], &end, 10) == 0)?
IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
else
direction = IDMAP_DIRECTION_U2W;
if (EMPTY_NAME(values[0])) {
idmap_namerule_set(rule, values[1], values[0],
values[4], is_user,
strtol(values[3], &end, 10),
strtol(values[5], &end, 10),
direction);
TRACE(req, res, "Mapping inhibited");
retcode = IDMAP_ERR_NOMAPPING;
goto out;
}
if (values[0][0] == '*') {
winname = unixname;
} else {
winname = values[0];
}
want_wuser = res->id.idtype == IDMAP_USID ? 1
: res->id.idtype == IDMAP_GSID ? 0
: -1;
if (values[1] != NULL)
windomain = values[1];
else if (state->defdom != NULL) {
windomain = state->defdom;
TRACE(req, res,
"Added default domain %s to rule",
windomain);
} else {
idmapdlog(LOG_ERR, "%s: no domain", me);
TRACE(req, res,
"No domain in rule, and no default domain");
retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
goto out;
}
retcode = lookup_name2sid(state->cache,
winname, windomain,
want_wuser, &canonname, &canondomain,
&res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
&res->id.idtype, req, 0);
if (retcode == IDMAP_SUCCESS) {
break;
} else if (retcode == IDMAP_ERR_NOTFOUND) {
if (values[0][0] == '*') {
TRACE(req, res,
"%s@%s not found, continuing",
winname, windomain);
continue;
} else {
TRACE(req, res,
"%s@%s not found",
winname, windomain);
retcode = IDMAP_ERR_NOMAPPING;
}
} else {
TRACE(req, res,
"Looking up %s@%s error=%d",
winname, windomain, retcode);
}
idmap_namerule_set(rule, values[1],
values[0], values[4], is_user,
strtol(values[3], &end, 10),
strtol(values[5], &end, 10),
direction);
goto out;
} else if (r == SQLITE_DONE) {
TRACE(req, res, "No matching rule");
retcode = IDMAP_ERR_NOTFOUND;
goto out;
} else {
(void) sqlite_finalize(vm, &errmsg);
vm = NULL;
idmapdlog(LOG_ERR, "%s: database error (%s)", me,
CHECK_NULL(errmsg));
sqlite_freemem(errmsg);
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
}
if (values[2] != NULL)
res->direction =
(strtol(values[2], &end, 10) == 0)?
IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
else
res->direction = IDMAP_DIRECTION_U2W;
req->id2name = canonname;
req->id2domain = canondomain;
idmap_namerule_set(rule, values[1], values[0], values[4],
is_user, strtol(values[3], &end, 10),
strtol(values[5], &end, 10),
rule->direction);
TRACE(req, res, "Windows name found");
out:
if (sql != NULL)
sqlite_freemem(sql);
if (retcode != IDMAP_ERR_NOTFOUND) {
res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
res->info.src = IDMAP_MAP_SRC_NEW;
}
if (vm != NULL)
(void) sqlite_finalize(vm, NULL);
return (retcode);
}
/*
* Convention when processing unix2win requests:
*
* Unix identity:
* req->id1name =
* unixname if given otherwise unixname found will be placed
* here.
* req->id1domain =
* NOT USED
* req->id1.idtype =
* Given type (IDMAP_UID or IDMAP_GID)
* req->id1..[uid or gid] =
* UID/GID if given otherwise UID/GID found will be placed here.
*
* Windows identity:
* req->id2name =
* winname found will be placed here.
* req->id2domain =
* windomain found will be placed here.
* res->id.idtype =
* Target type initialized from req->id2.idtype. If
* it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
* will be placed here.
* req->id..sid.[prefix, rid] =
* SID found will be placed here.
*
* Others:
* res->retcode =
* Return status for this request will be placed here.
* res->direction =
* Direction found will be placed here. Direction
* meaning whether the resultant mapping is valid
* only from unix2win or bi-directional.
* req->direction =
* INTERNAL USE. Used by idmapd to set various
* flags (_IDMAP_F_xxxx) to aid in processing
* of the request.
* req->id2.idtype =
* INTERNAL USE. Initially this is the requested target
* type and is used to initialize res->id.idtype.
* ad_lookup_batch() uses this field temporarily to store
* sid_type obtained by the batched AD lookups and after
* use resets it to IDMAP_NONE to prevent xdr from
* mis-interpreting the contents of req->id2.
* req->id2..[uid or gid or sid] =
* NOT USED
*/
/*
* This function does the following:
* 1. Lookup well-known SIDs table.
* 2. Lookup cache.
* 3. Check if the client does not want new mapping to be allocated
* in which case this pass is the final pass.
* 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
* to do AD/NLDAP lookup.
*/
idmap_retcode
pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
idmap_id_res *res, int is_user)
{
idmap_retcode retcode;
idmap_retcode retcode2;
bool_t gen_localsid_on_err = FALSE;
/* Initialize result */
res->id.idtype = req->id2.idtype;
res->direction = IDMAP_DIRECTION_UNDEF;
if (req->id2.idmap_id_u.sid.prefix != NULL) {
/* sanitize sidprefix */
free(req->id2.idmap_id_u.sid.prefix);
req->id2.idmap_id_u.sid.prefix = NULL;
}
/* Find pid */
if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
if (req->id1name == NULL) {
retcode = IDMAP_ERR_ARG;
goto out;
}
retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
if (retcode != IDMAP_SUCCESS) {
TRACE(req, res, "Getting UNIX ID error=%d", retcode);
retcode = IDMAP_ERR_NOMAPPING;
goto out;
}
TRACE(req, res, "Found UNIX ID");
}
/* Lookup in well-known SIDs table */
retcode = lookup_wksids_pid2sid(req, res, is_user);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Hardwired mapping");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res,
"Well-known account lookup error=%d", retcode);
goto out;
}
/* Lookup in cache */
retcode = lookup_cache_pid2sid(state->cache, req, res, is_user);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Found in mapping cache");
goto out;
} else if (retcode != IDMAP_ERR_NOTFOUND) {
TRACE(req, res,
"Mapping cache lookup error=%d", retcode);
goto out;
}
TRACE(req, res, "Not found in mapping cache");
/* Ephemeral ids cannot be allocated during pid2sid */
if (IDMAP_ID_IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
retcode = IDMAP_ERR_NOMAPPING;
TRACE(req, res, "Shouldn't have an ephemeral ID here");
goto out;
}
if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
retcode = IDMAP_ERR_NONE_GENERATED;
goto out;
}
if (AVOID_NAMESERVICE(req)) {
gen_localsid_on_err = TRUE;
retcode = IDMAP_ERR_NOMAPPING;
goto out;
}
/* Set flags for the next stage */
if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
req->direction |= _IDMAP_F_LOOKUP_AD;
state->ad_nqueries++;
} else if (AD_MODE(req->id1.idtype, state)) {
/*
* If AD-based name mapping is enabled then the next stage
* will need to lookup AD using unixname to get the
* corresponding winname.
*/
if (req->id1name == NULL) {
/* Get unixname if only pid is given. */
retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
is_user, &req->id1name);
if (retcode != IDMAP_SUCCESS) {
TRACE(req, res,
"Getting UNIX name error=%d", retcode);
gen_localsid_on_err = TRUE;
goto out;
}
TRACE(req, res, "Found UNIX name");
}
req->direction |= _IDMAP_F_LOOKUP_AD;
state->ad_nqueries++;
} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
/*
* If native LDAP or mixed mode is enabled for name mapping
* then the next stage will need to lookup native LDAP using
* unixname/pid to get the corresponding winname.
*/
req->direction |= _IDMAP_F_LOOKUP_NLDAP;
state->nldap_nqueries++;
}
/*
* Failed to find non-expired entry in cache. Set the flag to
* indicate that we are not done yet.
*/
state->pid2sid_done = FALSE;
req->direction |= _IDMAP_F_NOTDONE;
retcode = IDMAP_SUCCESS;
out:
res->retcode = idmap_stat4prot(retcode);
if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS) {
if (gen_localsid_on_err == TRUE) {
retcode2 = generate_localsid(req, res, is_user, TRUE);
if (retcode2 == IDMAP_SUCCESS)
TRACE(req, res, "Generate local SID");
else
TRACE(req, res,
"Generate local SID error=%d", retcode2);
}
}
return (retcode);
}
idmap_retcode
pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
idmap_id_res *res, int is_user)
{
bool_t gen_localsid_on_err = TRUE;
idmap_retcode retcode = IDMAP_SUCCESS;
idmap_retcode retcode2;
/* Check if second pass is needed */
if (ARE_WE_DONE(req->direction))
return (res->retcode);
/* Get status from previous pass */
retcode = res->retcode;
if (retcode != IDMAP_SUCCESS)
goto out;
/*
* If directory-based name mapping is enabled then the winname
* may already have been retrieved from the AD object (AD-mode)
* or from native LDAP object (nldap-mode or mixed-mode).
* Note that if we have winname but no SID then it's an error
* because this implies that the Native LDAP entry contains
* winname which does not exist and it's better that we return
* an error instead of doing rule-based mapping so that the user
* can detect the issue and take appropriate action.
*/
if (req->id2name != NULL) {
/* Return notfound if we've winname but no SID. */
if (res->id.idmap_id_u.sid.prefix == NULL) {
TRACE(req, res, "Windows name but no SID");
retcode = IDMAP_ERR_NOTFOUND;
goto out;
}
if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)
res->direction = IDMAP_DIRECTION_BI;
else if (AD_MODE(req->id1.idtype, state))
res->direction = IDMAP_DIRECTION_BI;
else if (NLDAP_MODE(req->id1.idtype, state))
res->direction = IDMAP_DIRECTION_BI;
else if (MIXED_MODE(req->id1.idtype, state))
res->direction = IDMAP_DIRECTION_W2U;
goto out;
} else if (res->id.idmap_id_u.sid.prefix != NULL) {
/*
* We've SID but no winname. This is fine because
* the caller may have only requested SID.
*/
goto out;
}
/* Free any mapping info from Directory based mapping */
if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
idmap_how_clear(&res->info.how);
if (req->id1name == NULL) {
/* Get unixname from name service */
retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
&req->id1name);
if (retcode != IDMAP_SUCCESS) {
TRACE(req, res,
"Getting UNIX name error=%d", retcode);
goto out;
}
TRACE(req, res, "Found UNIX name");
} else if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
/* Get pid from name service */
retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
if (retcode != IDMAP_SUCCESS) {
TRACE(req, res,
"Getting UNIX ID error=%d", retcode);
gen_localsid_on_err = FALSE;
goto out;
}
TRACE(req, res, "Found UNIX ID");
}
/* Use unixname to evaluate local name-based mapping rules */
retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
req, res);
if (retcode == IDMAP_ERR_NOTFOUND) {
retcode = generate_localsid(req, res, is_user, FALSE);
if (retcode == IDMAP_SUCCESS) {
TRACE(req, res, "Generated local SID");
} else {
TRACE(req, res,
"Generating local SID error=%d", retcode);
}
gen_localsid_on_err = FALSE;
}
out:
res->retcode = idmap_stat4prot(retcode);
if (res->retcode != IDMAP_SUCCESS) {
req->direction = _IDMAP_F_DONE;
free(req->id2name);
req->id2name = NULL;
free(req->id2domain);
req->id2domain = NULL;
if (gen_localsid_on_err == TRUE) {
retcode2 = generate_localsid(req, res, is_user, TRUE);
if (retcode2 == IDMAP_SUCCESS)
TRACE(req, res, "Generate local SID");
else
TRACE(req, res,
"Generate local SID error=%d", retcode2);
} else {
res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
}
}
if (!ARE_WE_DONE(req->direction))
state->pid2sid_done = FALSE;
return (retcode);
}
idmap_retcode
idmap_cache_flush(idmap_flush_op op)
{
idmap_retcode rc;
sqlite *cache = NULL;
char *sql1;
char *sql2;
switch (op) {
case IDMAP_FLUSH_EXPIRE:
sql1 =
"UPDATE idmap_cache SET expiration=1 WHERE expiration>0;";
sql2 =
"UPDATE name_cache SET expiration=1 WHERE expiration>0;";
break;
case IDMAP_FLUSH_DELETE:
sql1 = "DELETE FROM idmap_cache;";
sql2 = "DELETE FROM name_cache;";
break;
default:
return (IDMAP_ERR_INTERNAL);
}
rc = get_cache_handle(&cache);
if (rc != IDMAP_SUCCESS)
return (rc);
/*
* Note that we flush the idmapd cache first, before the kernel
* cache. If we did it the other way 'round, a request could come
* in after the kernel cache flush and pull a soon-to-be-flushed
* idmapd cache entry back into the kernel cache. This way the
* worst that will happen is that a new entry will be added to
* the kernel cache and then immediately flushed.
*/
rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql1);
if (rc == IDMAP_SUCCESS)
rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql2);
if (rc == IDMAP_SUCCESS)
(void) __idmap_flush_kcache();
if (rc == IDMAP_ERR_DB)
kill_cache_handle(cache);
return (rc);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2014 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Retrieve directory information for Active Directory users.
*/
#include <ldap.h>
#include <lber.h>
#include <pwd.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <libadutils.h>
#include <libuutil.h>
#include <note.h>
#include <assert.h>
#include "directory.h"
#include "directory_private.h"
#include "idmapd.h"
#include <rpcsvc/idmap_prot.h>
#include "directory_server_impl.h"
/*
* Information required by the function that handles the callback from LDAP
* when responses are received.
*/
struct cbinfo {
const char * const *attrs;
int nattrs;
directory_entry_rpc *entry;
const char *domain;
};
static void directory_provider_ad_cb(LDAP *ld, LDAPMessage **ldapres, int rc,
int qid, void *argp);
static void directory_provider_ad_cb1(LDAP *ld, LDAPMessage *msg,
struct cbinfo *cbinfo);
static directory_error_t bv_list_dav(directory_values_rpc *lvals,
struct berval **bv);
static directory_error_t directory_provider_ad_lookup(
directory_entry_rpc *pent, const char * const * attrs, int nattrs,
const char *domain, const char *filter);
static directory_error_t get_domain(LDAP *ld, LDAPMessage *ldapres,
char **domain);
static directory_error_t directory_provider_ad_utils_error(char *func, int rc);
#if defined(DUMP_VALUES)
static void dump_bv_list(const char *attr, struct berval **bv);
#endif
#define MAX_EXTRA_ATTRS 1 /* sAMAccountName */
/*
* Add an entry to a NULL-terminated list, if it's not already there.
* Assumes that the list has been allocated large enough for all additions,
* and prefilled with NULL.
*/
static
void
maybe_add_to_list(const char **list, const char *s)
{
for (; *list != NULL; list++) {
if (uu_strcaseeq(*list, s))
return;
}
*list = s;
}
/*
* Copy a counted attribute list to a NULL-terminated one.
* In the process, examine the requested attributes and augment
* the list as required to support any synthesized attributes
* requested.
*/
static
const char **
copy_and_augment_attr_list(char **req_list, int req_list_len)
{
const char **new_list;
int i;
new_list =
calloc(req_list_len + MAX_EXTRA_ATTRS + 1, sizeof (*new_list));
if (new_list == NULL)
return (NULL);
(void) memcpy(new_list, req_list, req_list_len * sizeof (char *));
for (i = 0; i < req_list_len; i++) {
const char *a = req_list[i];
/*
* Note that you must update MAX_EXTRA_ATTRS above if you
* add to this list.
*/
if (uu_strcaseeq(a, "x-sun-canonicalName")) {
maybe_add_to_list(new_list, "sAMAccountName");
continue;
}
/* None needed for x-sun-provider */
}
return (new_list);
}
/*
* Retrieve information by name.
* Called indirectly through the Directory_provider_static structure.
*/
static
directory_error_t
directory_provider_ad_get(
directory_entry_rpc *del,
idmap_utf8str_list *ids,
char *types,
idmap_utf8str_list *attrs)
{
int i;
const char **attrs2;
directory_error_t de = NULL;
/*
* If we don't have any AD servers handy, we can't find anything.
* XXX: this should be using our DC, not the GC.
*/
if (_idmapdstate.num_gcs < 1) {
return (NULL);
}
RDLOCK_CONFIG()
/* 6835280 spurious lint error if the strlen is in the declaration */
int len = strlen(_idmapdstate.cfg->pgcfg.default_domain);
char default_domain[len + 1];
(void) strcpy(default_domain, _idmapdstate.cfg->pgcfg.default_domain);
UNLOCK_CONFIG();
/*
* Turn our counted-array argument into a NULL-terminated array.
* At the same time, add in any attributes that we need to support
* any requested synthesized attributes.
*/
attrs2 = copy_and_augment_attr_list(attrs->idmap_utf8str_list_val,
attrs->idmap_utf8str_list_len);
if (attrs2 == NULL)
goto nomem;
for (i = 0; i < ids->idmap_utf8str_list_len; i++) {
char *vw[3];
int type;
/*
* Extract the type for this particular ID.
* Advance to the next type, if it's there, else keep
* using this type until we run out of IDs.
*/
type = *types;
if (*(types+1) != '\0')
types++;
/*
* If this entry has already been handled, one way or another,
* skip it.
*/
if (del[i].status != DIRECTORY_NOT_FOUND)
continue;
char *id = ids->idmap_utf8str_list_val[i];
/*
* Allow for expanding every character to \xx, plus some
* space for the query syntax.
*/
int id_len = strlen(id);
char filter[1000 + id_len*3];
if (type == DIRECTORY_ID_SID[0]) {
/*
* Mildly surprisingly, AD appears to allow searching
* based on text SIDs. Must be a special case on the
* server end.
*/
ldap_build_filter(filter, sizeof (filter),
"(objectSid=%v)", NULL, NULL, NULL, id, NULL);
de = directory_provider_ad_lookup(&del[i], attrs2,
attrs->idmap_utf8str_list_len, NULL, filter);
if (de != NULL) {
directory_entry_set_error(&del[i], de);
de = NULL;
}
} else {
int id_len = strlen(id);
char name[id_len + 1];
char domain[id_len + 1];
split_name(name, domain, id);
vw[0] = name;
if (uu_streq(domain, "")) {
vw[1] = default_domain;
} else {
vw[1] = domain;
}
if (type == DIRECTORY_ID_USER[0])
vw[2] = "user";
else if (type == DIRECTORY_ID_GROUP[0])
vw[2] = "group";
else
vw[2] = "*";
/*
* Try samAccountName.
* Note that here we rely on checking the returned
* distinguishedName to make sure that we found an
* entry from the right domain, because there's no
* attribute we can straightforwardly filter for to
* match domain.
*
* Eventually we should perhaps also try
* userPrincipalName.
*/
ldap_build_filter(filter, sizeof (filter),
"(&(samAccountName=%v1)(objectClass=%v3))",
NULL, NULL, NULL, NULL, vw);
de = directory_provider_ad_lookup(&del[i], attrs2,
attrs->idmap_utf8str_list_len, vw[1], filter);
if (de != NULL) {
directory_entry_set_error(&del[i], de);
de = NULL;
}
}
}
de = NULL;
goto out;
nomem:
de = directory_error("ENOMEM.AD",
"Out of memory during AD lookup", NULL);
out:
free(attrs2);
return (de);
}
/*
* Note that attrs is NULL terminated, and that nattrs is the number
* of attributes requested by the user... which might be fewer than are
* in attrs because of attributes that we need for our own processing.
*/
static
directory_error_t
directory_provider_ad_lookup(
directory_entry_rpc *pent,
const char * const * attrs,
int nattrs,
const char *domain,
const char *filter)
{
adutils_ad_t *ad;
adutils_rc batchrc;
struct cbinfo cbinfo;
adutils_query_state_t *qs;
int rc;
/*
* NEEDSWORK: Should eventually handle other forests.
* NEEDSWORK: Should eventually handle non-GC attributes.
*/
ad = _idmapdstate.gcs[0];
/* Stash away information for the callback function. */
cbinfo.attrs = attrs;
cbinfo.nattrs = nattrs;
cbinfo.entry = pent;
cbinfo.domain = domain;
rc = adutils_lookup_batch_start(ad, 1, directory_provider_ad_cb,
&cbinfo, &qs);
if (rc != ADUTILS_SUCCESS) {
return (directory_provider_ad_utils_error(
"adutils_lookup_batch_start", rc));
}
rc = adutils_lookup_batch_add(qs, filter, attrs, domain,
NULL, &batchrc);
if (rc != ADUTILS_SUCCESS) {
adutils_lookup_batch_release(&qs);
return (directory_provider_ad_utils_error(
"adutils_lookup_batch_add", rc));
}
rc = adutils_lookup_batch_end(&qs);
if (rc != ADUTILS_SUCCESS) {
return (directory_provider_ad_utils_error(
"adutils_lookup_batch_end", rc));
}
if (batchrc != ADUTILS_SUCCESS) {
/*
* NEEDSWORK: We're consistently getting -9997 here.
* What does it mean?
*/
return (NULL);
}
return (NULL);
}
/*
* Callback from the LDAP functions when they get responses.
* We don't really need (nor want) asynchronous handling, but it's
* what libadutils gives us.
*/
static
void
directory_provider_ad_cb(
LDAP *ld,
LDAPMessage **ldapres,
int rc,
int qid,
void *argp)
{
NOTE(ARGUNUSED(rc, qid))
struct cbinfo *cbinfo = (struct cbinfo *)argp;
LDAPMessage *msg = *ldapres;
for (msg = ldap_first_entry(ld, msg);
msg != NULL;
msg = ldap_next_entry(ld, msg)) {
directory_provider_ad_cb1(ld, msg, cbinfo);
}
}
/*
* Process a single entry returned by an LDAP callback.
* Note that this performs a function roughly equivalent to the
* directory*Populate() functions in the other providers.
* Given an LDAP response, populate the directory entry for return to
* the caller. This one differs primarily in that we're working directly
* with LDAP, so we don't have to do any attribute translation.
*/
static
void
directory_provider_ad_cb1(
LDAP *ld,
LDAPMessage *msg,
struct cbinfo *cbinfo)
{
int nattrs = cbinfo->nattrs;
const char * const *attrs = cbinfo->attrs;
directory_entry_rpc *pent = cbinfo->entry;
int i;
directory_values_rpc *llvals;
directory_error_t de;
char *domain = NULL;
/*
* We don't have a way to filter for entries from the right domain
* in the LDAP query, so we check for it here. Searches based on
* samAccountName might yield results from the wrong domain.
*/
de = get_domain(ld, msg, &domain);
if (de != NULL)
goto err;
if (cbinfo->domain != NULL && !domain_eq(cbinfo->domain, domain))
goto out;
/*
* If we've already found a match, error.
*/
if (pent->status != DIRECTORY_NOT_FOUND) {
de = directory_error("Duplicate.AD",
"Multiple matching entries found", NULL);
goto err;
}
llvals = calloc(nattrs, sizeof (directory_values_rpc));
if (llvals == NULL)
goto nomem;
pent->directory_entry_rpc_u.attrs.attrs_val = llvals;
pent->directory_entry_rpc_u.attrs.attrs_len = nattrs;
pent->status = DIRECTORY_FOUND;
for (i = 0; i < nattrs; i++) {
struct berval **bv;
const char *a = attrs[i];
directory_values_rpc *val = &llvals[i];
bv = ldap_get_values_len(ld, msg, a);
#if defined(DUMP_VALUES)
dump_bv_list(attrs[i], bv);
#endif
if (bv != NULL) {
de = bv_list_dav(val, bv);
ldap_value_free_len(bv);
if (de != NULL)
goto err;
} else if (uu_strcaseeq(a, "x-sun-canonicalName")) {
bv = ldap_get_values_len(ld, msg, "sAMAccountName");
if (bv != NULL) {
int n = ldap_count_values_len(bv);
if (n > 0) {
char *tmp;
(void) asprintf(&tmp, "%.*s@%s",
bv[0]->bv_len, bv[0]->bv_val,
domain);
if (tmp == NULL)
goto nomem;
const char *ctmp = tmp;
de = str_list_dav(val, &ctmp, 1);
free(tmp);
if (de != NULL)
goto err;
}
}
} else if (uu_strcaseeq(a, "x-sun-provider")) {
const char *provider = "LDAP-AD";
de = str_list_dav(val, &provider, 1);
}
}
goto out;
nomem:
de = directory_error("ENOMEM.users",
"No memory allocating return value for user lookup", NULL);
err:
directory_entry_set_error(pent, de);
de = NULL;
out:
free(domain);
}
/*
* Given a struct berval, populate a directory attribute value (which is a
* list of values).
* Note that here we populate the DAV with the exact bytes that LDAP returns.
* Back over in the client it appends a \0 so that strings are null
* terminated.
*/
static
directory_error_t
bv_list_dav(directory_values_rpc *lvals, struct berval **bv)
{
directory_value_rpc *dav;
int n;
int i;
n = ldap_count_values_len(bv);
dav = calloc(n, sizeof (directory_value_rpc));
if (dav == NULL)
goto nomem;
lvals->directory_values_rpc_u.values.values_val = dav;
lvals->directory_values_rpc_u.values.values_len = n;
lvals->found = TRUE;
for (i = 0; i < n; i++) {
dav[i].directory_value_rpc_val =
uu_memdup(bv[i]->bv_val, bv[i]->bv_len);
if (dav[i].directory_value_rpc_val == NULL)
goto nomem;
dav[i].directory_value_rpc_len = bv[i]->bv_len;
}
return (NULL);
nomem:
return (directory_error("ENOMEM.bv_list_dav",
"Insufficient memory copying values"));
}
#if defined(DUMP_VALUES)
static
void
dump_bv_list(const char *attr, struct berval **bv)
{
int i;
if (bv == NULL) {
(void) fprintf(stderr, "%s: (empty)\n", attr);
return;
}
for (i = 0; bv[i] != NULL; i++) {
(void) fprintf(stderr, "%s[%d] =\n", attr, i);
dump(stderr, " ", bv[i]->bv_val, bv[i]->bv_len);
}
}
#endif /* DUMP_VALUES */
/*
* Return the domain associated with the specified entry.
*/
static
directory_error_t
get_domain(
LDAP *ld,
LDAPMessage *msg,
char **domain)
{
*domain = NULL;
char *dn = ldap_get_dn(ld, msg);
if (dn == NULL) {
char buf[100]; /* big enough for any int */
char *m;
char *s;
int err = ldap_get_lderrno(ld, &m, &s);
(void) snprintf(buf, sizeof (buf), "%d", err);
return directory_error("AD.get_domain.ldap_get_dn",
"ldap_get_dn: %1 (%2)\n"
"matched: %3\n"
"error: %4",
ldap_err2string(err), buf,
m == NULL ? "(null)" : m,
s == NULL ? "(null)" : s,
NULL);
}
*domain = adutils_dn2dns(dn);
if (*domain == NULL) {
directory_error_t de;
de = directory_error("Unknown.get_domain.adutils_dn2dns",
"get_domain: Unexpected error from adutils_dn2dns(%1)",
dn, NULL);
free(dn);
return (de);
}
free(dn);
return (NULL);
}
/*
* Given an error report from libadutils, generate a directory_error_t.
*/
static
directory_error_t
directory_provider_ad_utils_error(char *func, int rc)
{
char rcstr[100]; /* plenty for any int */
char code[100]; /* plenty for any int */
(void) snprintf(rcstr, sizeof (rcstr), "%d", rc);
(void) snprintf(code, sizeof (code), "ADUTILS.%d", rc);
return (directory_error(code,
"Error %2 from adutils function %1", func, rcstr, NULL));
}
struct directory_provider_static directory_provider_ad = {
"AD",
directory_provider_ad_get,
};
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Retrieve directory information for built-in users and groups
*/
#include <stdio.h>
#include <limits.h>
#include <sys/idmap.h>
#include <sys/param.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <libuutil.h>
#include <note.h>
#include "idmapd.h"
#include "directory.h"
#include "directory_private.h"
#include <rpcsvc/idmap_prot.h>
#include "directory_server_impl.h"
#include "sidutil.h"
static directory_error_t sid_dav(directory_values_rpc *lvals,
const wksids_table_t *wksid);
static directory_error_t directory_provider_builtin_populate(
directory_entry_rpc *pent, const wksids_table_t *wksid,
idmap_utf8str_list *attrs);
/*
* Retrieve information by name.
* Called indirectly through the directory_provider_static structure.
*/
static
directory_error_t
directory_provider_builtin_get(
directory_entry_rpc *del,
idmap_utf8str_list *ids,
idmap_utf8str types,
idmap_utf8str_list *attrs)
{
int i;
for (i = 0; i < ids->idmap_utf8str_list_len; i++) {
const wksids_table_t *wksid;
directory_error_t de;
int type;
/*
* Extract the type for this particular ID.
* Advance to the next type, if it's there, else keep
* using this type until we run out of IDs.
*/
type = *types;
if (*(types+1) != '\0')
types++;
/*
* If this entry has already been handled, one way or another,
* skip it.
*/
if (del[i].status != DIRECTORY_NOT_FOUND)
continue;
char *id = ids->idmap_utf8str_list_val[i];
/*
* End-to-end error injection point.
* NEEDSWORK: should probably eliminate this for production
*/
if (uu_streq(id, " DEBUG BUILTIN ERROR ")) {
directory_entry_set_error(&del[i],
directory_error("Directory_provider_builtin.debug",
"Directory_provider_builtin: artificial error",
NULL));
continue;
}
if (type == DIRECTORY_ID_SID[0])
wksid = find_wk_by_sid(id);
else {
int idmap_id_type;
if (type == DIRECTORY_ID_NAME[0])
idmap_id_type = IDMAP_POSIXID;
else if (type == DIRECTORY_ID_USER[0])
idmap_id_type = IDMAP_UID;
else if (type == DIRECTORY_ID_GROUP[0])
idmap_id_type = IDMAP_GID;
else {
directory_entry_set_error(&del[i],
directory_error("invalid_arg.id_type",
"Invalid ID type \"%1\"",
types, NULL));
continue;
}
int id_len = strlen(id);
char name[id_len + 1];
char domain[id_len + 1];
split_name(name, domain, id);
wksid = find_wksid_by_name(name, domain, idmap_id_type);
}
if (wksid == NULL)
continue;
de = directory_provider_builtin_populate(&del[i], wksid, attrs);
if (de != NULL) {
directory_entry_set_error(&del[i], de);
de = NULL;
}
}
return (NULL);
}
/*
* Given a well-known name entry and a list of attributes that were
* requested, populate the structure to return to the caller.
*/
static
directory_error_t
directory_provider_builtin_populate(
directory_entry_rpc *pent,
const wksids_table_t *wksid,
idmap_utf8str_list *attrs)
{
int j;
directory_values_rpc *llvals;
int nattrs;
nattrs = attrs->idmap_utf8str_list_len;
llvals = calloc(nattrs, sizeof (directory_values_rpc));
if (llvals == NULL)
goto nomem;
pent->status = DIRECTORY_FOUND;
pent->directory_entry_rpc_u.attrs.attrs_val = llvals;
pent->directory_entry_rpc_u.attrs.attrs_len = nattrs;
for (j = 0; j < nattrs; j++) {
directory_values_rpc *val;
char *a;
directory_error_t de;
/*
* We're going to refer to these a lot, so make a shorthand
* copy.
*/
a = attrs->idmap_utf8str_list_val[j];
val = &llvals[j];
/*
* Start by assuming no errors and that we don't have
* the information.
*/
val->found = FALSE;
de = NULL;
if (uu_strcaseeq(a, "uid")) {
de = str_list_dav(val, &wksid->winname, 1);
} else if (uu_strcaseeq(a, "uidNumber")) {
if (wksid->pid != IDMAP_SENTINEL_PID &&
wksid->is_user) {
de = uint_list_dav(val, &wksid->pid, 1);
}
} else if (uu_strcaseeq(a, "gidNumber")) {
if (wksid->pid != IDMAP_SENTINEL_PID &&
!wksid->is_user) {
de = uint_list_dav(val, &wksid->pid, 1);
}
} else if (uu_strcaseeq(a, "displayName") ||
uu_strcaseeq(a, "cn")) {
de = str_list_dav(val, &wksid->winname, 1);
} else if (uu_strcaseeq(a, "distinguishedName")) {
char *container;
if (wksid->domain == NULL) {
container = "Users";
} else {
container = "Builtin";
}
RDLOCK_CONFIG();
char *dn;
(void) asprintf(&dn,
"CN=%s,CN=%s,DC=%s",
wksid->winname, container, _idmapdstate.hostname);
UNLOCK_CONFIG();
const char *cdn = dn;
de = str_list_dav(val, &cdn, 1);
free(dn);
} else if (uu_strcaseeq(a, "objectClass")) {
if (wksid->is_wuser) {
static const char *objectClasses[] = {
"top",
"person",
"organizationalPerson",
"user",
};
de = str_list_dav(val, objectClasses,
UU_NELEM(objectClasses));
} else {
static const char *objectClasses[] = {
"top",
"group",
};
de = str_list_dav(val, objectClasses,
UU_NELEM(objectClasses));
}
} else if (uu_strcaseeq(a, "objectSid")) {
de = sid_dav(val, wksid);
} else if (uu_strcaseeq(a, "x-sun-canonicalName")) {
char *canon;
if (wksid->domain == NULL) {
RDLOCK_CONFIG();
(void) asprintf(&canon, "%s@%s",
wksid->winname, _idmapdstate.hostname);
UNLOCK_CONFIG();
} else if (uu_streq(wksid->domain, "")) {
canon = strdup(wksid->winname);
} else {
(void) asprintf(&canon, "%s@%s",
wksid->winname, wksid->domain);
}
if (canon == NULL)
goto nomem;
const char *ccanon = canon;
de = str_list_dav(val, &ccanon, 1);
free(canon);
} else if (uu_strcaseeq(a, "x-sun-provider")) {
const char *provider = "Builtin";
de = str_list_dav(val, &provider, 1);
}
if (de != NULL)
return (de);
}
return (NULL);
nomem:
return (directory_error("ENOMEM.users",
"No memory allocating return value for user lookup", NULL));
}
/*
* Given a well-known name structure, generate a binary-format SID.
* It's a bit perverse that we must take a text-format SID and turn it into
* a binary-format SID, only to have the caller probably turn it back into
* text format, but SIDs are carried across LDAP in binary format.
*/
static
directory_error_t
sid_dav(directory_values_rpc *lvals, const wksids_table_t *wksid)
{
char *text_sid;
sid_t *sid;
directory_error_t de;
if (wksid->sidprefix == NULL) {
RDLOCK_CONFIG();
(void) asprintf(&text_sid, "%s-%d",
_idmapdstate.cfg->pgcfg.machine_sid,
wksid->rid);
UNLOCK_CONFIG();
} else {
(void) asprintf(&text_sid, "%s-%d",
wksid->sidprefix, wksid->rid);
}
if (text_sid == NULL)
goto nomem;
sid = sid_fromstr(text_sid);
free(text_sid);
if (sid == NULL)
goto nomem;
sid_to_le(sid);
de = bin_list_dav(lvals, sid, 1, sid_len(sid));
sid_free(sid);
return (de);
nomem:
return (directory_error("ENOMEM.sid_dav",
"No memory allocating SID for user lookup", NULL));
}
struct directory_provider_static directory_provider_builtin = {
"builtin",
directory_provider_builtin_get,
};
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Retrieve directory information for standard UNIX users/groups.
* (NB: not just from files, but all nsswitch sources.)
*/
#include <pwd.h>
#include <grp.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <libuutil.h>
#include <note.h>
#include <errno.h>
#include "idmapd.h"
#include "directory.h"
#include "directory_private.h"
#include <rpcsvc/idmap_prot.h>
#include "directory_server_impl.h"
#include "sidutil.h"
static directory_error_t machine_sid_dav(directory_values_rpc *lvals,
unsigned int rid);
static directory_error_t directory_provider_nsswitch_populate(
directory_entry_rpc *pent, struct passwd *pwd, struct group *grp,
idmap_utf8str_list *attrs);
/*
* Retrieve information by name.
* Called indirectly through the directory_provider_static structure.
*/
static
directory_error_t
directory_provider_nsswitch_get(
directory_entry_rpc *del,
idmap_utf8str_list *ids,
idmap_utf8str types,
idmap_utf8str_list *attrs)
{
int i;
RDLOCK_CONFIG();
/* 6835280 spurious lint error if the strlen is in the declaration */
int host_name_len = strlen(_idmapdstate.hostname);
char my_host_name[host_name_len + 1];
(void) strcpy(my_host_name, _idmapdstate.hostname);
/* We use len later, so this is not merely a workaround for 6835280 */
int machine_sid_len = strlen(_idmapdstate.cfg->pgcfg.machine_sid);
char my_machine_sid[machine_sid_len + 1];
(void) strcpy(my_machine_sid, _idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
for (i = 0; i < ids->idmap_utf8str_list_len; i++) {
struct passwd *pwd = NULL;
struct group *grp = NULL;
directory_error_t de;
int type;
/*
* Extract the type for this particular ID.
* Advance to the next type, if it's there, else keep
* using this type until we run out of IDs.
*/
type = *types;
if (*(types+1) != '\0')
types++;
/*
* If this entry has already been handled, one way or another,
* skip it.
*/
if (del[i].status != DIRECTORY_NOT_FOUND)
continue;
char *id = ids->idmap_utf8str_list_val[i];
if (type == DIRECTORY_ID_SID[0]) {
/*
* Is it our SID?
* Check whether the first part matches, then a "-",
* then a single RID.
*/
if (strncasecmp(id, my_machine_sid, machine_sid_len) !=
0)
continue;
if (id[machine_sid_len] != '-')
continue;
char *p;
uint32_t rid =
strtoul(id + machine_sid_len + 1, &p, 10);
if (*p != '\0')
continue;
if (rid < LOCALRID_UID_MIN) {
/* Builtin, not handled here */
continue;
}
if (rid <= LOCALRID_UID_MAX) {
/* User */
errno = 0;
pwd = getpwuid(rid - LOCALRID_UID_MIN);
if (pwd == NULL) {
if (errno == 0) /* Not found */
continue;
char buf[40];
int err = errno;
(void) snprintf(buf, sizeof (buf),
"%d", err);
directory_entry_set_error(&del[i],
directory_error("errno.getpwuid",
"getpwuid: %2 (%1)",
buf, strerror(err), NULL));
continue;
}
} else if (rid >= LOCALRID_GID_MIN &&
rid <= LOCALRID_GID_MAX) {
/* Group */
errno = 0;
grp = getgrgid(rid - LOCALRID_GID_MIN);
if (grp == NULL) {
if (errno == 0) /* Not found */
continue;
char buf[40];
int err = errno;
(void) snprintf(buf, sizeof (buf),
"%d", err);
directory_entry_set_error(&del[i],
directory_error("errno.getgrgid",
"getgrgid: %2 (%1)",
buf, strerror(err), NULL));
continue;
}
} else
continue;
} else {
int id_len = strlen(id);
char name[id_len + 1];
char domain[id_len + 1];
split_name(name, domain, id);
if (domain[0] != '\0') {
if (!domain_eq(domain, my_host_name))
continue;
}
/*
* If the caller has requested user or group
* information specifically, we only set one of
* pwd or grp.
* If the caller has requested either type, we try
* both in the hopes of getting one.
* Note that directory_provider_nsswitch_populate
* considers it to be an error if both are set.
*/
if (type != DIRECTORY_ID_GROUP[0]) {
/* prep for not found / error case */
errno = 0;
pwd = getpwnam(name);
if (pwd == NULL && errno != 0) {
char buf[40];
int err = errno;
(void) snprintf(buf, sizeof (buf),
"%d", err);
directory_entry_set_error(&del[i],
directory_error("errno.getpwnam",
"getpwnam: %2 (%1)",
buf, strerror(err), NULL));
continue;
}
}
if (type != DIRECTORY_ID_USER[0]) {
/* prep for not found / error case */
errno = 0;
grp = getgrnam(name);
if (grp == NULL && errno != 0) {
char buf[40];
int err = errno;
(void) snprintf(buf, sizeof (buf),
"%d", err);
directory_entry_set_error(&del[i],
directory_error("errno.getgrnam",
"getgrnam: %2 (%1)",
buf, strerror(err), NULL));
continue;
}
}
}
/*
* Didn't find it, don't populate the structure.
* Another provider might populate it.
*/
if (pwd == NULL && grp == NULL)
continue;
de = directory_provider_nsswitch_populate(&del[i], pwd, grp,
attrs);
if (de != NULL) {
directory_entry_set_error(&del[i], de);
de = NULL;
continue;
}
}
return (NULL);
}
/*
* Given a pwd structure or a grp structure, and a list of attributes that
* were requested, populate the structure to return to the caller.
*/
static
directory_error_t
directory_provider_nsswitch_populate(
directory_entry_rpc *pent,
struct passwd *pwd,
struct group *grp,
idmap_utf8str_list *attrs)
{
int j;
directory_values_rpc *llvals;
int nattrs;
/*
* If it wasn't for this case, everything would be a lot simpler.
* UNIX allows users and groups with the same name. Windows doesn't.
*/
if (pwd != NULL && grp != NULL) {
return directory_error("Ambiguous.Name",
"Ambiguous name, is both a user and a group",
NULL);
}
nattrs = attrs->idmap_utf8str_list_len;
llvals = calloc(nattrs, sizeof (directory_values_rpc));
if (llvals == NULL)
goto nomem;
pent->directory_entry_rpc_u.attrs.attrs_val = llvals;
pent->directory_entry_rpc_u.attrs.attrs_len = nattrs;
pent->status = DIRECTORY_FOUND;
for (j = 0; j < nattrs; j++) {
directory_values_rpc *val;
char *a;
directory_error_t de;
/*
* We're going to refer to these a lot, so make a shorthand
* copy.
*/
a = attrs->idmap_utf8str_list_val[j];
val = &llvals[j];
/*
* Start by assuming no errors and that we don't have
* the information
*/
val->found = FALSE;
de = NULL;
if (pwd != NULL) {
/*
* Handle attributes for user entries.
*/
if (uu_strcaseeq(a, "cn")) {
const char *p = pwd->pw_name;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "objectClass")) {
static const char *objectClasses[] = {
"top",
"posixAccount",
};
de = str_list_dav(val, objectClasses,
UU_NELEM(objectClasses));
} else if (uu_strcaseeq(a, "gidNumber")) {
de = uint_list_dav(val, &pwd->pw_gid, 1);
} else if (uu_strcaseeq(a, "objectSid")) {
de = machine_sid_dav(val,
pwd->pw_uid + LOCALRID_UID_MIN);
} else if (uu_strcaseeq(a, "displayName")) {
const char *p = pwd->pw_gecos;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "distinguishedName")) {
char *dn;
RDLOCK_CONFIG();
(void) asprintf(&dn,
"uid=%s,ou=people,dc=%s",
pwd->pw_name, _idmapdstate.hostname);
UNLOCK_CONFIG();
if (dn == NULL)
goto nomem;
const char *cdn = dn;
de = str_list_dav(val, &cdn, 1);
free(dn);
} else if (uu_strcaseeq(a, "uid")) {
const char *p = pwd->pw_name;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "uidNumber")) {
de = uint_list_dav(val, &pwd->pw_uid, 1);
} else if (uu_strcaseeq(a, "gecos")) {
const char *p = pwd->pw_gecos;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "homeDirectory")) {
const char *p = pwd->pw_dir;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "loginShell")) {
const char *p = pwd->pw_shell;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "x-sun-canonicalName")) {
char *canon;
RDLOCK_CONFIG();
(void) asprintf(&canon, "%s@%s",
pwd->pw_name, _idmapdstate.hostname);
UNLOCK_CONFIG();
if (canon == NULL)
goto nomem;
const char *ccanon = canon;
de = str_list_dav(val, &ccanon, 1);
free(canon);
} else if (uu_strcaseeq(a, "x-sun-provider")) {
const char *provider = "UNIX-passwd";
de = str_list_dav(val, &provider, 1);
}
} else if (grp != NULL) {
/*
* Handle attributes for group entries.
*/
if (uu_strcaseeq(a, "cn")) {
const char *p = grp->gr_name;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "objectClass")) {
static const char *objectClasses[] = {
"top",
"posixGroup",
};
de = str_list_dav(val, objectClasses,
UU_NELEM(objectClasses));
} else if (uu_strcaseeq(a, "gidNumber")) {
de = uint_list_dav(val, &grp->gr_gid, 1);
} else if (uu_strcaseeq(a, "objectSid")) {
de = machine_sid_dav(val,
grp->gr_gid + LOCALRID_GID_MIN);
} else if (uu_strcaseeq(a, "displayName")) {
const char *p = grp->gr_name;
de = str_list_dav(val, &p, 1);
} else if (uu_strcaseeq(a, "distinguishedName")) {
char *dn;
RDLOCK_CONFIG();
(void) asprintf(&dn,
"cn=%s,ou=group,dc=%s",
grp->gr_name, _idmapdstate.hostname);
UNLOCK_CONFIG();
if (dn == NULL)
goto nomem;
const char *cdn = dn;
de = str_list_dav(val, &cdn, 1);
free(dn);
} else if (uu_strcaseeq(a, "memberUid")) {
/*
* NEEDSWORK: There is probably a non-cast
* way to do this, but I don't immediately
* see it.
*/
const char * const *members =
(const char * const *)grp->gr_mem;
de = str_list_dav(val, members, 0);
} else if (uu_strcaseeq(a, "x-sun-canonicalName")) {
char *canon;
RDLOCK_CONFIG();
(void) asprintf(&canon, "%s@%s",
grp->gr_name, _idmapdstate.hostname);
UNLOCK_CONFIG();
if (canon == NULL)
goto nomem;
const char *ccanon = canon;
de = str_list_dav(val, &ccanon, 1);
free(canon);
} else if (uu_strcaseeq(a, "x-sun-provider")) {
const char *provider = "UNIX-group";
de = str_list_dav(val, &provider, 1);
}
}
if (de != NULL)
return (de);
}
return (NULL);
nomem:
return (directory_error("ENOMEM.users",
"No memory allocating return value for user lookup", NULL));
}
/*
* Populate a directory attribute value with a SID based on our machine SID
* and the specified RID.
*
* It's a bit perverse that we must take a text-format SID and turn it into
* a binary-format SID, only to have the caller probably turn it back into
* text format, but SIDs are carried across LDAP in binary format.
*/
static
directory_error_t
machine_sid_dav(directory_values_rpc *lvals, unsigned int rid)
{
sid_t *sid;
directory_error_t de;
RDLOCK_CONFIG();
int len = strlen(_idmapdstate.cfg->pgcfg.machine_sid);
char buf[len + 100]; /* 100 is enough space for any RID */
(void) snprintf(buf, sizeof (buf), "%s-%u",
_idmapdstate.cfg->pgcfg.machine_sid, rid);
UNLOCK_CONFIG();
sid = sid_fromstr(buf);
if (sid == NULL)
goto nomem;
sid_to_le(sid);
de = bin_list_dav(lvals, sid, 1, sid_len(sid));
sid_free(sid);
return (de);
nomem:
return (directory_error("ENOMEM.machine_sid_dav",
"Out of memory allocating return value for lookup", NULL));
}
struct directory_provider_static directory_provider_nsswitch = {
"files",
directory_provider_nsswitch_get,
};
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Server-side support for directory information lookup functions.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <malloc.h>
#include <sys/types.h>
#include <netdb.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <libuutil.h>
#include <note.h>
#include "idmapd.h"
#include "directory.h"
#include "directory_private.h"
#include <rpcsvc/idmap_prot.h>
#include "directory_library_impl.h"
#include "directory_server_impl.h"
#include "sized_array.h"
/*
* Here's a list of all of the modules that provide directory
* information. In the fullness of time this should probably be
* a plugin-able switch mechanism.
* Note that the list is in precedence order.
*/
extern struct directory_provider_static directory_provider_builtin;
extern struct directory_provider_static directory_provider_nsswitch;
extern struct directory_provider_static directory_provider_ad;
struct directory_provider_static *providers[] = {
&directory_provider_builtin,
&directory_provider_nsswitch,
&directory_provider_ad,
};
/*
* This is the entry point for all directory lookup service requests.
*/
bool_t
directory_get_common_1_svc(
idmap_utf8str_list ids,
idmap_utf8str types,
idmap_utf8str_list attrs,
directory_results_rpc *result,
struct svc_req *req)
{
NOTE(ARGUNUSED(req))
int nids;
directory_entry_rpc *entries;
directory_error_t de;
int i;
nids = ids.idmap_utf8str_list_len;
entries = (directory_entry_rpc *)
calloc(nids, sizeof (directory_entry_rpc));
if (entries == NULL)
goto nomem;
result->directory_results_rpc_u.entries.entries_val = entries;
result->directory_results_rpc_u.entries.entries_len = nids;
result->failed = FALSE;
for (i = 0; i < nids; i++) {
if (strlen(ids.idmap_utf8str_list_val[i]) >
IDMAP_MAX_NAME_LEN) {
directory_entry_set_error(&entries[i],
directory_error("invalid_arg.id.too_long",
"Identifier too long", NULL));
}
}
for (i = 0; i < UU_NELEM(providers); i++) {
de = providers[i]->get(entries, &ids, types,
&attrs);
if (de != NULL)
goto err;
}
return (TRUE);
nomem:
de = directory_error("ENOMEM.get_common",
"Insufficient memory retrieving directory data", NULL);
err:
xdr_free(xdr_directory_results_rpc, (char *)result);
result->failed = TRUE;
return (
directory_error_to_rpc(&result->directory_results_rpc_u.err, de));
}
/*
* Split name into {domain, name}.
* Suggest allocating name and domain on the stack, same size as id,
* using variable length arrays.
*/
void
split_name(char *name, char *domain, char *id)
{
char *p;
if ((p = strchr(id, '@')) != NULL) {
(void) strlcpy(name, id, p - id + 1);
(void) strcpy(domain, p + 1);
} else if ((p = strchr(id, '\\')) != NULL) {
(void) strcpy(name, p + 1);
(void) strlcpy(domain, id, p - id + 1);
} else {
(void) strcpy(name, id);
(void) strcpy(domain, "");
}
}
/*
* Given a list of strings, return a set of directory attribute values.
*
* Mark that the attribute was found.
*
* Note that the terminating \0 is *not* included in the result, because
* that's the way that strings come from LDAP.
* (Note also that the client side stuff adds in a terminating \0.)
*
* Note that on error the array may have been partially populated and will
* need to be cleaned up by the caller. This is normally not a problem
* because the caller will need to clean up several such arrays.
*/
directory_error_t
str_list_dav(directory_values_rpc *lvals, const char * const *str_list, int n)
{
directory_value_rpc *dav;
int i;
if (n == 0) {
for (n = 0; str_list[n] != NULL; n++)
/* LOOP */;
}
dav = calloc(n, sizeof (directory_value_rpc));
if (dav == NULL)
goto nomem;
lvals->directory_values_rpc_u.values.values_val = dav;
lvals->directory_values_rpc_u.values.values_len = n;
lvals->found = TRUE;
for (i = 0; i < n; i++) {
int len;
len = strlen(str_list[i]);
dav[i].directory_value_rpc_val = uu_memdup(str_list[i], len);
if (dav[i].directory_value_rpc_val == NULL)
goto nomem;
dav[i].directory_value_rpc_len = len;
}
return (NULL);
nomem:
return (directory_error("ENOMEM.str_list_dav",
"Insufficient memory copying values"));
}
/*
* Given a list of unsigned integers, return a set of string directory
* attribute values.
*
* Mark that the attribute was found.
*
* Note that the terminating \0 is *not* included in the result, because
* that's the way that strings come from LDAP.
* (Note also that the client side stuff adds in a terminating \0.)
*
* Note that on error the array may have been partially populated and will
* need to be cleaned up by the caller. This is normally not a problem
* because the caller will need to clean up several such arrays.
*/
directory_error_t
uint_list_dav(directory_values_rpc *lvals, const unsigned int *array, int n)
{
directory_value_rpc *dav;
int i;
dav = calloc(n, sizeof (directory_value_rpc));
if (dav == NULL)
goto nomem;
lvals->directory_values_rpc_u.values.values_val = dav;
lvals->directory_values_rpc_u.values.values_len = n;
lvals->found = TRUE;
for (i = 0; i < n; i++) {
char buf[100]; /* larger than any integer */
int len;
(void) snprintf(buf, sizeof (buf), "%u", array[i]);
len = strlen(buf);
dav[i].directory_value_rpc_val = uu_memdup(buf, len);
if (dav[i].directory_value_rpc_val == NULL)
goto nomem;
dav[i].directory_value_rpc_len = len;
}
return (NULL);
nomem:
return (directory_error("ENOMEM.uint_list_dav",
"Insufficient memory copying values"));
}
/*
* Given a list of fixed-length binary chunks, return a set of binary
* directory attribute values.
*
* Mark that the attribute was found.
*
* Note that on error the array may have been partially populated and will
* need to be cleaned up by the caller. This is normally not a problem
* because the caller will need to clean up several such arrays.
*/
directory_error_t
bin_list_dav(directory_values_rpc *lvals, const void *array, int n, size_t sz)
{
directory_value_rpc *dav;
char *inbuf = (char *)array;
int i;
dav = calloc(n, sizeof (directory_value_rpc));
if (dav == NULL)
goto nomem;
lvals->directory_values_rpc_u.values.values_val = dav;
lvals->directory_values_rpc_u.values.values_len = n;
lvals->found = TRUE;
for (i = 0; i < n; i++) {
dav[i].directory_value_rpc_val = uu_memdup(inbuf, sz);
if (dav[i].directory_value_rpc_val == NULL)
goto nomem;
dav[i].directory_value_rpc_len = sz;
inbuf += sz;
}
return (NULL);
nomem:
return (directory_error("ENOMEM.bin_list_dav",
"Insufficient memory copying values"));
}
/*
* Set up to return an error on a particular directory entry.
* Note that the caller need not (and in fact must not) free
* the directory_error_t; it will be freed when the directory entry
* list is freed.
*/
void
directory_entry_set_error(directory_entry_rpc *ent, directory_error_t de)
{
xdr_free(xdr_directory_entry_rpc, (char *)&ent);
ent->status = DIRECTORY_ERROR;
(void) directory_error_to_rpc(&ent->directory_entry_rpc_u.err, de);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _DIRECTORY_SERVER_IMPL_H
#define _DIRECTORY_SERVER_IMPL_H
/*
* Internal implementation details for the server side of directory lookup.
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* Functions to populate Directory Attribute Value lists.
*/
directory_error_t str_list_dav(directory_values_rpc *lvals,
const char * const *str_list, int n);
directory_error_t uint_list_dav(directory_values_rpc *lvals,
const unsigned int *uint_list, int n);
directory_error_t bin_list_dav(directory_values_rpc *lvals,
const void *array, int n, size_t sz);
/*
* Split a name@domain into name, domain. Recommend allocating the
* destination buffers the same size as the input, on the stack,
* using variable length arrays.
*/
void split_name(char *name, char *domain, char *id);
/*
* Insert a directory_error_t into a directory entry to be returned.
* Caller MUST NOT free the directory_error_t.
*/
void directory_entry_set_error(directory_entry_rpc *ent,
directory_error_t de);
/*
* This is the structure by which a provider supplies its entry points.
* The name is not currently used.
*/
struct directory_provider_static {
char *name;
directory_error_t (*get)(
directory_entry_rpc *ret,
idmap_utf8str_list *ids,
idmap_utf8str types,
idmap_utf8str_list *attrs);
};
#ifdef __cplusplus
}
#endif
#endif /* _DIRECTORY_SERVER_IMPL_H */
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
Copyright 2018 Nexenta Systems, Inc. All rights reserved.
Copyright 2023 RackTop Systems, Inc.
CDDL HEADER START
The contents of this file are subject to the terms of the
Common Development and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
or http://www.opensolaris.org/os/licensing.
See the License for the specific language governing permissions
and limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each
file and include the License file at usr/src/OPENSOLARIS.LICENSE.
If applicable, add the following below this CDDL HEADER, with the
fields enclosed by brackets "[]" replaced with your own identifying
information: Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
NOTE: This service manifest is not editable; its contents will
be overwritten by package or patch operations, including
operating system upgrade. Make customizations in a different
file.
-->
<service_bundle type='manifest' name='SUNWcsr:idmap'>
<service
name='system/idmap'
type='service'
version='1'>
<create_default_instance enabled='false' />
<single_instance />
<dependency
name='rpcbind'
grouping='require_all'
restart_on='restart'
type='service'>
<service_fmri value='svc:/network/rpc/bind' />
</dependency>
<dependency name='filesystem-minimal'
grouping='require_all'
restart_on='error'
type='service'>
<service_fmri value='svc:/system/filesystem/minimal' />
</dependency>
<exec_method
type='method'
name='start'
exec='/usr/lib/idmapd'
timeout_seconds='60' />
<exec_method
type='method'
name='stop'
exec=':kill'
timeout_seconds='60' />
<exec_method
type='method'
name='refresh'
exec=':kill -HUP'
timeout_seconds='60' />
<property_group name='general' type='framework'>
<propval
name='action_authorization'
type='astring'
value='solaris.smf.manage.idmap' />
<propval
name='value_authorization'
type='astring'
value='solaris.smf.manage.idmap' />
</property_group>
<!--
Properties affecting the service
-->
<property_group name='config' type='application' >
<stability value='Unstable' />
<propval
name='list_size_limit'
type='count'
value='0' />
<propval
name='max_threads'
type='count'
value='40' />
<propval
name='value_authorization'
type='astring'
value='solaris.smf.value.idmap' />
<propval
name='discovery_retry_max_delay'
type='count'
value='30' />
<propval
name='id_cache_timeout'
type='count'
value='86400' />
<propval
name='name_cache_timeout'
type='count'
value='604800' />
<propval
name='preferred_dc'
type='astring'
value='' />
<propval
name='rediscovery_interval'
type='count'
value='3600' />
<propval
name='site_name'
type='astring'
value='' />
<propval
name='use_ads'
type='boolean'
value='true' />
<propval
name='use_lsa'
type='boolean'
value='true' />
</property_group>
<property_group name='debug' type='application' >
<stability value='Unstable' />
<propval name='all' type='integer' value='0' />
<propval name='config' type='integer' value='0' />
<propval name='mapping' type='integer' value='0' />
<propval name='discovery' type='integer' value='0' />
<propval name='dns' type='integer' value='0' />
<propval name='ldap' type='integer' value='0' />
<propval
name='value_authorization'
type='astring'
value='solaris.smf.value.idmap' />
</property_group>
<stability value='Unstable' />
<template>
<common_name>
<loctext xml:lang='C'>
Native Identity Mapping Service
</loctext>
</common_name>
<documentation>
<manpage title='idmapd' section='8'
manpath='/usr/share/man' />
<manpage title='idmap' section='8'
manpath='/usr/share/man' />
</documentation>
</template>
</service>
</service_bundle>
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2019 Nexenta Systems, Inc. All rights reserved.
* Copyright 2023 RackTop Systems, Inc.
*/
/*
* Config routines common to idmap(8) and idmapd(8)
*/
#include <stdlib.h>
#include <strings.h>
#include <libintl.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <uuid/uuid.h>
#include <pthread.h>
#include <port.h>
#include <sys/socket.h>
#include <net/route.h>
#include <sys/u8_textprep.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <note.h>
#include <limits.h>
#include "idmapd.h"
#include "addisc.h"
#define MACHINE_SID_LEN (9 + 3 * 11)
#define FMRI_BASE "svc:/system/idmap"
#define CONFIG_PG "config"
#define DEBUG_PG "debug"
#define RECONFIGURE 1
#define POKE_AUTO_DISCOVERY 2
#define KICK_AUTO_DISCOVERY 3
/*
* Default cache timeouts. Can override via svccfg
* config/id_cache_timeout = count: seconds
* config/name_cache_timeout = count: seconds
*/
#define ID_CACHE_TMO_DEFAULT 86400
#define NAME_CACHE_TMO_DEFAULT 604800
/*
* Default maximum time between rediscovery runs.
* config/rediscovery_interval = count: seconds
*/
#define REDISCOVERY_INTERVAL_DEFAULT 3600
/*
* Minimum time between rediscovery runs, in case adutils gives us a
* really short TTL (which it never should, but be defensive)
* (not configurable) seconds.
*/
#define MIN_REDISCOVERY_INTERVAL 60
/*
* Max number of concurrent door calls
*/
#define MAX_THREADS_DEFAULT 40
/*
* Number of failed discovery attempts before we mark the service degraded.
*/
#define DISCOVERY_RETRY_DEGRADE_CUTOFF 6
/*
* Default maximum time between discovery attempts when we don't have a DC.
* config/discovery_retry_max_delay = count: seconds
*/
#define DISCOVERY_RETRY_MAX_DELAY_DEFAULT 30
/*
* Initial retry delay when discovery fails. Doubles on every failure.
*/
#define DISCOVERY_RETRY_INITIAL_DELAY 1
enum event_type {
EVENT_NOTHING, /* Woke up for no good reason */
EVENT_TIMEOUT, /* Timeout expired */
EVENT_ROUTING, /* An interesting routing event happened */
EVENT_POKED, /* Requested from degrade_svc() */
EVENT_KICKED, /* Force rediscovery, i.e. DC failed. */
EVENT_REFRESH, /* SMF refresh */
};
static void idmapd_set_krb5_realm(char *);
static pthread_t update_thread_handle = 0;
static int idmapd_ev_port = -1;
static int rt_sock = -1;
struct enum_lookup_map directory_mapping_map[] = {
{ DIRECTORY_MAPPING_NONE, "none" },
{ DIRECTORY_MAPPING_NAME, "name" },
{ DIRECTORY_MAPPING_IDMU, "idmu" },
{ 0, NULL },
};
struct enum_lookup_map trust_dir_map[] = {
{ 1, "they trust us" },
{ 2, "we trust them" },
{ 3, "we trust each other" },
{ 0, NULL },
};
static int
generate_machine_uuid(char **machine_uuid)
{
uuid_t uu;
*machine_uuid = calloc(1, UUID_PRINTABLE_STRING_LENGTH + 1);
if (*machine_uuid == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (-1);
}
uuid_clear(uu);
uuid_generate_time(uu);
uuid_unparse(uu, *machine_uuid);
return (0);
}
static int
generate_machine_sid(char **machine_sid, char *machine_uuid)
{
union {
uuid_t uu;
uint32_t v[4];
} uv;
int len;
/*
* Split the 128-bit machine UUID into three 32-bit values
* we'll use as the "sub-authorities" of the machine SID.
* The machine_sid will have the form S-1-5-21-J-K-L
* (that's four sub-authorities altogether) where:
* J = last 4 bytes of node_addr,
* K = time_mid, time_hi_and_version
* L = time_low
* (see struct uuid)
*/
(void) memset(&uv, 0, sizeof (uv));
(void) uuid_parse(machine_uuid, uv.uu);
len = asprintf(machine_sid, "S-1-5-21-%u-%u-%u",
uv.v[3], uv.v[0], uv.v[1]);
if (len == -1 || *machine_sid == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (-1);
}
return (0);
}
/* In the case of error, exists is set to FALSE anyway */
static int
prop_exists(idmap_cfg_handles_t *handles, const char *name, boolean_t *exists)
{
scf_property_t *scf_prop;
*exists = B_FALSE;
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
return (-1);
}
if (scf_pg_get_property(handles->config_pg, name, scf_prop) == 0)
*exists = B_TRUE;
scf_property_destroy(scf_prop);
return (0);
}
static int
get_debug(idmap_cfg_handles_t *handles, const char *name)
{
int64_t i64 = 0;
scf_property_t *scf_prop;
scf_value_t *value;
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
abort();
}
value = scf_value_create(handles->main);
if (value == NULL) {
idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
scf_strerror(scf_error()));
abort();
}
if (scf_pg_get_property(handles->debug_pg, name, scf_prop) < 0) {
/* this is OK: the property is just undefined */
goto destruction;
}
if (scf_property_get_value(scf_prop, value) < 0) {
/* It is still OK when a property doesn't have any value */
goto destruction;
}
if (scf_value_get_integer(value, &i64) != 0) {
idmapdlog(LOG_ERR, "Can not retrieve %s/%s: %s",
DEBUG_PG, name, scf_strerror(scf_error()));
abort();
}
destruction:
scf_value_destroy(value);
scf_property_destroy(scf_prop);
return ((int)i64);
}
static int
get_val_bool(idmap_cfg_handles_t *handles, const char *name,
boolean_t *val, boolean_t default_val)
{
int rc = 0;
scf_property_t *scf_prop;
scf_value_t *value;
*val = default_val;
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
return (-1);
}
value = scf_value_create(handles->main);
if (value == NULL) {
idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
scf_strerror(scf_error()));
scf_property_destroy(scf_prop);
return (-1);
}
/* It is OK if the property is undefined */
if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
goto destruction;
/* It is still OK when a property doesn't have any value */
if (scf_property_get_value(scf_prop, value) < 0)
goto destruction;
uint8_t b;
rc = scf_value_get_boolean(value, &b);
if (rc == 0)
*val = (boolean_t)b;
destruction:
scf_value_destroy(value);
scf_property_destroy(scf_prop);
return (rc);
}
static int
get_val_int(idmap_cfg_handles_t *handles, const char *name,
void *val, scf_type_t type)
{
int rc = 0;
scf_property_t *scf_prop;
scf_value_t *value;
switch (type) {
case SCF_TYPE_COUNT:
*(uint64_t *)val = 0;
break;
case SCF_TYPE_INTEGER:
*(int64_t *)val = 0;
break;
default:
idmapdlog(LOG_ERR, "Invalid scf integer type (%d)",
type);
abort();
}
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
return (-1);
}
value = scf_value_create(handles->main);
if (value == NULL) {
idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
scf_strerror(scf_error()));
scf_property_destroy(scf_prop);
return (-1);
}
if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
/* this is OK: the property is just undefined */
goto destruction;
if (scf_property_get_value(scf_prop, value) < 0)
/* It is still OK when a property doesn't have any value */
goto destruction;
switch (type) {
case SCF_TYPE_COUNT:
rc = scf_value_get_count(value, val);
break;
case SCF_TYPE_INTEGER:
rc = scf_value_get_integer(value, val);
break;
default:
abort(); /* tested above */
/* NOTREACHED */
}
if (rc != 0) {
idmapdlog(LOG_ERR, "Can not retrieve config/%s: %s",
name, scf_strerror(scf_error()));
}
destruction:
scf_value_destroy(value);
scf_property_destroy(scf_prop);
return (rc);
}
static char *
scf_value2string(const char *name, scf_value_t *value)
{
static size_t max_val = 0;
if (max_val == 0)
max_val = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH);
char buf[max_val + 1];
if (scf_value_get_astring(value, buf, max_val + 1) < 0) {
idmapdlog(LOG_ERR, "Can not retrieve config/%s: %s",
name, scf_strerror(scf_error()));
return (NULL);
}
char *s = strdup(buf);
if (s == NULL)
idmapdlog(LOG_ERR, "Out of memory");
return (s);
}
/*
* Load a domain server property. These are multi-value string properties.
* We'll later map these to an ad_disc_ds_t, which includes looking up
* the name in DNS, so don't do that before startup completes.
*/
static int
get_val_ds(idmap_cfg_handles_t *handles, const char *name, char ***val)
{
scf_property_t *scf_prop;
scf_value_t *value;
scf_iter_t *iter;
char *host, **servers = NULL;
int len, i;
int count = 0;
int rc = -1;
*val = NULL;
restart:
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
return (-1);
}
value = scf_value_create(handles->main);
if (value == NULL) {
idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
scf_strerror(scf_error()));
scf_property_destroy(scf_prop);
return (-1);
}
iter = scf_iter_create(handles->main);
if (iter == NULL) {
idmapdlog(LOG_ERR, "scf_iter_create() failed: %s",
scf_strerror(scf_error()));
scf_value_destroy(value);
scf_property_destroy(scf_prop);
return (-1);
}
if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0) {
/* this is OK: the property is just undefined */
rc = 0;
goto destruction;
}
if (scf_iter_property_values(iter, scf_prop) < 0) {
idmapdlog(LOG_ERR,
"scf_iter_property_values(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
/* Workaround scf bugs -- can't reset an iteration */
if (count == 0) {
while (scf_iter_next_value(iter, value) > 0)
count++;
if (count == 0) {
/* no values */
rc = 0;
goto destruction;
}
scf_value_destroy(value);
scf_iter_destroy(iter);
scf_property_destroy(scf_prop);
goto restart;
}
if ((servers = calloc(count + 1, sizeof (*servers))) == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
goto destruction;
}
i = 0;
while (i < count && scf_iter_next_value(iter, value) > 0) {
if ((host = scf_value2string(name, value)) == NULL)
continue;
/*
* Ignore this server if the hostname is too long
* or empty (continue without i++)
*/
len = strlen(host);
if (len == 0) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "%s host=\"\"", name);
}
continue;
}
if (len >= AD_DISC_MAXHOSTNAME) {
idmapdlog(LOG_ERR, "Host name too long: %s", host);
idmapdlog(LOG_ERR, "ignoring %s value", name);
continue;
}
/* Add a DS to the array. */
servers[i++] = host;
}
if (i == 0) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "%s is empty", name);
}
free(servers);
servers = NULL;
}
*val = servers;
rc = 0;
destruction:
scf_value_destroy(value);
scf_iter_destroy(iter);
scf_property_destroy(scf_prop);
if (rc < 0) {
if (servers)
free(servers);
*val = NULL;
}
return (rc);
}
static int
resolve_ds_addr(idmap_cfg_handles_t *handles, const char *name, int defport,
char **ds, ad_disc_ds_t **val)
{
struct addrinfo hints = {
.ai_protocol = IPPROTO_TCP,
.ai_socktype = SOCK_STREAM
};
struct addrinfo *ai;
ad_disc_ds_t *servers = NULL;
int err, i, num_ds = 0;
*val = NULL;
if (ds == NULL || ds[0] == NULL) {
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "%s is empty", name);
return (0);
}
for (i = 0; ds[i] != NULL; i++)
num_ds++;
if ((servers = calloc(num_ds + 1, sizeof (*servers))) == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (-1);
}
i = 0;
while (i < num_ds && *ds != NULL) {
char port_str[8];
char *pport;
const char *host = *ds++;
servers[i].priority = 0;
servers[i].weight = 100;
servers[i].port = defport;
if ((pport = strchr(host, ':')) != NULL) {
*pport++ = '\0';
servers[i].port = strtol(pport,
(char **)NULL, 10);
if (servers[i].port == 0)
servers[i].port = defport;
}
/*
* Get the host address. If we can't, then
* log an error and skip this host.
*/
if (DBG(CONFIG, 2))
idmapdlog(LOG_INFO, "%s: lookup %s:%d",
name, host, servers[i].port);
(void) snprintf(port_str, sizeof (port_str),
"%d", servers[i].port);
ai = NULL;
err = getaddrinfo(host, port_str, &hints, &ai);
if (err != 0) {
idmapdlog(LOG_ERR,
"%s: No address for host: %s (%s); skipping host",
name, host, gai_strerror(err));
continue;
}
(void) strlcpy(servers[i].host, host,
sizeof (servers->host));
(void) memcpy(&servers[i].addr, ai->ai_addr, ai->ai_addrlen);
freeaddrinfo(ai);
/* Added a DS to the array. */
i++;
}
if (i == 0) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "No valid values in %s", name);
}
free(servers);
servers = NULL;
}
*val = servers;
return (0);
}
static int
get_val_astring(idmap_cfg_handles_t *handles, const char *name, char **val)
{
int rc = 0;
scf_property_t *scf_prop;
scf_value_t *value;
scf_prop = scf_property_create(handles->main);
if (scf_prop == NULL) {
idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
scf_strerror(scf_error()));
return (-1);
}
value = scf_value_create(handles->main);
if (value == NULL) {
idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
scf_strerror(scf_error()));
scf_property_destroy(scf_prop);
return (-1);
}
*val = NULL;
if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
/* this is OK: the property is just undefined */
goto destruction;
if (scf_property_get_value(scf_prop, value) < 0) {
idmapdlog(LOG_ERR,
"scf_property_get_value(%s) failed: %s",
name, scf_strerror(scf_error()));
rc = -1;
goto destruction;
}
*val = scf_value2string(name, value);
if (*val == NULL)
rc = -1;
destruction:
scf_value_destroy(value);
scf_property_destroy(scf_prop);
if (rc < 0) {
if (*val)
free(*val);
*val = NULL;
}
return (rc);
}
static int
del_val(
idmap_cfg_handles_t *handles,
scf_propertygroup_t *pg,
const char *name)
{
int rc = -1;
int ret;
scf_transaction_t *tx = NULL;
scf_transaction_entry_t *ent = NULL;
if ((tx = scf_transaction_create(handles->main)) == NULL) {
idmapdlog(LOG_ERR,
"scf_transaction_create() failed: %s",
scf_strerror(scf_error()));
goto destruction;
}
if ((ent = scf_entry_create(handles->main)) == NULL) {
idmapdlog(LOG_ERR,
"scf_entry_create() failed: %s",
scf_strerror(scf_error()));
goto destruction;
}
do {
if (scf_pg_update(pg) == -1) {
idmapdlog(LOG_ERR,
"scf_pg_update(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
if (scf_transaction_start(tx, pg) != 0) {
idmapdlog(LOG_ERR,
"scf_transaction_start(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
if (scf_transaction_property_delete(tx, ent, name) != 0) {
/* Don't complain if it already doesn't exist. */
if (scf_error() != SCF_ERROR_NOT_FOUND) {
idmapdlog(LOG_ERR,
"scf_transaction_property_delete() failed:"
" %s",
scf_strerror(scf_error()));
}
goto destruction;
}
ret = scf_transaction_commit(tx);
if (ret == 0)
scf_transaction_reset(tx);
} while (ret == 0);
if (ret == -1) {
idmapdlog(LOG_ERR,
"scf_transaction_commit(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
rc = 0;
destruction:
if (ent != NULL)
scf_entry_destroy(ent);
if (tx != NULL)
scf_transaction_destroy(tx);
return (rc);
}
static int
set_val(
idmap_cfg_handles_t *handles,
scf_propertygroup_t *pg,
const char *name,
scf_value_t *value)
{
int rc = -1;
int i;
scf_property_t *prop = NULL;
scf_transaction_t *tx = NULL;
scf_transaction_entry_t *ent = NULL;
if ((prop = scf_property_create(handles->main)) == NULL ||
(tx = scf_transaction_create(handles->main)) == NULL ||
(ent = scf_entry_create(handles->main)) == NULL) {
idmapdlog(LOG_ERR, "Unable to set property %s",
name, scf_strerror(scf_error()));
goto destruction;
}
for (i = 0; i < MAX_TRIES; i++) {
int ret;
if (scf_pg_update(pg) == -1) {
idmapdlog(LOG_ERR,
"scf_pg_update() failed: %s",
scf_strerror(scf_error()));
goto destruction;
}
if (scf_transaction_start(tx, pg) == -1) {
idmapdlog(LOG_ERR,
"scf_transaction_start(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
ret = scf_pg_get_property(pg, name, prop);
if (ret == SCF_SUCCESS) {
if (scf_transaction_property_change_type(tx, ent, name,
scf_value_type(value)) < 0) {
idmapdlog(LOG_ERR,
"scf_transaction_property_change_type(%s)"
" failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
if (scf_transaction_property_new(tx, ent, name,
scf_value_type(value)) < 0) {
idmapdlog(LOG_ERR,
"scf_transaction_property_new() failed: %s",
scf_strerror(scf_error()));
goto destruction;
}
} else {
idmapdlog(LOG_ERR,
"scf_pg_get_property(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
if (scf_entry_add_value(ent, value) == -1) {
idmapdlog(LOG_ERR,
"scf_entry_add_value() failed: %s",
scf_strerror(scf_error()));
goto destruction;
}
ret = scf_transaction_commit(tx);
if (ret == 0) {
/*
* Property group set in scf_transaction_start()
* is not the most recent. Update pg, reset tx and
* retry tx.
*/
idmapdlog(LOG_WARNING,
"scf_transaction_commit(%s) failed: %s",
name, scf_strerror(scf_error()));
scf_transaction_reset(tx);
continue;
}
if (ret != 1) {
idmapdlog(LOG_ERR,
"scf_transaction_commit(%s) failed: %s",
name, scf_strerror(scf_error()));
goto destruction;
}
/* Success! */
rc = 0;
break;
}
destruction:
scf_entry_destroy(ent);
scf_transaction_destroy(tx);
scf_property_destroy(prop);
return (rc);
}
static int
set_val_integer(
idmap_cfg_handles_t *handles,
scf_propertygroup_t *pg,
const char *name,
int64_t val)
{
scf_value_t *value = NULL;
int rc;
if ((value = scf_value_create(handles->main)) == NULL) {
idmapdlog(LOG_ERR, "Unable to set property %s",
name, scf_strerror(scf_error()));
return (-1);
}
scf_value_set_integer(value, val);
rc = set_val(handles, pg, name, value);
scf_value_destroy(value);
return (rc);
}
static int
set_val_astring(
idmap_cfg_handles_t *handles,
scf_propertygroup_t *pg,
const char *name,
const char *val)
{
scf_value_t *value = NULL;
int rc = -1;
if ((value = scf_value_create(handles->main)) == NULL) {
idmapdlog(LOG_ERR, "Unable to set property %s",
name, scf_strerror(scf_error()));
goto out;
}
if (scf_value_set_astring(value, val) == -1) {
idmapdlog(LOG_ERR,
"scf_value_set_astring() failed: %s",
scf_strerror(scf_error()));
goto out;
}
rc = set_val(handles, pg, name, value);
out:
scf_value_destroy(value);
return (rc);
}
/*
* This function updates a boolean value.
* If nothing has changed it returns 0 else 1
*/
static int
update_bool(boolean_t *value, boolean_t *new, char *name)
{
if (*value == *new)
return (0);
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "change %s=%s", name,
*new ? "true" : "false");
}
*value = *new;
return (1);
}
/*
* This function updates a uint64_t value.
* If nothing has changed it returns 0 else 1
*/
static int
update_uint64(uint64_t *value, uint64_t *new, char *name)
{
if (*value == *new)
return (0);
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "change %s=%llu", name, *new);
*value = *new;
return (1);
}
/*
* This function updates a string value.
* If nothing has changed it returns 0 else 1
*/
static int
update_string(char **value, char **new, char *name)
{
int changed;
if (*new == NULL && *value != NULL)
changed = 1;
else if (*new != NULL && *value == NULL)
changed = 1;
else if (*new != NULL && *value != NULL && strcmp(*new, *value) != 0)
changed = 1;
else
changed = 0;
/*
* Note that even if unchanged we can't just return; we must free one
* of the values.
*/
if (DBG(CONFIG, 1) && changed)
idmapdlog(LOG_INFO, "change %s=%s", name, CHECK_NULL(*new));
free(*value);
*value = *new;
*new = NULL;
return (changed);
}
static int
update_enum(int *value, int *new, char *name, struct enum_lookup_map *map)
{
if (*value == *new)
return (0);
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "change %s=%s", name,
enum_lookup(*new, map));
}
*value = *new;
return (1);
}
/*
* This function updates a directory service structure.
* If nothing has changed it returns 0 else 1
*/
static int
update_dirs(ad_disc_ds_t **value, ad_disc_ds_t **new, char *name)
{
if (*value == *new)
/* Nothing to do */
return (0);
if (*value != NULL && *new != NULL &&
ad_disc_compare_ds(*value, *new) == 0) {
free(*new);
*new = NULL;
return (0);
}
if (*value != NULL)
free(*value);
*value = *new;
*new = NULL;
if (*value == NULL) {
/* We're unsetting this DS property */
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "change %s=<none>", name);
return (1);
}
if (DBG(CONFIG, 1)) {
/* List all the new DSs */
char buf[64];
ad_disc_ds_t *ds;
for (ds = *value; ds->host[0] != '\0'; ds++) {
if (ad_disc_getnameinfo(buf, sizeof (buf), &ds->addr))
(void) strlcpy(buf, "?", sizeof (buf));
idmapdlog(LOG_INFO, "change %s=%s addr=%s port=%d",
name, ds->host, buf, ds->port);
}
}
return (1);
}
/*
* This function updates a trusted domains structure.
* If nothing has changed it returns 0 else 1
*/
static int
update_trusted_domains(ad_disc_trusteddomains_t **value,
ad_disc_trusteddomains_t **new, char *name)
{
int i;
if (*value == *new)
/* Nothing to do */
return (0);
if (*value != NULL && *new != NULL &&
ad_disc_compare_trusteddomains(*value, *new) == 0) {
free(*new);
*new = NULL;
return (0);
}
if (*value != NULL)
free(*value);
*value = *new;
*new = NULL;
if (*value == NULL) {
/* We're unsetting this DS property */
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "change %s=<none>", name);
return (1);
}
if (DBG(CONFIG, 1)) {
/* List all the new domains */
for (i = 0; (*value)[i].domain[0] != '\0'; i++) {
idmapdlog(LOG_INFO, "change %s=%s direction=%s", name,
(*value)[i].domain,
enum_lookup((*value)[i].direction, trust_dir_map));
}
}
return (1);
}
/*
* This function updates a domains in a forest structure.
* If nothing has changed it returns 0 else 1
*/
static int
update_domains_in_forest(ad_disc_domainsinforest_t **value,
ad_disc_domainsinforest_t **new, char *name)
{
int i;
if (*value == *new)
/* Nothing to do */
return (0);
if (*value != NULL && *new != NULL &&
ad_disc_compare_domainsinforest(*value, *new) == 0) {
free(*new);
*new = NULL;
return (0);
}
if (*value != NULL)
free(*value);
*value = *new;
*new = NULL;
if (*value == NULL) {
/* We're unsetting this DS property */
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "change %s=<none>", name);
return (1);
}
if (DBG(CONFIG, 1)) {
/* List all the new domains */
for (i = 0; (*value)[i].domain[0] != '\0'; i++) {
idmapdlog(LOG_INFO, "change %s=%s", name,
(*value)[i].domain);
}
}
return (1);
}
static void
free_trusted_forests(idmap_trustedforest_t **value, int *num_values)
{
int i;
for (i = 0; i < *num_values; i++) {
free((*value)[i].forest_name);
free((*value)[i].global_catalog);
free((*value)[i].domains_in_forest);
}
free(*value);
*value = NULL;
*num_values = 0;
}
static int
compare_trusteddomainsinforest(ad_disc_domainsinforest_t *df1,
ad_disc_domainsinforest_t *df2)
{
int i, j;
int num_df1 = 0;
int num_df2 = 0;
boolean_t match;
for (i = 0; df1[i].domain[0] != '\0'; i++)
if (df1[i].trusted)
num_df1++;
for (j = 0; df2[j].domain[0] != '\0'; j++)
if (df2[j].trusted)
num_df2++;
if (num_df1 != num_df2)
return (1);
for (i = 0; df1[i].domain[0] != '\0'; i++) {
if (df1[i].trusted) {
match = B_FALSE;
for (j = 0; df2[j].domain[0] != '\0'; j++) {
if (df2[j].trusted &&
domain_eq(df1[i].domain, df2[j].domain) &&
strcmp(df1[i].sid, df2[j].sid) == 0) {
match = B_TRUE;
break;
}
}
if (!match)
return (1);
}
}
return (0);
}
/*
* This function updates trusted forest structure.
* If nothing has changed it returns 0 else 1
*/
static int
update_trusted_forest(idmap_trustedforest_t **value, int *num_value,
idmap_trustedforest_t **new, int *num_new, char *name)
{
int i, j;
boolean_t match;
if (*value == *new)
/* Nothing to do */
return (0);
if (*value != NULL && *new != NULL) {
if (*num_value != *num_new)
goto not_equal;
for (i = 0; i < *num_value; i++) {
match = B_FALSE;
for (j = 0; j < *num_new; j++) {
if (strcmp((*value)[i].forest_name,
(*new)[j].forest_name) == 0 &&
ad_disc_compare_ds(
(*value)[i].global_catalog,
(*new)[j].global_catalog) == 0 &&
compare_trusteddomainsinforest(
(*value)[i].domains_in_forest,
(*new)[j].domains_in_forest) == 0) {
match = B_TRUE;
break;
}
}
if (!match)
goto not_equal;
}
free_trusted_forests(new, num_new);
return (0);
}
not_equal:
if (*value != NULL)
free_trusted_forests(value, num_value);
*value = *new;
*num_value = *num_new;
*new = NULL;
*num_new = 0;
if (*value == NULL) {
/* We're unsetting this DS property */
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "change %s=<none>", name);
return (1);
}
if (DBG(CONFIG, 1)) {
/* List all the trusted forests */
for (i = 0; i < *num_value; i++) {
idmap_trustedforest_t *f = &(*value)[i];
for (j = 0;
f->domains_in_forest[j].domain[0] != '\0';
j++) {
/* List trusted Domains in the forest. */
if (f->domains_in_forest[j].trusted)
idmapdlog(LOG_INFO,
"change %s=%s domain=%s",
name, f->forest_name,
f->domains_in_forest[j].domain);
}
/* List the hosts */
for (j = 0;
f->global_catalog[j].host[0] != '\0';
j++) {
idmapdlog(LOG_INFO,
"change %s=%s host=%s port=%d",
name, f->forest_name,
f->global_catalog[j].host,
f->global_catalog[j].port);
}
}
}
return (1);
}
const char *
enum_lookup(int value, struct enum_lookup_map *map)
{
for (; map->string != NULL; map++) {
if (value == map->value) {
return (map->string);
}
}
return ("(invalid)");
}
/*
* Returns 1 if the PF_ROUTE socket event indicates that we should rescan the
* interfaces.
*
* Shamelessly based on smb_nics_changed() and other PF_ROUTE uses in ON.
*/
static
boolean_t
pfroute_event_is_interesting(int rt_sock)
{
int nbytes;
int64_t msg[2048 / 8];
struct rt_msghdr *rtm;
boolean_t is_interesting = B_FALSE;
for (;;) {
if ((nbytes = read(rt_sock, msg, sizeof (msg))) <= 0)
break;
rtm = (struct rt_msghdr *)msg;
if (rtm->rtm_version != RTM_VERSION)
continue;
if (nbytes < rtm->rtm_msglen)
continue;
switch (rtm->rtm_type) {
case RTM_NEWADDR:
case RTM_DELADDR:
case RTM_IFINFO:
is_interesting = B_TRUE;
break;
default:
break;
}
}
return (is_interesting);
}
/*
* Wait for an event, and report what kind of event occurred.
*
* Note that there are cases where we are awoken but don't care about
* the lower-level event. We can't just loop here because we can't
* readily calculate how long to sleep the next time. We return
* EVENT_NOTHING and let the caller loop.
*/
static
enum event_type
wait_for_event(struct timespec *timeoutp)
{
port_event_t pe;
(void) memset(&pe, 0, sizeof (pe));
if (port_get(idmapd_ev_port, &pe, timeoutp) != 0) {
switch (errno) {
case EINTR:
return (EVENT_NOTHING);
case ETIME:
/* Timeout */
return (EVENT_TIMEOUT);
default:
/* EBADF, EBADFD, EFAULT, EINVAL (end of time?)? */
idmapdlog(LOG_ERR, "Event port failed: %s",
strerror(errno));
exit(1);
/* NOTREACHED */
}
}
switch (pe.portev_source) {
case 0:
/*
* This isn't documented, but seems to be what you get if
* the timeout is zero seconds and there are no events
* pending.
*/
return (EVENT_TIMEOUT);
case PORT_SOURCE_USER:
switch (pe.portev_events) {
case RECONFIGURE:
return (EVENT_REFRESH);
case POKE_AUTO_DISCOVERY:
return (EVENT_POKED);
case KICK_AUTO_DISCOVERY:
return (EVENT_KICKED);
}
return (EVENT_NOTHING);
case PORT_SOURCE_FD:
if (pe.portev_object == rt_sock) {
/*
* PF_ROUTE socket read event:
* re-associate fd
* handle event
*/
if (port_associate(idmapd_ev_port, PORT_SOURCE_FD,
rt_sock, POLLIN, NULL) != 0) {
idmapdlog(LOG_ERR, "Failed to re-associate the "
"routing socket with the event port: %s",
strerror(errno));
abort();
}
/*
* The network configuration may still be in flux.
* No matter, the resolver will re-transmit and
* timeout if need be.
*/
if (pfroute_event_is_interesting(rt_sock)) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_DEBUG,
"Interesting routing event");
}
return (EVENT_ROUTING);
} else {
if (DBG(CONFIG, 2)) {
idmapdlog(LOG_DEBUG,
"Boring routing event");
}
return (EVENT_NOTHING);
}
}
/* Event on an FD other than the routing FD? Ignore it. */
break;
}
return (EVENT_NOTHING);
}
void *
idmap_cfg_update_thread(void *arg)
{
NOTE(ARGUNUSED(arg))
idmap_pg_config_t *pgcfg = &_idmapdstate.cfg->pgcfg;
const ad_disc_t ad_ctx = _idmapdstate.cfg->handles.ad_ctx;
int flags = CFG_DISCOVER;
uint_t retry_count = 0;
for (;;) {
struct timespec timeout;
struct timespec *timeoutp;
int rc;
int ttl, max_ttl;
(void) ad_disc_SubnetChanged(ad_ctx);
rc = idmap_cfg_load(_idmapdstate.cfg, flags);
if (rc < -1) {
idmapdlog(LOG_ERR, "Fatal errors while reading "
"SMF properties");
exit(1);
} else if (rc == -1) {
idmapdlog(LOG_WARNING,
"Errors re-loading configuration may cause AD "
"lookups to fail");
}
/*
* If we don't know our domain name, we're not in a domain;
* don't bother with rediscovery until the next config change.
* Avoids hourly noise in workgroup mode.
*
* If we don't have a DC currently, use a greatly reduced TTL
* until we get one. Degrade if that takes too long.
*/
if (pgcfg->domain_name == NULL) {
ttl = -1;
/* We don't need a DC if we're no longer in a domain. */
if (retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF)
restore_svc();
retry_count = 0;
} else if (pgcfg->domain_controller == NULL ||
pgcfg->global_catalog == NULL) {
if (retry_count == 0)
ttl = DISCOVERY_RETRY_INITIAL_DELAY;
else
ttl *= 2;
if (ttl > pgcfg->discovery_retry_max_delay)
ttl = pgcfg->discovery_retry_max_delay;
if (++retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF) {
degrade_svc(B_FALSE,
"Too many DC discovery failures");
}
} else {
ttl = ad_disc_get_TTL(ad_ctx);
max_ttl = (int)pgcfg->rediscovery_interval;
if (ttl > max_ttl)
ttl = max_ttl;
if (ttl < MIN_REDISCOVERY_INTERVAL)
ttl = MIN_REDISCOVERY_INTERVAL;
if (retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF)
restore_svc();
retry_count = 0;
}
/*
* Wait for an interesting event. Note that we might get
* boring events between interesting events. If so, we loop.
*/
flags = CFG_DISCOVER;
for (;;) {
if (ttl < 0) {
timeoutp = NULL;
} else {
timeout.tv_sec = ttl;
timeout.tv_nsec = 0;
timeoutp = &timeout;
}
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG,
"_cfg_update_thread waiting");
switch (wait_for_event(timeoutp)) {
case EVENT_NOTHING:
if (DBG(CONFIG, 2))
idmapdlog(LOG_DEBUG, "Boring event.");
continue;
case EVENT_REFRESH:
if (DBG(CONFIG, 1))
idmapdlog(LOG_INFO, "SMF refresh");
/*
* Forget any DC we had previously.
*/
flags |= CFG_FORGET_DC;
break;
case EVENT_POKED:
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "poked");
break;
case EVENT_KICKED:
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "kicked");
flags |= CFG_FORGET_DC;
break;
case EVENT_TIMEOUT:
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "TTL expired");
break;
case EVENT_ROUTING:
/* Already logged to DEBUG */
break;
}
/* An interesting event! */
break;
}
}
/*
* Lint isn't happy with the concept of a function declared to
* return something, that doesn't return. Of course, merely adding
* the return isn't enough, because it's never reached...
*/
/*NOTREACHED*/
return (NULL);
}
int
idmap_cfg_start_updates(void)
{
if ((idmapd_ev_port = port_create()) < 0) {
idmapdlog(LOG_ERR, "Failed to create event port: %s",
strerror(errno));
return (-1);
}
if ((rt_sock = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
idmapdlog(LOG_ERR, "Failed to open routing socket: %s",
strerror(errno));
(void) close(idmapd_ev_port);
return (-1);
}
if (fcntl(rt_sock, F_SETFL, O_NDELAY|O_NONBLOCK) < 0) {
idmapdlog(LOG_ERR, "Failed to set routing socket flags: %s",
strerror(errno));
(void) close(rt_sock);
(void) close(idmapd_ev_port);
return (-1);
}
if (port_associate(idmapd_ev_port, PORT_SOURCE_FD,
rt_sock, POLLIN, NULL) != 0) {
idmapdlog(LOG_ERR, "Failed to associate the routing "
"socket with the event port: %s", strerror(errno));
(void) close(rt_sock);
(void) close(idmapd_ev_port);
return (-1);
}
if ((errno = pthread_create(&update_thread_handle, NULL,
idmap_cfg_update_thread, NULL)) != 0) {
idmapdlog(LOG_ERR, "Failed to start update thread: %s",
strerror(errno));
(void) port_dissociate(idmapd_ev_port, PORT_SOURCE_FD, rt_sock);
(void) close(rt_sock);
(void) close(idmapd_ev_port);
return (-1);
}
return (0);
}
/*
* Reject attribute names with invalid characters.
*/
static
int
valid_ldap_attr(const char *attr)
{
for (; *attr; attr++) {
if (!isalnum(*attr) && *attr != '-' &&
*attr != '_' && *attr != '.' && *attr != ';')
return (0);
}
return (1);
}
static
void
idmapd_set_debug(
idmap_cfg_handles_t *handles,
enum idmapd_debug item,
const char *name)
{
int val;
if (item < 0 || item > IDMAPD_DEBUG_MAX)
return;
val = get_debug(handles, name);
if (val != _idmapdstate.debug[item])
idmapdlog(LOG_DEBUG, "%s/%s = %d", DEBUG_PG, name, val);
_idmapdstate.debug[item] = val;
}
static
void
check_smf_debug_mode(idmap_cfg_handles_t *handles)
{
idmapd_set_debug(handles, IDMAPD_DEBUG_ALL, "all");
idmapd_set_debug(handles, IDMAPD_DEBUG_CONFIG, "config");
idmapd_set_debug(handles, IDMAPD_DEBUG_MAPPING, "mapping");
idmapd_set_debug(handles, IDMAPD_DEBUG_DISC, "discovery");
idmapd_set_debug(handles, IDMAPD_DEBUG_DNS, "dns");
idmapd_set_debug(handles, IDMAPD_DEBUG_LDAP, "ldap");
adutils_set_debug(AD_DEBUG_ALL, _idmapdstate.debug[IDMAPD_DEBUG_ALL]);
adutils_set_debug(AD_DEBUG_DISC, _idmapdstate.debug[IDMAPD_DEBUG_DISC]);
adutils_set_debug(AD_DEBUG_DNS, _idmapdstate.debug[IDMAPD_DEBUG_DNS]);
adutils_set_debug(AD_DEBUG_LDAP, _idmapdstate.debug[IDMAPD_DEBUG_LDAP]);
}
/*
* This is the half of idmap_cfg_load() that loads property values from
* SMF (using the config/ property group of the idmap FMRI).
*
* Return values: 0 -> success, -1 -> failure, -2 -> hard failures
* -3 -> hard smf config failures
* reading from SMF.
*/
static int
idmap_cfg_load_smf(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg,
int * const errors)
{
int rc;
char *s;
*errors = 0;
if (scf_pg_update(handles->config_pg) < 0) {
idmapdlog(LOG_ERR, "scf_pg_update() failed: %s",
scf_strerror(scf_error()));
return (-2);
}
if (scf_pg_update(handles->debug_pg) < 0) {
idmapdlog(LOG_ERR, "scf_pg_update() failed: %s",
scf_strerror(scf_error()));
return (-2);
}
check_smf_debug_mode(handles);
rc = get_val_bool(handles, "unresolvable_sid_mapping",
&pgcfg->eph_map_unres_sids, B_TRUE);
if (rc != 0)
(*errors)++;
rc = get_val_bool(handles, "use_ads",
&pgcfg->use_ads, B_TRUE);
if (rc != 0)
(*errors)++;
rc = get_val_bool(handles, "use_lsa",
&pgcfg->use_lsa, B_TRUE);
if (rc != 0)
(*errors)++;
rc = get_val_bool(handles, "disable_cross_forest_trusts",
&pgcfg->disable_cross_forest_trusts, B_TRUE);
if (rc != 0)
(*errors)++;
rc = get_val_astring(handles, "directory_based_mapping", &s);
if (rc != 0)
(*errors)++;
else if (s == NULL || strcasecmp(s, "none") == 0)
pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NONE;
else if (strcasecmp(s, "name") == 0)
pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NAME;
else if (strcasecmp(s, "idmu") == 0)
pgcfg->directory_based_mapping = DIRECTORY_MAPPING_IDMU;
else {
pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NONE;
idmapdlog(LOG_ERR,
"config/directory_based_mapping: invalid value \"%s\" ignored",
s);
(*errors)++;
}
free(s);
rc = get_val_int(handles, "list_size_limit",
&pgcfg->list_size_limit, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
rc = get_val_int(handles, "max_threads",
&pgcfg->max_threads, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
if (pgcfg->max_threads == 0)
pgcfg->max_threads = MAX_THREADS_DEFAULT;
if (pgcfg->max_threads > UINT_MAX)
pgcfg->max_threads = UINT_MAX;
rc = get_val_int(handles, "discovery_retry_max_delay",
&pgcfg->discovery_retry_max_delay, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
if (pgcfg->discovery_retry_max_delay == 0)
pgcfg->discovery_retry_max_delay =
DISCOVERY_RETRY_MAX_DELAY_DEFAULT;
rc = get_val_int(handles, "id_cache_timeout",
&pgcfg->id_cache_timeout, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
if (pgcfg->id_cache_timeout == 0)
pgcfg->id_cache_timeout = ID_CACHE_TMO_DEFAULT;
rc = get_val_int(handles, "name_cache_timeout",
&pgcfg->name_cache_timeout, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
if (pgcfg->name_cache_timeout == 0)
pgcfg->name_cache_timeout = NAME_CACHE_TMO_DEFAULT;
rc = get_val_int(handles, "rediscovery_interval",
&pgcfg->rediscovery_interval, SCF_TYPE_COUNT);
if (rc != 0)
(*errors)++;
if (pgcfg->rediscovery_interval == 0)
pgcfg->rediscovery_interval = REDISCOVERY_INTERVAL_DEFAULT;
rc = get_val_astring(handles, "domain_name",
&pgcfg->domain_name);
if (rc != 0)
(*errors)++;
else {
if (pgcfg->domain_name != NULL &&
pgcfg->domain_name[0] == '\0') {
free(pgcfg->domain_name);
pgcfg->domain_name = NULL;
}
if (pgcfg->domain_name != NULL)
pgcfg->domain_name_auto_disc = B_FALSE;
(void) ad_disc_set_DomainName(handles->ad_ctx,
pgcfg->domain_name);
}
rc = get_val_astring(handles, "default_domain",
&pgcfg->default_domain);
if (rc != 0) {
/*
* SCF failures fetching config/default_domain we treat
* as fatal as they may leave ID mapping rules that
* match unqualified winnames flapping in the wind.
*/
return (-2);
}
if (pgcfg->default_domain == NULL && pgcfg->domain_name != NULL) {
pgcfg->default_domain = strdup(pgcfg->domain_name);
}
rc = get_val_astring(handles, "domain_guid", &s);
if (rc != 0) {
(*errors)++;
} else if (s == NULL || s[0] == '\0') {
/* OK, not set. */
free(s);
} else {
uuid_t u;
if (uuid_parse(s, u) != 0) {
idmapdlog(LOG_ERR,
"config/domain_guid: invalid value \"%s\" ignored", s);
free(s);
(*errors)++;
} else {
pgcfg->domain_guid = s;
pgcfg->domain_guid_auto_disc = B_FALSE;
(void) ad_disc_set_DomainGUID(handles->ad_ctx, u);
}
}
rc = get_val_astring(handles, "machine_uuid", &pgcfg->machine_uuid);
if (rc != 0)
(*errors)++;
if (pgcfg->machine_uuid == NULL) {
/* If machine_uuid not configured, generate one */
if (generate_machine_uuid(&pgcfg->machine_uuid) < 0)
return (-2);
rc = set_val_astring(handles, handles->config_pg,
"machine_uuid", pgcfg->machine_uuid);
if (rc != 0)
(*errors)++;
}
rc = get_val_astring(handles, "machine_sid", &pgcfg->machine_sid);
if (rc != 0)
(*errors)++;
if (pgcfg->machine_sid == NULL) {
/*
* If machine_sid not configured, generate one
* from the machine UUID.
*/
if (generate_machine_sid(&pgcfg->machine_sid,
pgcfg->machine_uuid) < 0)
return (-2);
rc = set_val_astring(handles, handles->config_pg,
"machine_sid", pgcfg->machine_sid);
if (rc != 0)
(*errors)++;
}
rc = get_val_ds(handles, "domain_controller",
&pgcfg->cfg_domain_controller);
if (rc != 0)
(*errors)++;
rc = get_val_ds(handles, "preferred_dc",
&pgcfg->cfg_preferred_dc);
if (rc != 0)
(*errors)++;
rc = get_val_astring(handles, "forest_name", &pgcfg->forest_name);
if (rc != 0)
(*errors)++;
else {
if (pgcfg->forest_name != NULL &&
pgcfg->forest_name[0] == '\0') {
free(pgcfg->forest_name);
pgcfg->forest_name = NULL;
}
if (pgcfg->forest_name != NULL)
pgcfg->forest_name_auto_disc = B_FALSE;
(void) ad_disc_set_ForestName(handles->ad_ctx,
pgcfg->forest_name);
}
rc = get_val_astring(handles, "site_name", &pgcfg->site_name);
if (rc != 0)
(*errors)++;
else {
if (pgcfg->site_name != NULL &&
pgcfg->site_name[0] == '\0') {
free(pgcfg->site_name);
pgcfg->site_name = NULL;
}
if (pgcfg->site_name != NULL)
pgcfg->site_name_auto_disc = B_FALSE;
(void) ad_disc_set_SiteName(handles->ad_ctx, pgcfg->site_name);
}
rc = get_val_ds(handles, "global_catalog",
&pgcfg->cfg_global_catalog);
if (rc != 0)
(*errors)++;
/* Unless we're doing directory-based name mapping, we're done. */
if (pgcfg->directory_based_mapping != DIRECTORY_MAPPING_NAME)
return (0);
rc = get_val_astring(handles, "ad_unixuser_attr",
&pgcfg->ad_unixuser_attr);
if (rc != 0)
return (-2);
if (pgcfg->ad_unixuser_attr != NULL &&
!valid_ldap_attr(pgcfg->ad_unixuser_attr)) {
idmapdlog(LOG_ERR, "config/ad_unixuser_attr=%s is not a "
"valid LDAP attribute name", pgcfg->ad_unixuser_attr);
return (-3);
}
rc = get_val_astring(handles, "ad_unixgroup_attr",
&pgcfg->ad_unixgroup_attr);
if (rc != 0)
return (-2);
if (pgcfg->ad_unixgroup_attr != NULL &&
!valid_ldap_attr(pgcfg->ad_unixgroup_attr)) {
idmapdlog(LOG_ERR, "config/ad_unixgroup_attr=%s is not a "
"valid LDAP attribute name", pgcfg->ad_unixgroup_attr);
return (-3);
}
rc = get_val_astring(handles, "nldap_winname_attr",
&pgcfg->nldap_winname_attr);
if (rc != 0)
return (-2);
if (pgcfg->nldap_winname_attr != NULL &&
!valid_ldap_attr(pgcfg->nldap_winname_attr)) {
idmapdlog(LOG_ERR, "config/nldap_winname_attr=%s is not a "
"valid LDAP attribute name", pgcfg->nldap_winname_attr);
return (-3);
}
if (pgcfg->ad_unixuser_attr == NULL &&
pgcfg->ad_unixgroup_attr == NULL &&
pgcfg->nldap_winname_attr == NULL) {
idmapdlog(LOG_ERR,
"If config/directory_based_mapping property is set to "
"\"name\" then at least one of the following name mapping "
"attributes must be specified. (config/ad_unixuser_attr OR "
"config/ad_unixgroup_attr OR config/nldap_winname_attr)");
return (-3);
}
return (rc);
}
static
void
log_if_unable(const void *val, const char *what)
{
if (val == NULL) {
idmapdlog(LOG_DEBUG, "unable to discover %s", what);
}
}
static
void
discover_trusted_domains(idmap_pg_config_t *pgcfg, ad_disc_t ad_ctx)
{
ad_disc_t trusted_ctx;
int i, j, k, l;
char *forestname;
int num_trusteddomains;
boolean_t new_forest;
char *trusteddomain;
ad_disc_ds_t *globalcatalog;
idmap_trustedforest_t *trustedforests;
ad_disc_domainsinforest_t *domainsinforest;
pgcfg->trusted_domains =
ad_disc_get_TrustedDomains(ad_ctx, NULL);
if (pgcfg->forest_name != NULL && pgcfg->trusted_domains != NULL &&
pgcfg->trusted_domains[0].domain[0] != '\0') {
/*
* We have trusted domains. We need to go through every
* one and find its forest. If it is a new forest we then need
* to find its Global Catalog and the domains in the forest
*/
for (i = 0; pgcfg->trusted_domains[i].domain[0] != '\0'; i++)
continue;
num_trusteddomains = i;
trustedforests = calloc(num_trusteddomains,
sizeof (idmap_trustedforest_t));
j = 0;
for (i = 0; pgcfg->trusted_domains[i].domain[0] != '\0'; i++) {
trusteddomain = pgcfg->trusted_domains[i].domain;
trusted_ctx = ad_disc_init();
(void) ad_disc_set_DomainName(trusted_ctx,
trusteddomain);
forestname =
ad_disc_get_ForestName(trusted_ctx, NULL);
if (forestname == NULL) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_DEBUG,
"unable to discover Forest Name"
" for the trusted domain %s",
trusteddomain);
}
ad_disc_fini(trusted_ctx);
continue;
}
if (strcasecmp(forestname, pgcfg->forest_name) == 0) {
/*
* Ignore the domain as it is part of
* the primary forest
*/
free(forestname);
ad_disc_fini(trusted_ctx);
continue;
}
/* Is this a new forest? */
new_forest = B_TRUE;
for (k = 0; k < j; k++) {
if (strcasecmp(forestname,
trustedforests[k].forest_name) == 0) {
new_forest = B_FALSE;
domainsinforest =
trustedforests[k].domains_in_forest;
break;
}
}
if (!new_forest) {
/* Mark the domain as trusted */
for (l = 0;
domainsinforest[l].domain[0] != '\0'; l++) {
if (domain_eq(trusteddomain,
domainsinforest[l].domain)) {
domainsinforest[l].trusted =
TRUE;
break;
}
}
free(forestname);
ad_disc_fini(trusted_ctx);
continue;
}
/*
* Get the Global Catalog and the domains in
* this new forest.
*/
globalcatalog =
ad_disc_get_GlobalCatalog(trusted_ctx,
AD_DISC_PREFER_SITE, NULL);
if (globalcatalog == NULL) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_DEBUG,
"unable to discover Global Catalog"
" for the trusted domain %s",
trusteddomain);
}
free(forestname);
ad_disc_fini(trusted_ctx);
continue;
}
domainsinforest =
ad_disc_get_DomainsInForest(trusted_ctx, NULL);
if (domainsinforest == NULL) {
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_DEBUG,
"unable to discover Domains in the"
" Forest for the trusted domain %s",
trusteddomain);
}
free(globalcatalog);
free(forestname);
ad_disc_fini(trusted_ctx);
continue;
}
trustedforests[j].forest_name = forestname;
trustedforests[j].global_catalog = globalcatalog;
trustedforests[j].domains_in_forest = domainsinforest;
j++;
/* Mark the domain as trusted */
for (l = 0; domainsinforest[l].domain[0] != '\0';
l++) {
if (domain_eq(trusteddomain,
domainsinforest[l].domain)) {
domainsinforest[l].trusted = TRUE;
break;
}
}
ad_disc_fini(trusted_ctx);
}
if (j > 0) {
pgcfg->num_trusted_forests = j;
pgcfg->trusted_forests = trustedforests;
} else {
free(trustedforests);
}
}
}
/*
* This is the half of idmap_cfg_load() that auto-discovers values of
* discoverable properties that weren't already set via SMF properties.
*
* idmap_cfg_discover() is called *after* idmap_cfg_load_smf(), so it
* needs to be careful not to overwrite any properties set in SMF.
*/
static void
idmap_cfg_discover1(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg)
{
ad_disc_t ad_ctx = handles->ad_ctx;
FILE *status_fp = NULL;
time_t t0, t1;
t0 = time(NULL);
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Running domain discovery.");
(void) unlink(IDMAP_CACHEDIR "/discovery.log");
status_fp = fopen(IDMAP_CACHEDIR "/discovery.log", "w");
if (status_fp) {
(void) fchmod(fileno(status_fp), 0644);
ad_disc_set_StatusFP(ad_ctx, status_fp);
}
if (pgcfg->domain_name == NULL) {
idmapdlog(LOG_DEBUG, "No domain name specified.");
if (status_fp)
(void) fprintf(status_fp, "(no domain name)\n");
goto out;
}
if (pgcfg->domain_controller == NULL)
pgcfg->domain_controller =
ad_disc_get_DomainController(ad_ctx,
AD_DISC_PREFER_SITE,
&pgcfg->domain_controller_auto_disc);
if (pgcfg->domain_guid == NULL) {
char buf[UUID_PRINTABLE_STRING_LENGTH];
uchar_t *u = ad_disc_get_DomainGUID(ad_ctx,
&pgcfg->domain_guid_auto_disc);
(void) memset(buf, 0, sizeof (buf));
if (u != NULL) {
uuid_unparse(u, buf);
pgcfg->domain_guid = strdup(buf);
}
}
if (pgcfg->forest_name == NULL)
pgcfg->forest_name = ad_disc_get_ForestName(ad_ctx,
&pgcfg->forest_name_auto_disc);
if (pgcfg->site_name == NULL)
pgcfg->site_name = ad_disc_get_SiteName(ad_ctx,
&pgcfg->site_name_auto_disc);
if (DBG(CONFIG, 1)) {
log_if_unable(pgcfg->domain_name, "Domain Name");
log_if_unable(pgcfg->domain_controller,
"Domain Controller");
log_if_unable(pgcfg->domain_guid, "Domain GUID");
log_if_unable(pgcfg->forest_name, "Forest Name");
log_if_unable(pgcfg->site_name, "Site Name");
}
out:
if (status_fp) {
ad_disc_set_StatusFP(ad_ctx, NULL);
(void) fclose(status_fp);
status_fp = NULL;
}
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Domain discovery done.");
/*
* Log when this took more than 15 sec.
*/
t1 = time(NULL);
if (t1 > (t0 + 15)) {
idmapdlog(LOG_NOTICE, "Domain discovery took %d sec.",
(int)(t1 - t0));
idmapdlog(LOG_NOTICE, "Check the DNS configuration.");
}
}
/*
* This is the second part of discovery, which can take a while.
* We don't want to hold up parties who just want to know what
* domain controller we're using (like smbd), so this part runs
* after we've updated that info in the "live" config and told
* such consumers to go ahead.
*
* This is a lot like idmap_cfg_discover(), but used LDAP queries
* get the forest information from the global catalog servers.
*
* Note: the previous update_* calls have usually nuked any
* useful information from pgcfg before we get here, so we
* can only use it store discovery results, not to read.
*/
static void
idmap_cfg_discover2(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg)
{
ad_disc_t ad_ctx = handles->ad_ctx;
FILE *status_fp = NULL;
time_t t0, t1;
t0 = time(NULL);
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Running forest discovery.");
status_fp = fopen(IDMAP_CACHEDIR "/discovery.log", "a");
if (status_fp)
ad_disc_set_StatusFP(ad_ctx, status_fp);
if (pgcfg->global_catalog == NULL)
pgcfg->global_catalog =
ad_disc_get_GlobalCatalog(ad_ctx,
AD_DISC_PREFER_SITE,
&pgcfg->global_catalog_auto_disc);
if (pgcfg->global_catalog != NULL) {
pgcfg->domains_in_forest =
ad_disc_get_DomainsInForest(ad_ctx, NULL);
if (!pgcfg->disable_cross_forest_trusts)
discover_trusted_domains(pgcfg, ad_ctx);
}
if (DBG(CONFIG, 1)) {
log_if_unable(pgcfg->global_catalog, "Global Catalog");
log_if_unable(pgcfg->domains_in_forest,
"Domains in the Forest");
/* Empty trusted domains list is OK. */
}
if (status_fp) {
ad_disc_set_StatusFP(ad_ctx, NULL);
(void) fclose(status_fp);
status_fp = NULL;
}
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Forest discovery done.");
/*
* Log when this took more than 30 sec.
*/
t1 = time(NULL);
if (t1 > (t0 + 30)) {
idmapdlog(LOG_NOTICE, "Forest discovery took %d sec.",
(int)(t1 - t0));
idmapdlog(LOG_NOTICE, "Check AD join status.");
}
}
/*
* idmap_cfg_load() is called at startup, and periodically via the
* update thread when the auto-discovery TTLs expire, as well as part of
* the refresh method, to update the current configuration. It always
* reads from SMF, but you still have to refresh the service after
* changing the config pg in order for the changes to take effect.
*
* There is one flag:
*
* - CFG_DISCOVER
*
* If CFG_DISCOVER is set then idmap_cfg_load() calls
* idmap_cfg_discover() to discover, via DNS and LDAP lookups, property
* values that weren't set in SMF.
*
* idmap_cfg_load() will log (to LOG_NOTICE) whether the configuration
* changed.
*
* Return values: 0 -> success, -1 -> failure, -2 -> hard failures
* reading from SMF.
*/
int
idmap_cfg_load(idmap_cfg_t *cfg, int flags)
{
const ad_disc_t ad_ctx = cfg->handles.ad_ctx;
int rc = 0;
int errors;
int changed = 0;
bool_t dc_changed = FALSE;
bool_t gc_changed = FALSE;
idmap_pg_config_t new_pgcfg, *live_pgcfg;
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Loading configuration.");
live_pgcfg = &cfg->pgcfg;
(void) memset(&new_pgcfg, 0, sizeof (new_pgcfg));
(void) pthread_mutex_lock(&cfg->handles.mutex);
if ((rc = idmap_cfg_load_smf(&cfg->handles, &new_pgcfg, &errors)) < -1)
goto err;
if (flags & CFG_DISCOVER) {
ad_disc_refresh(ad_ctx);
/*
* Convert domain server configuration items to libadutils
* values. This involves DNS, so we want to avoid doing this
* during startup, less we risk slow or unresponsive servers
* causing startup to timeout.
*/
rc = resolve_ds_addr(&cfg->handles, "domain_controller", 389,
new_pgcfg.cfg_domain_controller,
&new_pgcfg.domain_controller);
if (rc != 0)
errors++;
else {
(void) ad_disc_set_DomainController(ad_ctx,
new_pgcfg.domain_controller);
new_pgcfg.domain_controller_auto_disc = B_FALSE;
}
rc = resolve_ds_addr(&cfg->handles, "preferred_dc", 389,
new_pgcfg.cfg_preferred_dc,
&new_pgcfg.preferred_dc);
if (rc != 0)
errors++;
else {
(void) ad_disc_set_PreferredDC(ad_ctx,
new_pgcfg.preferred_dc);
new_pgcfg.preferred_dc_auto_disc = B_FALSE;
}
rc = resolve_ds_addr(&cfg->handles, "global_catalog", 3268,
new_pgcfg.cfg_global_catalog,
&new_pgcfg.global_catalog);
if (rc != 0)
errors++;
else {
(void) ad_disc_set_GlobalCatalog(ad_ctx,
new_pgcfg.global_catalog);
new_pgcfg.global_catalog_auto_disc = B_FALSE;
}
/*
* Unless we've been asked to forget the current DC,
* give preference (in order) to the preferred DC if
* configured, or the current DC. These preferences
* reduce undesirable DC changes.
*/
if (flags & CFG_FORGET_DC) {
(void) ad_disc_set_PreferredDC(ad_ctx, NULL);
} else if (new_pgcfg.preferred_dc != NULL) {
(void) ad_disc_set_PreferredDC(ad_ctx,
new_pgcfg.preferred_dc);
} else if (live_pgcfg->domain_controller != NULL) {
(void) ad_disc_set_PreferredDC(ad_ctx,
live_pgcfg->domain_controller);
} else {
(void) ad_disc_set_PreferredDC(ad_ctx, NULL);
}
/*
* We want a way to tell adspriv_getdcname_1_svc()
* (and others) that discovery is running and therefore
* they may want to wait a bit or return an error...
*/
(void) mutex_lock(&_idmapdstate.addisc_lk);
_idmapdstate.addisc_st |= ADDISC_ST_RUNNING;
(void) mutex_unlock(&_idmapdstate.addisc_lk);
idmap_cfg_discover1(&cfg->handles, &new_pgcfg);
WRLOCK_CONFIG();
(void) mutex_lock(&_idmapdstate.addisc_lk);
_idmapdstate.addisc_st = 0;
(void) cond_broadcast(&_idmapdstate.addisc_cv);
(void) mutex_unlock(&_idmapdstate.addisc_lk);
} else {
WRLOCK_CONFIG();
}
/* Non-discoverable props updated here */
changed += update_uint64(&live_pgcfg->list_size_limit,
&new_pgcfg.list_size_limit, "list_size_limit");
changed += update_uint64(&live_pgcfg->max_threads,
&new_pgcfg.max_threads, "max_threads");
changed += update_uint64(&live_pgcfg->discovery_retry_max_delay,
&new_pgcfg.discovery_retry_max_delay, "discovery_retry_max_delay");
changed += update_uint64(&live_pgcfg->id_cache_timeout,
&new_pgcfg.id_cache_timeout, "id_cache_timeout");
changed += update_uint64(&live_pgcfg->name_cache_timeout,
&new_pgcfg.name_cache_timeout, "name_cache_timeout");
changed += update_uint64(&live_pgcfg->rediscovery_interval,
&new_pgcfg.rediscovery_interval, "rediscovery_interval");
changed += update_string(&live_pgcfg->machine_sid,
&new_pgcfg.machine_sid, "machine_sid");
changed += update_bool(&live_pgcfg->eph_map_unres_sids,
&new_pgcfg.eph_map_unres_sids, "unresolvable_sid_mapping");
changed += update_bool(&live_pgcfg->use_ads,
&new_pgcfg.use_ads, "use_ads");
changed += update_bool(&live_pgcfg->use_lsa,
&new_pgcfg.use_lsa, "use_lsa");
changed += update_bool(&live_pgcfg->disable_cross_forest_trusts,
&new_pgcfg.disable_cross_forest_trusts,
"disable_cross_forest_trusts");
changed += update_enum(&live_pgcfg->directory_based_mapping,
&new_pgcfg.directory_based_mapping, "directory_based_mapping",
directory_mapping_map);
changed += update_string(&live_pgcfg->ad_unixuser_attr,
&new_pgcfg.ad_unixuser_attr, "ad_unixuser_attr");
changed += update_string(&live_pgcfg->ad_unixgroup_attr,
&new_pgcfg.ad_unixgroup_attr, "ad_unixgroup_attr");
changed += update_string(&live_pgcfg->nldap_winname_attr,
&new_pgcfg.nldap_winname_attr, "nldap_winname_attr");
changed += update_string(&live_pgcfg->default_domain,
&new_pgcfg.default_domain, "default_domain");
changed += update_dirs(&live_pgcfg->preferred_dc,
&new_pgcfg.preferred_dc, "preferred_dc");
/* Props that can be discovered or set in SMF updated here */
if (update_string(&live_pgcfg->domain_name,
&new_pgcfg.domain_name, "domain_name")) {
changed++;
dc_changed = TRUE;
gc_changed = TRUE;
idmapd_set_krb5_realm(live_pgcfg->domain_name);
}
live_pgcfg->domain_name_auto_disc = new_pgcfg.domain_name_auto_disc;
changed += update_string(&live_pgcfg->domain_guid,
&new_pgcfg.domain_guid, "domain_guid");
live_pgcfg->domain_guid_auto_disc = new_pgcfg.domain_guid_auto_disc;
if (update_dirs(&live_pgcfg->domain_controller,
&new_pgcfg.domain_controller, "domain_controller")) {
changed++;
dc_changed = TRUE;
}
live_pgcfg->domain_controller_auto_disc =
new_pgcfg.domain_controller_auto_disc;
changed += update_string(&live_pgcfg->forest_name,
&new_pgcfg.forest_name, "forest_name");
live_pgcfg->forest_name_auto_disc = new_pgcfg.forest_name_auto_disc;
changed += update_string(&live_pgcfg->site_name,
&new_pgcfg.site_name, "site_name");
live_pgcfg->site_name_auto_disc = new_pgcfg.site_name_auto_disc;
/* Note: explicitly ignoring the bare string domain server values */
if (DBG(CONFIG, 1)) {
if (changed)
idmapdlog(LOG_NOTICE, "Configuration changed");
else
idmapdlog(LOG_NOTICE, "Configuration unchanged");
}
UNLOCK_CONFIG();
if (dc_changed) {
notify_dc_changed();
}
/*
* Discovery2 can take a while.
*/
if (flags & CFG_DISCOVER) {
if (live_pgcfg->domain_name != NULL &&
live_pgcfg->forest_name != NULL)
idmap_cfg_discover2(&cfg->handles, &new_pgcfg);
ad_disc_done(ad_ctx);
}
WRLOCK_CONFIG();
/* More props that can be discovered or set in SMF */
if (update_dirs(&live_pgcfg->global_catalog,
&new_pgcfg.global_catalog, "global_catalog")) {
changed++;
gc_changed = TRUE;
}
live_pgcfg->global_catalog_auto_disc =
new_pgcfg.global_catalog_auto_disc;
/* Props that are only discovered (never in SMF) */
if (update_domains_in_forest(&live_pgcfg->domains_in_forest,
&new_pgcfg.domains_in_forest, "domains_in_forest")) {
changed++;
gc_changed = TRUE;
}
if (update_trusted_domains(&live_pgcfg->trusted_domains,
&new_pgcfg.trusted_domains, "trusted_domains")) {
changed++;
if (live_pgcfg->trusted_domains != NULL &&
live_pgcfg->trusted_domains[0].domain[0] != '\0')
gc_changed = TRUE;
}
if (update_trusted_forest(&live_pgcfg->trusted_forests,
&live_pgcfg->num_trusted_forests, &new_pgcfg.trusted_forests,
&new_pgcfg.num_trusted_forests, "trusted_forest")) {
changed++;
if (live_pgcfg->trusted_forests != NULL)
gc_changed = TRUE;
}
if (DBG(CONFIG, 1)) {
if (changed)
idmapdlog(LOG_NOTICE, "Configuration changed");
else
idmapdlog(LOG_NOTICE, "Configuration unchanged");
}
UNLOCK_CONFIG();
if (dc_changed)
reload_dcs();
if (gc_changed)
reload_gcs();
idmap_cfg_unload(&new_pgcfg);
err:
(void) pthread_mutex_unlock(&cfg->handles.mutex);
if (rc < -1)
return (rc);
return ((errors == 0) ? 0 : -1);
}
/*
* Initialize 'cfg'.
*/
idmap_cfg_t *
idmap_cfg_init()
{
idmap_cfg_handles_t *handles;
/* First the smf repository handles: */
idmap_cfg_t *cfg = calloc(1, sizeof (idmap_cfg_t));
if (!cfg) {
idmapdlog(LOG_ERR, "Out of memory");
return (NULL);
}
handles = &cfg->handles;
(void) pthread_mutex_init(&handles->mutex, NULL);
if (!(handles->main = scf_handle_create(SCF_VERSION))) {
idmapdlog(LOG_ERR, "scf_handle_create() failed: %s",
scf_strerror(scf_error()));
goto error;
}
if (scf_handle_bind(handles->main) < 0) {
idmapdlog(LOG_ERR, "scf_handle_bind() failed: %s",
scf_strerror(scf_error()));
goto error;
}
if (!(handles->service = scf_service_create(handles->main)) ||
!(handles->instance = scf_instance_create(handles->main)) ||
!(handles->config_pg = scf_pg_create(handles->main)) ||
!(handles->debug_pg = scf_pg_create(handles->main))) {
idmapdlog(LOG_ERR, "scf handle creation failed: %s",
scf_strerror(scf_error()));
goto error;
}
if (scf_handle_decode_fmri(handles->main,
FMRI_BASE "/:properties/" CONFIG_PG,
NULL, /* scope */
handles->service, /* service */
handles->instance, /* instance */
handles->config_pg, /* pg */
NULL, /* prop */
SCF_DECODE_FMRI_EXACT) < 0) {
idmapdlog(LOG_ERR, "scf_handle_decode_fmri() failed: %s",
scf_strerror(scf_error()));
goto error;
}
if (scf_service_get_pg(handles->service,
DEBUG_PG, handles->debug_pg) < 0) {
idmapdlog(LOG_ERR, "Property group \"%s\": %s",
DEBUG_PG, scf_strerror(scf_error()));
goto error;
}
check_smf_debug_mode(handles);
/* Initialize AD Auto Discovery context */
handles->ad_ctx = ad_disc_init();
if (handles->ad_ctx == NULL)
goto error;
return (cfg);
error:
(void) idmap_cfg_fini(cfg);
return (NULL);
}
void
idmap_cfg_unload(idmap_pg_config_t *pgcfg)
{
if (pgcfg->default_domain) {
free(pgcfg->default_domain);
pgcfg->default_domain = NULL;
}
if (pgcfg->domain_name) {
free(pgcfg->domain_name);
pgcfg->domain_name = NULL;
}
if (pgcfg->domain_guid) {
free(pgcfg->domain_guid);
pgcfg->domain_guid = NULL;
}
if (pgcfg->machine_sid) {
free(pgcfg->machine_sid);
pgcfg->machine_sid = NULL;
}
if (pgcfg->cfg_domain_controller) {
char **host = &pgcfg->cfg_domain_controller[0];
while (*host != NULL)
free(*host++);
free(pgcfg->cfg_domain_controller);
pgcfg->cfg_domain_controller = NULL;
}
if (pgcfg->domain_controller) {
free(pgcfg->domain_controller);
pgcfg->domain_controller = NULL;
}
if (pgcfg->cfg_preferred_dc) {
char **host = &pgcfg->cfg_preferred_dc[0];
while (*host != NULL)
free(*host++);
free(pgcfg->cfg_preferred_dc);
pgcfg->cfg_preferred_dc = NULL;
}
if (pgcfg->preferred_dc) {
free(pgcfg->preferred_dc);
pgcfg->preferred_dc = NULL;
}
if (pgcfg->forest_name) {
free(pgcfg->forest_name);
pgcfg->forest_name = NULL;
}
if (pgcfg->site_name) {
free(pgcfg->site_name);
pgcfg->site_name = NULL;
}
if (pgcfg->cfg_global_catalog) {
char **host = &pgcfg->cfg_global_catalog[0];
while (*host != NULL)
free(*host++);
free(pgcfg->cfg_global_catalog);
pgcfg->cfg_global_catalog = NULL;
}
if (pgcfg->global_catalog) {
free(pgcfg->global_catalog);
pgcfg->global_catalog = NULL;
}
if (pgcfg->trusted_domains) {
free(pgcfg->trusted_domains);
pgcfg->trusted_domains = NULL;
}
if (pgcfg->trusted_forests)
free_trusted_forests(&pgcfg->trusted_forests,
&pgcfg->num_trusted_forests);
if (pgcfg->ad_unixuser_attr) {
free(pgcfg->ad_unixuser_attr);
pgcfg->ad_unixuser_attr = NULL;
}
if (pgcfg->ad_unixgroup_attr) {
free(pgcfg->ad_unixgroup_attr);
pgcfg->ad_unixgroup_attr = NULL;
}
if (pgcfg->nldap_winname_attr) {
free(pgcfg->nldap_winname_attr);
pgcfg->nldap_winname_attr = NULL;
}
}
int
idmap_cfg_fini(idmap_cfg_t *cfg)
{
idmap_cfg_handles_t *handles = &cfg->handles;
idmap_cfg_unload(&cfg->pgcfg);
(void) pthread_mutex_destroy(&handles->mutex);
scf_pg_destroy(handles->config_pg);
if (handles->debug_pg != NULL)
scf_pg_destroy(handles->debug_pg);
scf_instance_destroy(handles->instance);
scf_service_destroy(handles->service);
scf_handle_destroy(handles->main);
if (handles->ad_ctx != NULL)
ad_disc_fini(handles->ad_ctx);
free(cfg);
return (0);
}
void
idmap_cfg_poke_updates(void)
{
int prev_st;
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "idmap_cfg_poke_updates");
}
(void) mutex_lock(&_idmapdstate.addisc_lk);
prev_st = _idmapdstate.addisc_st;
_idmapdstate.addisc_st |= ADDISC_ST_REQUESTED;
(void) mutex_unlock(&_idmapdstate.addisc_lk);
if (prev_st & ADDISC_ST_REQUESTED) {
idmapdlog(LOG_DEBUG, "already poked");
} else {
idmapdlog(LOG_DEBUG, "port send poke");
(void) port_send(idmapd_ev_port, POKE_AUTO_DISCOVERY, NULL);
}
}
void
idmap_cfg_force_rediscovery(void)
{
int prev_st;
if (DBG(CONFIG, 1)) {
idmapdlog(LOG_INFO, "idmap_cfg_force_rediscovery");
}
(void) mutex_lock(&_idmapdstate.addisc_lk);
prev_st = _idmapdstate.addisc_st;
_idmapdstate.addisc_st |= ADDISC_ST_REQUESTED;
(void) mutex_unlock(&_idmapdstate.addisc_lk);
if (prev_st & ADDISC_ST_REQUESTED) {
idmapdlog(LOG_DEBUG, "already kicked");
} else {
idmapdlog(LOG_DEBUG, "port send kick");
(void) port_send(idmapd_ev_port, KICK_AUTO_DISCOVERY, NULL);
}
}
/*ARGSUSED*/
void
idmap_cfg_hup_handler(int sig)
{
if (idmapd_ev_port >= 0)
(void) port_send(idmapd_ev_port, RECONFIGURE, NULL);
}
/*
* Upgrade the debug flags.
*
* We're replacing a single debug flag with a fine-grained mechanism that
* is also capable of considerably more verbosity. We'll take a stab at
* producing roughly the same level of output.
*/
static
int
upgrade_debug(idmap_cfg_handles_t *handles)
{
boolean_t debug_present;
const char DEBUG_PROP[] = "debug";
int rc;
rc = prop_exists(handles, DEBUG_PROP, &debug_present);
if (rc != 0)
return (rc);
if (!debug_present)
return (0);
idmapdlog(LOG_INFO,
"Upgrading old %s/%s setting to %s/* settings.",
CONFIG_PG, DEBUG_PROP, DEBUG_PG);
rc = set_val_integer(handles, handles->debug_pg, "config", 1);
if (rc != 0)
return (rc);
rc = set_val_integer(handles, handles->debug_pg, "discovery", 1);
if (rc != 0)
return (rc);
rc = del_val(handles, handles->config_pg, DEBUG_PROP);
if (rc != 0)
return (rc);
return (0);
}
/*
* Upgrade the DS mapping flags.
*
* If the old ds_name_mapping_enabled flag is present, then
* if the new directory_based_mapping value is present, then
* if the two are compatible, delete the old and note it
* else delete the old and warn
* else
* set the new based on the old, and note it
* delete the old
*/
static
int
upgrade_directory_mapping(idmap_cfg_handles_t *handles)
{
boolean_t legacy_ds_name_mapping_present;
const char DS_NAME_MAPPING_ENABLED[] = "ds_name_mapping_enabled";
const char DIRECTORY_BASED_MAPPING[] = "directory_based_mapping";
int rc;
rc = prop_exists(handles, DS_NAME_MAPPING_ENABLED,
&legacy_ds_name_mapping_present);
if (rc != 0)
return (rc);
if (!legacy_ds_name_mapping_present)
return (0);
boolean_t legacy_ds_name_mapping_enabled;
rc = get_val_bool(handles, DS_NAME_MAPPING_ENABLED,
&legacy_ds_name_mapping_enabled, B_FALSE);
if (rc != 0)
return (rc);
char *legacy_mode;
char *legacy_bool_string;
if (legacy_ds_name_mapping_enabled) {
legacy_mode = "name";
legacy_bool_string = "true";
} else {
legacy_mode = "none";
legacy_bool_string = "false";
}
char *directory_based_mapping;
rc = get_val_astring(handles, DIRECTORY_BASED_MAPPING,
&directory_based_mapping);
if (rc != 0)
return (rc);
if (directory_based_mapping == NULL) {
idmapdlog(LOG_INFO,
"Upgrading old %s=%s setting\n"
"to %s=%s.",
DS_NAME_MAPPING_ENABLED, legacy_bool_string,
DIRECTORY_BASED_MAPPING, legacy_mode);
rc = set_val_astring(handles, handles->config_pg,
DIRECTORY_BASED_MAPPING, legacy_mode);
if (rc != 0)
return (rc);
} else {
boolean_t new_name_mapping;
if (strcasecmp(directory_based_mapping, "name") == 0)
new_name_mapping = B_TRUE;
else
new_name_mapping = B_FALSE;
if (legacy_ds_name_mapping_enabled == new_name_mapping) {
idmapdlog(LOG_INFO,
"Automatically removing old %s=%s setting\n"
"in favor of %s=%s.",
DS_NAME_MAPPING_ENABLED, legacy_bool_string,
DIRECTORY_BASED_MAPPING, directory_based_mapping);
} else {
idmapdlog(LOG_WARNING,
"Removing conflicting %s=%s setting\n"
"in favor of %s=%s.",
DS_NAME_MAPPING_ENABLED, legacy_bool_string,
DIRECTORY_BASED_MAPPING, directory_based_mapping);
}
free(directory_based_mapping);
}
rc = del_val(handles, handles->config_pg, DS_NAME_MAPPING_ENABLED);
if (rc != 0)
return (rc);
return (0);
}
/*
* Do whatever is necessary to upgrade idmap's configuration before
* we load it.
*/
int
idmap_cfg_upgrade(idmap_cfg_t *cfg)
{
int rc;
rc = upgrade_directory_mapping(&cfg->handles);
if (rc != 0)
return (rc);
rc = upgrade_debug(&cfg->handles);
if (rc != 0)
return (rc);
return (0);
}
/*
* The LDAP code passes principal names lacking any
* realm information, which causes mech_krb5 to do
* awful things trying to figure out the realm.
* Avoid that by making sure it has a default,
* even when krb5.conf is not configured.
*/
static void
idmapd_set_krb5_realm(char *domain)
{
static char realm[MAXHOSTNAMELEN];
size_t ilen, olen;
int err;
(void) unlink(IDMAP_CACHEDIR "/ccache");
if (domain == NULL) {
(void) unsetenv("KRB5_DEFAULT_REALM");
return;
}
/* Convert to upper case, in place. */
(void) strlcpy(realm, domain, sizeof (realm));
olen = ilen = strlen(realm);
(void) u8_textprep_str(realm, &ilen, realm, &olen,
U8_TEXTPREP_TOUPPER, U8_UNICODE_LATEST, &err);
(void) setenv("KRB5_DEFAULT_REALM", realm, 1);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
* Copyright 2023 RackTop Systems, Inc.
*/
#ifndef _IDMAP_CONFIG_H
#define _IDMAP_CONFIG_H
#include "idmap.h"
#include "addisc.h"
#include <libscf.h>
#include <synch.h>
#include <sys/uuid.h>
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_POLICY_SIZE 1023
#define DIRECTORY_MAPPING_NONE 0
#define DIRECTORY_MAPPING_NAME 1
#define DIRECTORY_MAPPING_IDMU 2
struct enum_lookup_map {
int value;
char *string;
};
extern struct enum_lookup_map directory_mapping_map[];
extern const char *enum_lookup(int value, struct enum_lookup_map *map);
/* SMF and auto-discovery context handles */
typedef struct idmap_cfg_handles {
pthread_mutex_t mutex;
scf_handle_t *main;
scf_instance_t *instance;
scf_service_t *service;
scf_propertygroup_t *config_pg;
scf_propertygroup_t *debug_pg;
ad_disc_t ad_ctx;
} idmap_cfg_handles_t;
/*
* This structure stores AD and AD-related configuration
*/
typedef struct idmap_trustedforest {
char *forest_name;
ad_disc_ds_t *global_catalog; /* global catalog hosts */
ad_disc_domainsinforest_t
*domains_in_forest;
} idmap_trustedforest_t;
typedef struct idmap_pg_config {
uint64_t list_size_limit;
uint64_t max_threads;
uint64_t discovery_retry_max_delay;
uint64_t id_cache_timeout;
uint64_t name_cache_timeout;
uint64_t rediscovery_interval;
char *machine_uuid; /* machine uuid */
char *machine_sid; /* machine sid */
char *default_domain; /* default domain name */
char *domain_name; /* AD domain name */
boolean_t domain_name_auto_disc;
char *domain_guid; /* GUID (string) */
boolean_t domain_guid_auto_disc;
char **cfg_domain_controller;
ad_disc_ds_t *domain_controller; /* domain controller hosts */
boolean_t domain_controller_auto_disc;
char *forest_name; /* forest name */
boolean_t forest_name_auto_disc;
char *site_name; /* site name */
boolean_t site_name_auto_disc;
char **cfg_global_catalog;
ad_disc_ds_t *global_catalog; /* global catalog hosts */
boolean_t global_catalog_auto_disc;
ad_disc_domainsinforest_t
*domains_in_forest;
ad_disc_trusteddomains_t
*trusted_domains; /* Trusted Domains */
int num_trusted_forests;
idmap_trustedforest_t
*trusted_forests; /* Array of trusted forests */
char **cfg_preferred_dc;
ad_disc_ds_t *preferred_dc;
boolean_t preferred_dc_auto_disc;
/*
* Following properties are associated with directory-based
* name-mappings.
*/
char *ad_unixuser_attr;
char *ad_unixgroup_attr;
char *nldap_winname_attr;
int directory_based_mapping; /* enum */
boolean_t eph_map_unres_sids;
boolean_t use_ads;
boolean_t use_lsa;
boolean_t disable_cross_forest_trusts;
} idmap_pg_config_t;
typedef struct idmap_cfg {
idmap_pg_config_t pgcfg; /* live AD/ID mapping config */
idmap_cfg_handles_t handles;
int initialized;
} idmap_cfg_t;
extern void idmap_cfg_unload(idmap_pg_config_t *);
extern int idmap_cfg_load(idmap_cfg_t *, int);
extern idmap_cfg_t *idmap_cfg_init(void);
extern int idmap_cfg_fini(idmap_cfg_t *);
extern int idmap_cfg_upgrade(idmap_cfg_t *);
extern int idmap_cfg_start_updates(void);
extern void idmap_cfg_poke_updates(void);
extern void idmap_cfg_force_rediscovery(void);
extern void idmap_cfg_hup_handler(int);
#define CFG_DISCOVER 0x1 /* Run discovery */
#define CFG_FORGET_DC 0x2 /* Forget current DC. */
#define CFG_LOG 0x4
#ifdef __cplusplus
}
#endif
#endif /* _IDMAP_CONFIG_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2019 Nexenta Systems, Inc. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
*/
/*
* LSA lookups
*/
#include <stdio.h>
#include <note.h>
#include <assert.h>
#include "idmapd.h"
#include "libsmb.h"
idmap_retcode
idmap_lsa_xlate_sid_type(const lsa_account_t *acct, idmap_id_type *ret_type)
{
switch (acct->a_sidtype) {
case SidTypeUser:
case SidTypeComputer:
case SidTypeDomain:
case SidTypeDeletedAccount:
case SidTypeUnknown:
case SidTypeLabel:
*ret_type = IDMAP_USID;
return (IDMAP_SUCCESS);
case SidTypeGroup:
case SidTypeAlias:
case SidTypeWellKnownGroup:
*ret_type = IDMAP_GSID;
return (IDMAP_SUCCESS);
case SidTypeNull:
case SidTypeInvalid:
default:
idmapdlog(LOG_WARNING,
"LSA lookup: bad type %d for %s@%s",
acct->a_sidtype, acct->a_name, acct->a_domain);
return (IDMAP_ERR_OTHER);
}
NOTE(NOTREACHED)
}
/* Given SID, look up name and type */
idmap_retcode
lookup_lsa_by_sid(
const char *sidprefix,
uint32_t rid,
char **ret_name,
char **ret_domain,
idmap_id_type *ret_type)
{
lsa_account_t acct;
char sid[SMB_SID_STRSZ + 1];
idmap_retcode ret;
int rc;
(void) memset(&acct, 0, sizeof (acct));
*ret_name = NULL;
*ret_domain = NULL;
(void) snprintf(sid, sizeof (sid), "%s-%u", sidprefix, rid);
rc = smb_lookup_lsid(sid, &acct);
if (rc != 0) {
idmapdlog(LOG_ERR, "Error: SMB lookup SID failed.");
idmapdlog(LOG_ERR,
"Check SMB service (svc:/network/smb/server).");
idmapdlog(LOG_ERR,
"Check connectivity to Active Directory.");
ret = IDMAP_ERR_OTHER;
goto out;
}
if (acct.a_status == NT_STATUS_NONE_MAPPED) {
ret = IDMAP_ERR_NOTFOUND;
goto out;
}
if (acct.a_status != NT_STATUS_SUCCESS) {
idmapdlog(LOG_WARNING,
"Warning: SMB lookup SID(%s) failed (0x%x)",
sid, acct.a_status);
/* Fail soft */
ret = IDMAP_ERR_NOTFOUND;
goto out;
}
ret = idmap_lsa_xlate_sid_type(&acct, ret_type);
if (ret != IDMAP_SUCCESS)
goto out;
*ret_name = strdup(acct.a_name);
if (*ret_name == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
*ret_domain = strdup(acct.a_domain);
if (*ret_domain == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
ret = IDMAP_SUCCESS;
out:
if (ret != IDMAP_SUCCESS) {
free(*ret_name);
*ret_name = NULL;
free(*ret_domain);
*ret_domain = NULL;
}
return (ret);
}
/* Given name and optional domain, look up SID, type, and canonical name */
idmap_retcode
lookup_lsa_by_name(
const char *name,
const char *domain,
char **ret_sidprefix,
uint32_t *ret_rid,
char **ret_name,
char **ret_domain,
idmap_id_type *ret_type)
{
lsa_account_t acct;
char *namedom = NULL;
idmap_retcode ret;
int rc;
(void) memset(&acct, 0, sizeof (acct));
*ret_sidprefix = NULL;
if (ret_name != NULL)
*ret_name = NULL;
if (ret_domain != NULL)
*ret_domain = NULL;
if (domain != NULL)
(void) asprintf(&namedom, "%s@%s", name, domain);
else
namedom = strdup(name);
if (namedom == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
rc = smb_lookup_lname(namedom, SidTypeUnknown, &acct);
if (rc != 0) {
idmapdlog(LOG_ERR, "Error: SMB lookup name failed.");
idmapdlog(LOG_ERR,
"Check SMB service (svc:/network/smb/server).");
idmapdlog(LOG_ERR,
"Check connectivity to Active Directory.");
ret = IDMAP_ERR_OTHER;
goto out;
}
if (acct.a_status == NT_STATUS_NONE_MAPPED) {
ret = IDMAP_ERR_NOTFOUND;
goto out;
}
if (acct.a_status != NT_STATUS_SUCCESS) {
idmapdlog(LOG_WARNING,
"Warning: SMB lookup name(%s) failed (0x%x)",
namedom, acct.a_status);
/* Fail soft */
ret = IDMAP_ERR_NOTFOUND;
goto out;
}
rc = smb_sid_splitstr(acct.a_sid, ret_rid);
assert(rc == 0);
*ret_sidprefix = strdup(acct.a_sid);
if (*ret_sidprefix == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
ret = idmap_lsa_xlate_sid_type(&acct, ret_type);
if (ret != IDMAP_SUCCESS)
goto out;
if (ret_name != NULL) {
*ret_name = strdup(acct.a_name);
if (*ret_name == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
}
if (ret_domain != NULL) {
*ret_domain = strdup(acct.a_domain);
if (*ret_domain == NULL) {
ret = IDMAP_ERR_MEMORY;
goto out;
}
}
ret = IDMAP_SUCCESS;
out:
free(namedom);
if (ret != IDMAP_SUCCESS) {
if (ret_name != NULL) {
free(*ret_name);
*ret_name = NULL;
}
if (ret_domain != NULL) {
free(*ret_domain);
*ret_domain = NULL;
}
free(*ret_sidprefix);
*ret_sidprefix = NULL;
}
return (ret);
}
/*
* This exists just so we can avoid exposing all of idmapd to libsmb.h.
* Like the above functions, it's a door call over to smbd.
*/
void
notify_dc_changed(void)
{
int rc;
rc = smb_notify_dc_changed();
if (rc != 0) {
idmapdlog(LOG_WARNING,
"Warning: smb_notify_dc_changed, rc=%d", rc);
}
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
*/
#ifndef IDMAP_LSA_H
#define IDMAP_LSA_H
/*
* LSA lookups
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <rpcsvc/idmap_prot.h>
/* Given SID, look up name and type */
idmap_retcode
lookup_lsa_by_sid(const char *sidprefix, uint32_t rid, char **ret_name,
char **ret_domain, idmap_id_type *ret_type);
/* Given name and optional domain, look up SID, type, and canonical name */
idmap_retcode lookup_lsa_by_name(const char *name, const char *domain,
char **ret_sidprefix, uint32_t *ret_rid, char **ret_name,
char **ret_domain, idmap_id_type *ret_type);
#ifdef __cplusplus
}
#endif
#endif /* IDMAP_LSA_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
* Copyright 2023 RackTop Systems, Inc.
* Copyright 2025 Bill Sommerfeld
*/
/*
* main() of idmapd(8)
*/
#include "idmapd.h"
#include <atomic.h>
#include <signal.h>
#include <rpc/pmap_clnt.h> /* for pmap_unset */
#include <string.h> /* strcmp */
#include <unistd.h> /* setsid */
#include <sys/types.h>
#include <memory.h>
#include <stropts.h>
#include <netconfig.h>
#include <sys/resource.h> /* rlimit */
#include <rpcsvc/daemon_utils.h> /* DAEMON_UID and DAEMON_GID */
#include <priv_utils.h> /* privileges */
#include <locale.h>
#include <sys/systeminfo.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <zone.h>
#include <door.h>
#include <port.h>
#include <tsol/label.h>
#include <sys/resource.h>
#include <sys/sid.h>
#include <sys/idmap.h>
#include <pthread.h>
#include <stdarg.h>
#include <assert.h>
#include <note.h>
#define CBUFSIZ 26 /* ctime(3c) */
static void term_handler(int);
static void init_idmapd();
static void fini_idmapd();
/* The DC Locator lives inside idmap (for now). */
extern void init_dc_locator(void);
extern void fini_dc_locator(void);
idmapd_state_t _idmapdstate;
mutex_t _svcstate_lock = ERRORCHECKMUTEX;
SVCXPRT *xprt = NULL;
static int dfd = -1; /* our door server fildes, for unregistration */
static boolean_t degraded = B_FALSE;
static uint32_t num_threads = 0;
static pthread_key_t create_threads_key;
static uint32_t max_threads = 40;
/*
* Server door thread start routine.
*
* Set a TSD value to the door thread. This enables the destructor to
* be called when this thread exits. Note that we need a non-NULL
* value for this or the TSD destructor is not called.
*/
/*ARGSUSED*/
static void *
idmapd_door_thread_start(void *arg)
{
static void *value = "NON-NULL TSD";
/*
* Disable cancellation to avoid memory leaks from not running
* the thread cleanup code.
*/
(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
(void) pthread_setspecific(create_threads_key, value);
(void) door_return(NULL, 0, NULL, 0);
/* make lint happy */
return (NULL);
}
/*
* Server door threads creation
*/
/*ARGSUSED*/
static void
idmapd_door_thread_create(door_info_t *dip)
{
int num;
pthread_t thread_id;
if ((num = atomic_inc_32_nv(&num_threads)) > max_threads) {
atomic_dec_32(&num_threads);
idmapdlog(LOG_DEBUG,
"thread creation refused - %d threads currently active",
num - 1);
return;
}
(void) pthread_create(&thread_id, NULL, idmapd_door_thread_start, NULL);
idmapdlog(LOG_DEBUG,
"created thread ID %d - %d threads currently active",
thread_id, num);
}
/*
* Server door thread cleanup
*/
/*ARGSUSED*/
static void
idmapd_door_thread_cleanup(void *arg)
{
int num;
/* set TSD to NULL so we don't loop infinitely */
(void) pthread_setspecific(create_threads_key, NULL);
num = atomic_dec_32_nv(&num_threads);
idmapdlog(LOG_DEBUG,
"exiting thread ID %d - %d threads currently active",
pthread_self(), num);
}
/*
* This is needed for mech_krb5 -- we run as daemon, yes, but we want
* mech_krb5 to think we're root so it can get host/nodename.fqdn
* tickets for us so we can authenticate to AD as the machine account
* that we are. For more details look at the entry point in mech_krb5
* corresponding to gss_init_sec_context().
*
* As a side effect of faking our effective UID to mech_krb5 we will use
* root's default ccache (/tmp/krb5cc_0). But if that's created by
* another process then we won't have access to it: we run as daemon and
* keep PRIV_FILE_DAC_READ, which is insufficient to share the ccache
* with others. We putenv("KRB5CCNAME=/var/run/idmap/ccache") in main()
* to avoid this issue; see main().
*
* Someday we'll have gss/mech_krb5 extensions for acquiring initiator
* creds with keytabs/raw keys, and someday we'll have extensions to
* libsasl to specify creds/name to use on the initiator side, and
* someday we'll have extensions to libldap to pass those through to
* libsasl. Until then this interposer will have to do.
*
* Also, we have to tell lint to shut up: it thinks app_krb5_user_uid()
* is defined but not used.
*/
/*LINTLIBRARY*/
uid_t
app_krb5_user_uid(void)
{
return (0);
}
/*ARGSUSED*/
static void
term_handler(int sig)
{
idmapdlog(LOG_INFO, "Terminating.");
fini_dc_locator();
fini_idmapd();
_exit(0);
}
/*ARGSUSED*/
static void
usr1_handler(int sig)
{
NOTE(ARGUNUSED(sig))
print_idmapdstate();
}
static int pipe_fd = -1;
static void
daemonize_ready(void)
{
char data = '\0';
/*
* wake the parent
*/
(void) write(pipe_fd, &data, 1);
(void) close(pipe_fd);
}
static int
daemonize_start(void)
{
char data;
int status;
int devnull;
int filedes[2];
pid_t pid;
(void) sigset(SIGPIPE, SIG_IGN);
devnull = open("/dev/null", O_RDONLY);
if (devnull < 0)
return (-1);
(void) dup2(devnull, 0);
(void) dup2(2, 1); /* stderr only */
if (pipe(filedes) < 0)
return (-1);
if ((pid = fork1()) < 0)
return (-1);
if (pid != 0) {
/*
* parent
*/
(void) close(filedes[1]);
if (read(filedes[0], &data, 1) == 1) {
/* presume success */
_exit(0);
}
status = -1;
(void) wait4(pid, &status, 0, NULL);
if (WIFEXITED(status))
_exit(WEXITSTATUS(status));
else
_exit(-1);
}
/*
* child
*/
pipe_fd = filedes[1];
(void) close(filedes[0]);
(void) setsid();
(void) umask(0077);
openlog("idmap", LOG_PID, LOG_DAEMON);
return (0);
}
int
main(int argc, char **argv)
{
int c;
struct rlimit rl;
if (rwlock_init(&_idmapdstate.rwlk_cfg, USYNC_THREAD, NULL) != 0)
return (-1);
if (mutex_init(&_idmapdstate.addisc_lk, USYNC_THREAD, NULL) != 0)
return (-1);
if (cond_init(&_idmapdstate.addisc_cv, USYNC_THREAD, NULL) != 0)
return (-1);
_idmapdstate.daemon_mode = TRUE;
while ((c = getopt(argc, argv, "d")) != -1) {
switch (c) {
case 'd':
_idmapdstate.daemon_mode = FALSE;
break;
default:
(void) fprintf(stderr,
"Usage: /usr/lib/idmapd [-d]\n");
return (SMF_EXIT_ERR_CONFIG);
}
}
/* set locale and domain for internationalization */
(void) setlocale(LC_ALL, "");
(void) textdomain(TEXT_DOMAIN);
idmap_set_logger(idmapdlog);
adutils_set_logger(idmapdlog);
if (is_system_labeled() && getzoneid() != GLOBAL_ZONEID) {
idmapdlog(LOG_ERR,
"with Trusted Extensions idmapd runs only in the "
"global zone");
exit(1);
}
/*
* Raise the fd limit to max
*/
if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
idmapdlog(LOG_ERR, "getrlimit failed");
} else if (rl.rlim_cur < rl.rlim_max) {
rl.rlim_cur = rl.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
idmapdlog(LOG_ERR,
"Unable to raise RLIMIT_NOFILE to %d",
rl.rlim_cur);
}
if (_idmapdstate.daemon_mode == TRUE) {
if (daemonize_start() < 0) {
idmapdlog(LOG_ERR, "unable to daemonize");
exit(-1);
}
} else
(void) umask(0077);
idmap_init_tsd_key();
init_idmapd();
init_dc_locator();
/* signal handlers that should run only after we're initialized */
(void) sigset(SIGTERM, term_handler);
(void) sigset(SIGUSR1, usr1_handler);
(void) sigset(SIGHUP, idmap_cfg_hup_handler);
if (__init_daemon_priv(PU_RESETGROUPS|PU_CLEARLIMITSET,
DAEMON_UID, DAEMON_GID,
PRIV_PROC_AUDIT, PRIV_FILE_DAC_READ,
(char *)NULL) == -1) {
idmapdlog(LOG_ERR, "unable to drop privileges");
exit(1);
}
__fini_daemon_priv(PRIV_PROC_FORK, PRIV_PROC_EXEC, PRIV_PROC_SESSION,
PRIV_FILE_LINK_ANY, PRIV_PROC_INFO, (char *)NULL);
if (_idmapdstate.daemon_mode == TRUE)
daemonize_ready();
/* With doors RPC this just wastes this thread, oh well */
svc_run();
return (0);
}
static void
init_idmapd()
{
int error;
int connmaxrec = IDMAP_MAX_DOOR_RPC;
/* create directories as root and chown to daemon uid */
if (create_directory(IDMAP_DBDIR, DAEMON_UID, DAEMON_GID) < 0)
exit(1);
if (create_directory(IDMAP_CACHEDIR, DAEMON_UID, DAEMON_GID) < 0)
exit(1);
/*
* Set KRB5CCNAME in the environment. See app_krb5_user_uid()
* for more details. We blow away the existing one, if there is
* one.
*/
(void) unlink(IDMAP_CACHEDIR "/ccache");
(void) putenv("KRB5CCNAME=" IDMAP_CACHEDIR "/ccache");
(void) putenv("MS_INTEROP=1");
if (sysinfo(SI_HOSTNAME, _idmapdstate.hostname,
sizeof (_idmapdstate.hostname)) == -1) {
error = errno;
idmapdlog(LOG_ERR, "unable to determine hostname, error: %d",
error);
exit(1);
}
if ((error = init_mapping_system()) < 0) {
idmapdlog(LOG_ERR, "unable to initialize mapping system");
exit(error < -2 ? SMF_EXIT_ERR_CONFIG : 1);
}
/*
* This means max_threads can't be updated without restarting idmap.
*/
RDLOCK_CONFIG();
max_threads = _idmapdstate.cfg->pgcfg.max_threads;
UNLOCK_CONFIG();
(void) door_server_create(idmapd_door_thread_create);
if ((error = pthread_key_create(&create_threads_key,
idmapd_door_thread_cleanup)) != 0) {
idmapdlog(LOG_ERR, "unable to create threads key (%s)",
strerror(error));
goto errout;
}
xprt = svc_door_create(idmap_prog_1, IDMAP_PROG, IDMAP_V1, connmaxrec);
if (xprt == NULL) {
idmapdlog(LOG_ERR, "unable to create door RPC service");
goto errout;
}
if (!svc_control(xprt, SVCSET_CONNMAXREC, &connmaxrec)) {
idmapdlog(LOG_ERR, "unable to limit RPC request size");
goto errout;
}
dfd = xprt->xp_fd;
if (dfd == -1) {
idmapdlog(LOG_ERR, "unable to register door");
goto errout;
}
if ((error = __idmap_reg(dfd)) != 0) {
idmapdlog(LOG_ERR, "unable to register door (%s)",
strerror(errno));
goto errout;
}
pthread_mutex_init(&_idmapdstate.id_lock, NULL);
if ((error = allocids(_idmapdstate.new_eph_db,
8192, &_idmapdstate.next_uid,
8192, &_idmapdstate.next_gid)) != 0) {
idmapdlog(LOG_ERR, "unable to allocate ephemeral IDs (%s)",
strerror(errno));
_idmapdstate.next_uid = IDMAP_SENTINEL_PID;
_idmapdstate.limit_uid = IDMAP_SENTINEL_PID;
_idmapdstate.next_gid = IDMAP_SENTINEL_PID;
_idmapdstate.limit_gid = IDMAP_SENTINEL_PID;
} else {
_idmapdstate.limit_uid = _idmapdstate.next_uid + 8192;
_idmapdstate.limit_gid = _idmapdstate.next_gid + 8192;
}
if (DBG(CONFIG, 1))
print_idmapdstate();
return;
errout:
fini_idmapd();
exit(1);
}
static void
fini_idmapd()
{
(void) __idmap_unreg(dfd);
fini_mapping_system();
if (xprt != NULL)
svc_destroy(xprt);
}
static
const char *
get_fmri(void)
{
static char *fmri = NULL;
static char buf[60];
char *s;
membar_consumer();
s = fmri;
if (s != NULL && *s == '\0')
return (NULL);
else if (s != NULL)
return (s);
if ((s = getenv("SMF_FMRI")) == NULL || strlen(s) >= sizeof (buf))
buf[0] = '\0';
else
(void) strlcpy(buf, s, sizeof (buf));
membar_producer();
fmri = buf;
return (get_fmri());
}
/*
* Wrappers for smf_degrade/restore_instance()
*
* smf_restore_instance() is too heavy duty to be calling every time we
* have a successful AD name<->SID lookup.
*/
void
degrade_svc(int poke_discovery, const char *reason)
{
const char *fmri;
membar_consumer();
if (degraded)
return;
idmapdlog(LOG_ERR, "Degraded operation (%s).", reason);
membar_producer();
degraded = B_TRUE;
if ((fmri = get_fmri()) != NULL)
(void) smf_degrade_instance(fmri, 0);
/*
* If the config update thread is in a state where auto-discovery could
* be re-tried, then this will make it try it -- a sort of auto-refresh.
*/
if (poke_discovery)
idmap_cfg_poke_updates();
}
void
restore_svc(void)
{
const char *fmri;
membar_consumer();
if (!degraded)
return;
if ((fmri = get_fmri()) == NULL)
(void) smf_restore_instance(fmri);
membar_producer();
degraded = B_FALSE;
idmapdlog(LOG_NOTICE, "Normal operation restored");
}
/* printflike */
void
idmapdlog(int pri, const char *format, ...)
{
static time_t prev_ts;
va_list args;
char cbuf[CBUFSIZ];
time_t ts;
ts = time(NULL);
if (prev_ts != ts) {
prev_ts = ts;
/* NB: cbuf has \n */
(void) fprintf(stderr, "@ %s",
ctime_r(&ts, cbuf, sizeof (cbuf)));
}
va_start(args, format);
(void) vfprintf(stderr, format, args);
(void) fprintf(stderr, "\n");
va_end(args);
/*
* We don't want to fill up the logs with useless messages when
* we're degraded, but we still want to log.
*/
if (degraded)
pri = LOG_DEBUG;
va_start(args, format);
vsyslog(pri, format, args);
va_end(args);
}
static void
trace_str(nvlist_t *entry, char *n1, char *n2, char *str)
{
char name[IDMAP_TRACE_NAME_MAX+1]; /* Max used is only about 11 */
(void) strlcpy(name, n1, sizeof (name));
if (n2 != NULL)
(void) strlcat(name, n2, sizeof (name));
(void) nvlist_add_string(entry, name, str);
}
static void
trace_int(nvlist_t *entry, char *n1, char *n2, int64_t i)
{
char name[IDMAP_TRACE_NAME_MAX+1]; /* Max used is only about 11 */
(void) strlcpy(name, n1, sizeof (name));
if (n2 != NULL)
(void) strlcat(name, n2, sizeof (name));
(void) nvlist_add_int64(entry, name, i);
}
static void
trace_sid(nvlist_t *entry, char *n1, char *n2, idmap_sid *sid)
{
char *str;
(void) asprintf(&str, "%s-%u", sid->prefix, sid->rid);
if (str == NULL)
return;
trace_str(entry, n1, n2, str);
free(str);
}
static void
trace_id(nvlist_t *entry, char *fromto, idmap_id *id, char *name, char *domain)
{
trace_int(entry, fromto, IDMAP_TRACE_TYPE, (int64_t)id->idtype);
if (IS_ID_SID(*id)) {
if (name != NULL) {
char *str;
(void) asprintf(&str, "%s%s%s", name,
domain == NULL ? "" : "@",
domain == NULL ? "" : domain);
if (str != NULL) {
trace_str(entry, fromto, IDMAP_TRACE_NAME, str);
free(str);
}
}
if (id->idmap_id_u.sid.prefix != NULL) {
trace_sid(entry, fromto, IDMAP_TRACE_SID,
&id->idmap_id_u.sid);
}
} else if (IS_ID_POSIX(*id)) {
if (name != NULL)
trace_str(entry, fromto, IDMAP_TRACE_NAME, name);
if (id->idmap_id_u.uid != IDMAP_SENTINEL_PID) {
trace_int(entry, fromto, IDMAP_TRACE_UNIXID,
(int64_t)id->idmap_id_u.uid);
}
}
}
/*
* Record a trace event. TRACE() has already decided whether or not
* tracing is required; what we do here is collect the data and send it
* to its destination - to the trace log in the response, if
* IDMAP_REQ_FLG_TRACE is set, and to the SMF service log, if debug/mapping
* is greater than zero.
*/
int
trace(idmap_mapping *req, idmap_id_res *res, char *fmt, ...)
{
va_list va;
char *buf;
int err;
nvlist_t *entry;
assert(req != NULL);
assert(res != NULL);
err = nvlist_alloc(&entry, NV_UNIQUE_NAME, 0);
if (err != 0) {
(void) fprintf(stderr, "trace nvlist_alloc(entry): %s\n",
strerror(err));
return (0);
}
trace_id(entry, "from", &req->id1, req->id1name, req->id1domain);
trace_id(entry, "to", &res->id, req->id2name, req->id2domain);
if (IDMAP_ERROR(res->retcode)) {
trace_int(entry, IDMAP_TRACE_ERROR, NULL,
(int64_t)res->retcode);
}
va_start(va, fmt);
(void) vasprintf(&buf, fmt, va);
va_end(va);
if (buf != NULL) {
trace_str(entry, IDMAP_TRACE_MESSAGE, NULL, buf);
free(buf);
}
if (DBG(MAPPING, 1))
idmap_trace_print_1(stderr, "", entry);
if (req->flag & IDMAP_REQ_FLG_TRACE) {
/* Lazily allocate the trace list */
if (res->info.trace == NULL) {
err = nvlist_alloc(&res->info.trace, 0, 0);
if (err != 0) {
res->info.trace = NULL; /* just in case */
(void) fprintf(stderr,
"trace nvlist_alloc(trace): %s\n",
strerror(err));
nvlist_free(entry);
return (0);
}
}
(void) nvlist_add_nvlist(res->info.trace, "", entry);
/* Note that entry is copied, so we must still free our copy */
}
nvlist_free(entry);
return (0);
}
/*
* Enable libumem debugging by default on DEBUG builds.
* idmapd uses rpcgen, so we can't use #ifdef DEBUG without causing
* undesirable behavior.
*/
#ifdef IDMAPD_DEBUG
const char *
_umem_debug_init(void)
{
return ("default,verbose"); /* $UMEM_DEBUG setting */
}
const char *
_umem_logging_init(void)
{
return ("fail,contents"); /* $UMEM_LOGGING setting */
}
#endif
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2014 Nexenta Systems, Inc. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
* Copyright 2025 Bill Sommerfeld
*/
#ifndef _IDMAPD_H
#define _IDMAPD_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <rpc/rpc.h>
#include <synch.h>
#include <thread.h>
#include <libintl.h>
#include <strings.h>
#include <sqlite-sys/sqlite.h>
#include <syslog.h>
#include <inttypes.h>
#include <rpcsvc/idmap_prot.h>
#include "adutils.h"
#include "idmap_priv.h"
#include "idmap_config.h"
#include "libadutils.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CHECK_NULL(s) (s != NULL ? s : "null")
extern mutex_t _svcstate_lock; /* lock for _rpcsvcstate, _rpcsvccount */
typedef enum idmap_namemap_mode {
IDMAP_NM_NONE = 0,
IDMAP_NM_AD,
IDMAP_NM_NLDAP,
IDMAP_NM_MIXED
} idmap_namemap_mode_t;
/*
* Debugging output.
*
* There are some number of areas - configuration, mapping, discovery, et
* cetera - and for each area there is a verbosity level controlled through
* an SMF property. The default is zero, and "debug/all" provides a master
* control allowing you to turn on all debugging output with one setting.
*
* A typical debugging output sequence would look like
*
* if (DBG(CONFIG, 2)) {
* idmapdlog(LOG_DEBUG,
* "some message about config at verbosity 2");
* }
*/
enum idmapd_debug {
IDMAPD_DEBUG_ALL = 0,
IDMAPD_DEBUG_CONFIG = 1,
IDMAPD_DEBUG_MAPPING = 2,
IDMAPD_DEBUG_DISC = 3,
IDMAPD_DEBUG_DNS = 4,
IDMAPD_DEBUG_LDAP = 5,
IDMAPD_DEBUG_MAX = 5
};
#define DBG(type, lev) \
(_idmapdstate.debug[IDMAPD_DEBUG_##type] >= (lev) || \
_idmapdstate.debug[IDMAPD_DEBUG_ALL] >= (lev))
/*
* Global state of idmapd daemon.
*/
typedef struct idmapd_state {
rwlock_t rwlk_cfg; /* config lock */
idmap_cfg_t *cfg; /* config */
bool_t daemon_mode;
char hostname[MAX_NAME_LEN]; /* my hostname */
pthread_mutex_t id_lock; /* id allocator lock */
uid_t next_uid;
gid_t next_gid;
uid_t limit_uid;
gid_t limit_gid;
int new_eph_db; /* was the ephem ID db [re-]created? */
int num_gcs;
adutils_ad_t **gcs;
int num_dcs;
adutils_ad_t **dcs;
mutex_t addisc_lk;
cond_t addisc_cv;
int addisc_st;
int debug[IDMAPD_DEBUG_MAX+1];
} idmapd_state_t;
extern idmapd_state_t _idmapdstate;
#define ADDISC_ST_REQUESTED 1
#define ADDISC_ST_RUNNING 2
#define RDLOCK_CONFIG() \
(void) rw_rdlock(&_idmapdstate.rwlk_cfg);
#define WRLOCK_CONFIG() \
(void) rw_wrlock(&_idmapdstate.rwlk_cfg);
#define UNLOCK_CONFIG() \
(void) rw_unlock(&_idmapdstate.rwlk_cfg);
typedef struct hashentry {
uint_t key;
uint_t next;
} hashentry_t;
typedef struct lookup_state {
bool_t sid2pid_done;
bool_t pid2sid_done;
int ad_nqueries;
int nldap_nqueries;
bool_t eph_map_unres_sids;
int directory_based_mapping; /* enum */
uint_t id_cache_timeout;
uint_t name_cache_timeout;
uint_t curpos;
hashentry_t *sid_history;
uint_t sid_history_size;
idmap_mapping_batch *batch;
idmap_ids_res *result;
idmap_namemap_mode_t nm_siduid;
idmap_namemap_mode_t nm_sidgid;
char *ad_unixuser_attr;
char *ad_unixgroup_attr;
char *nldap_winname_attr;
char *defdom;
sqlite *cache;
sqlite *db;
} lookup_state_t;
#define NLDAP_OR_MIXED(nm) \
((nm) == IDMAP_NM_NLDAP || (nm) == IDMAP_NM_MIXED)
#define AD_OR_MIXED(nm) \
((nm) == IDMAP_NM_AD || (nm) == IDMAP_NM_MIXED)
#define PID_UID_OR_UNKNOWN(pidtype) \
((pidtype) == IDMAP_UID || (pidtype) == IDMAP_POSIXID)
#define PID_GID_OR_UNKNOWN(pidtype) \
((pidtype) == IDMAP_GID || (pidtype) == IDMAP_POSIXID)
#define NLDAP_OR_MIXED_MODE(pidtype, ls) \
(NLDAP_MODE(pidtype, ls) || MIXED_MODE(pidtype, ls))
#define AD_OR_MIXED_MODE(pidtype, ls)\
(AD_MODE(pidtype, ls) || MIXED_MODE(pidtype, ls))
#define NLDAP_MODE(pidtype, ls) \
((PID_UID_OR_UNKNOWN(pidtype) && (ls)->nm_siduid == IDMAP_NM_NLDAP) || \
(PID_GID_OR_UNKNOWN(pidtype) && (ls)->nm_sidgid == IDMAP_NM_NLDAP))
#define AD_MODE(pidtype, ls) \
((PID_UID_OR_UNKNOWN(pidtype) && (ls)->nm_siduid == IDMAP_NM_AD) || \
(PID_GID_OR_UNKNOWN(pidtype) && (ls)->nm_sidgid == IDMAP_NM_AD))
#define MIXED_MODE(pidtype, ls) \
((PID_UID_OR_UNKNOWN(pidtype) && (ls)->nm_siduid == IDMAP_NM_MIXED) || \
(PID_GID_OR_UNKNOWN(pidtype) && (ls)->nm_sidgid == IDMAP_NM_MIXED))
typedef struct list_cb_data {
void *result;
uint64_t next;
uint64_t len;
uint64_t limit;
int flag;
} list_cb_data_t;
typedef struct msg_table {
idmap_retcode retcode;
const char *msg;
} msg_table_t;
/*
* Data structure to store well-known SIDs and
* associated mappings (if any)
*/
typedef struct wksids_table {
const char *sidprefix;
uint32_t rid;
const char *domain;
const char *winname;
int is_wuser;
posix_id_t pid;
int is_user;
int direction;
} wksids_table_t;
#define IDMAPD_SEARCH_TIMEOUT 3 /* seconds */
#define IDMAPD_LDAP_OPEN_TIMEOUT 1 /* secs; initial, w/ exp backoff */
/*
* The following flags are used by idmapd while processing a
* given mapping request. Note that idmapd uses multiple passes to
* process the request and the flags are used to pass information
* about the state of the request between these passes.
*/
/* Initial state. Done. Reset all flags. Remaining passes can be skipped */
#define _IDMAP_F_DONE 0x00000000
/* Set when subsequent passes are required */
#define _IDMAP_F_NOTDONE 0x00000001
/* Don't update name_cache. (e.g. set when winname,SID found in name_cache) */
#define _IDMAP_F_DONT_UPDATE_NAMECACHE 0x00000002
/* Batch this request for AD lookup */
#define _IDMAP_F_LOOKUP_AD 0x00000004
/* Batch this request for nldap directory lookup */
#define _IDMAP_F_LOOKUP_NLDAP 0x00000008
/*
* Expired ephemeral mapping found in cache when processing sid2uid request.
* Use it if the given SID cannot be mapped by name
*/
#define _IDMAP_F_EXP_EPH_UID 0x00000010
/* Same as above. Used for sid2gid request */
#define _IDMAP_F_EXP_EPH_GID 0x00000020
/* This request is not valid for the current forest */
#define _IDMAP_F_LOOKUP_OTHER_AD 0x00000040
/*
* Check if we are done. If so, subsequent passes can be skipped
* when processing a given mapping request.
*/
#define ARE_WE_DONE(f) ((f & _IDMAP_F_NOTDONE) == 0)
#define SIZE_INCR 5
#define MAX_TRIES 5
#define IDMAP_DBDIR "/var/idmap"
#define IDMAP_CACHEDIR "/var/run/idmap"
#define IDMAP_DBNAME IDMAP_DBDIR "/idmap.db"
#define IDMAP_CACHENAME IDMAP_CACHEDIR "/cache.db"
#define IS_ID_NONE(id) \
((id).idtype == IDMAP_NONE)
#define IS_ID_SID(id) \
((id).idtype == IDMAP_SID || \
(id).idtype == IDMAP_USID || \
(id).idtype == IDMAP_GSID) \
#define IS_ID_UID(id) \
((id).idtype == IDMAP_UID)
#define IS_ID_GID(id) \
((id).idtype == IDMAP_GID)
#define IS_ID_POSIX(id) \
((id).idtype == IDMAP_UID || \
(id).idtype == IDMAP_GID || \
(id).idtype == IDMAP_POSIXID) \
/*
* Local RID ranges
*/
#define LOCALRID_UID_MIN 1000U
#define LOCALRID_UID_MAX ((uint32_t)INT32_MAX)
#define LOCALRID_GID_MIN (((uint32_t)INT32_MAX) + 1)
#define LOCALRID_GID_MAX UINT32_MAX
/*
* Tracing.
*
* The tracing mechanism is intended to help the administrator understand
* why their mapping configuration is doing what it is. Each interesting
* decision point during the mapping process calls TRACE() with the current
* request and response and a printf-style message. The message, plus
* data from the request and the response, is logged to the service log
* (if debug/mapping is greater than zero) or reported to the caller
* (if IDMAP_REQ_FLG_TRACE was set in the request. The primary consumer
* is the "-V" option to "idmap show".
*
* TRACING(req) says whether tracing is appropriate for the request, and
* is used to determine and record whether any request in a batch requested
* tracing, to control whether later code loops over the batch to do tracing
* for any of the requests.
*
* TRACE(req, res, fmt, ...) generates a trace entry if appropriate.
*/
#define TRACING(req) \
(DBG(MAPPING, 1) || \
((req)->flag & IDMAP_REQ_FLG_TRACE) != 0)
#define TRACE(req, res, ...) \
((void)(TRACING(req) && trace(req, res, __VA_ARGS__)))
extern int trace(idmap_mapping *req, idmap_id_res *res, char *fmt, ...);
typedef idmap_retcode (*update_list_res_cb)(void *, const char **, uint64_t);
typedef int (*list_svc_cb)(void *, int, char **, char **);
extern void idmap_prog_1(struct svc_req *, register SVCXPRT *);
extern void idmapdlog(int, const char *, ...);
extern int init_mapping_system(void);
extern void fini_mapping_system(void);
extern void print_idmapdstate(void);
extern int create_directory(const char *, uid_t, gid_t);
extern int load_config(void);
extern void reload_gcs(void);
extern void reload_dcs(void);
extern void idmap_init_tsd_key(void);
extern void degrade_svc(int, const char *);
extern void restore_svc(void);
extern void notify_dc_changed(void);
extern int init_dbs(void);
extern void fini_dbs(void);
extern idmap_retcode get_db_handle(sqlite **);
extern idmap_retcode get_cache_handle(sqlite **);
extern void kill_db_handle(sqlite *);
extern void kill_cache_handle(sqlite *);
extern idmap_retcode sql_exec_no_cb(sqlite *, const char *, char *);
extern idmap_retcode add_namerule(sqlite *, idmap_namerule *);
extern idmap_retcode rm_namerule(sqlite *, idmap_namerule *);
extern idmap_retcode flush_namerules(sqlite *);
extern char *tolower_u8(const char *);
extern idmap_retcode gen_sql_expr_from_rule(idmap_namerule *, char **);
extern idmap_retcode validate_list_cb_data(list_cb_data_t *, int,
char **, int, uchar_t **, size_t);
extern idmap_retcode process_list_svc_sql(sqlite *, const char *, char *,
uint64_t, int, list_svc_cb, void *);
extern idmap_retcode sid2pid_first_pass(lookup_state_t *,
idmap_mapping *, idmap_id_res *);
extern idmap_retcode sid2pid_second_pass(lookup_state_t *,
idmap_mapping *, idmap_id_res *);
extern idmap_retcode pid2sid_first_pass(lookup_state_t *,
idmap_mapping *, idmap_id_res *, int);
extern idmap_retcode pid2sid_second_pass(lookup_state_t *,
idmap_mapping *, idmap_id_res *, int);
extern idmap_retcode update_cache_sid2pid(lookup_state_t *,
idmap_mapping *, idmap_id_res *);
extern idmap_retcode update_cache_pid2sid(lookup_state_t *,
idmap_mapping *, idmap_id_res *);
extern idmap_retcode get_u2w_mapping(sqlite *, sqlite *, idmap_mapping *,
idmap_mapping *, int);
extern idmap_retcode get_w2u_mapping(sqlite *, sqlite *, idmap_mapping *,
idmap_mapping *);
extern idmap_retcode load_cfg_in_state(lookup_state_t *);
extern void cleanup_lookup_state(lookup_state_t *);
extern idmap_retcode ad_lookup_batch(lookup_state_t *,
idmap_mapping_batch *, idmap_ids_res *);
extern idmap_retcode lookup_name2sid(sqlite *, const char *, const char *,
int, char **, char **, char **,
idmap_rid_t *, idmap_id_type *,
idmap_mapping *, int);
extern idmap_retcode lookup_wksids_name2sid(const char *, const char *,
char **, char **, char **, idmap_rid_t *,
idmap_id_type *);
extern idmap_retcode idmap_cache_flush(idmap_flush_op);
extern const wksids_table_t *find_wksid_by_pid(posix_id_t pid, int is_user);
extern const wksids_table_t *find_wksid_by_sid(const char *sid, int rid,
idmap_id_type type);
extern const wksids_table_t *find_wksid_by_name(const char *name,
const char *domain, idmap_id_type type);
extern const wksids_table_t *find_wk_by_sid(char *sid);
#ifdef __cplusplus
}
#endif
#endif /* _IDMAPD_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Initialization routines
*/
#include "idmapd.h"
#include <signal.h>
#include <thread.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <rpcsvc/daemon_utils.h>
int
init_mapping_system(void)
{
int rc = 0;
if ((rc = load_config()) < 0)
return (rc);
(void) setegid(DAEMON_GID);
(void) seteuid(DAEMON_UID);
if (init_dbs() < 0) {
rc = -1;
fini_mapping_system();
}
(void) seteuid(0);
(void) setegid(0);
return (rc);
}
void
fini_mapping_system(void)
{
fini_dbs();
}
int
load_config(void)
{
int rc;
if ((_idmapdstate.cfg = idmap_cfg_init()) == NULL) {
degrade_svc(0, "failed to initialize config");
return (-1);
}
rc = idmap_cfg_upgrade(_idmapdstate.cfg);
if (rc != 0) {
degrade_svc(0, "fatal error while upgrading configuration");
return (rc);
}
rc = idmap_cfg_load(_idmapdstate.cfg, 0);
if (rc < -1) {
/* Total failure */
degrade_svc(0, "fatal error while loading configuration");
return (rc);
}
if (rc != 0)
/* Partial failure */
idmapdlog(LOG_ERR, "Various errors occurred while loading "
"the configuration; check the logs");
if ((rc = idmap_cfg_start_updates()) < 0) {
/* Total failure */
degrade_svc(0, "could not start config updater");
return (rc);
}
if (DBG(CONFIG, 1))
idmapdlog(LOG_DEBUG, "Initial configuration loaded");
return (0);
}
void
reload_gcs(void)
{
int i, j;
adutils_ad_t **new_gcs;
adutils_ad_t **old_gcs = _idmapdstate.gcs;
int new_num_gcs;
int old_num_gcs = _idmapdstate.num_gcs;
idmap_pg_config_t *pgcfg = &_idmapdstate.cfg->pgcfg;
idmap_trustedforest_t *trustfor = pgcfg->trusted_forests;
int num_trustfor = pgcfg->num_trusted_forests;
ad_disc_domainsinforest_t *domain_in_forest;
if (pgcfg->use_ads == B_FALSE ||
pgcfg->domain_name == NULL) {
/*
* ADS disabled, or no domain name specified.
* Not using adutils. (but still can use lsa)
*/
new_gcs = NULL;
new_num_gcs = 0;
goto out;
}
if (pgcfg->global_catalog == NULL ||
pgcfg->global_catalog[0].host[0] == '\0') {
/*
* No GCs. Continue to use the previous AD config in case
* that's still good but auto-discovery had a transient failure.
* If that stops working we'll go into degraded mode anyways
* when it does.
*/
idmapdlog(LOG_INFO,
"Global Catalog servers not configured/discoverable");
return;
}
new_num_gcs = 1 + num_trustfor;
new_gcs = calloc(new_num_gcs, sizeof (adutils_ad_t *));
if (new_gcs == NULL) {
degrade_svc(0, "could not allocate AD context array "
"(out of memory)");
return;
}
if (adutils_ad_alloc(&new_gcs[0], NULL, ADUTILS_AD_GLOBAL_CATALOG) !=
ADUTILS_SUCCESS) {
free(new_gcs);
degrade_svc(0, "could not initialize AD context "
"(out of memory)");
return;
}
for (i = 0; pgcfg->global_catalog[i].host[0] != '\0'; i++) {
if (idmap_add_ds(new_gcs[0],
pgcfg->global_catalog[i].host,
pgcfg->global_catalog[i].port) != 0) {
adutils_ad_free(&new_gcs[0]);
free(new_gcs);
degrade_svc(0, "could not set AD hosts "
"(out of memory)");
return;
}
}
if (pgcfg->domains_in_forest != NULL) {
for (i = 0; pgcfg->domains_in_forest[i].domain[0] != '\0';
i++) {
if (adutils_add_domain(new_gcs[0],
pgcfg->domains_in_forest[i].domain,
pgcfg->domains_in_forest[i].sid) != 0) {
adutils_ad_free(&new_gcs[0]);
free(new_gcs);
degrade_svc(0, "could not set AD domains "
"(out of memory)");
return;
}
}
}
for (i = 0; i < num_trustfor; i++) {
if (adutils_ad_alloc(&new_gcs[i + 1], NULL,
ADUTILS_AD_GLOBAL_CATALOG) != ADUTILS_SUCCESS) {
degrade_svc(0, "could not initialize trusted AD "
"context (out of memory)");
new_num_gcs = i + 1;
goto out;
}
for (j = 0; trustfor[i].global_catalog[j].host[0] != '\0';
j++) {
if (idmap_add_ds(new_gcs[i + 1],
trustfor[i].global_catalog[j].host,
trustfor[i].global_catalog[j].port) != 0) {
adutils_ad_free(&new_gcs[i + 1]);
degrade_svc(0, "could not set trusted "
"AD hosts (out of memory)");
new_num_gcs = i + 1;
goto out;
}
}
for (j = 0; trustfor[i].domains_in_forest[j].domain[0] != '\0';
j++) {
domain_in_forest = &trustfor[i].domains_in_forest[j];
/* Only add domains which are marked */
if (domain_in_forest->trusted) {
if (adutils_add_domain(new_gcs[i + 1],
domain_in_forest->domain,
domain_in_forest->sid) != 0) {
adutils_ad_free(&new_gcs[i + 1]);
degrade_svc(0, "could not set trusted "
"AD domains (out of memory)");
new_num_gcs = i + 1;
goto out;
}
}
}
}
out:
_idmapdstate.gcs = new_gcs;
_idmapdstate.num_gcs = new_num_gcs;
if (old_gcs != NULL) {
for (i = 0; i < old_num_gcs; i++)
adutils_ad_free(&old_gcs[i]);
free(old_gcs);
}
}
/*
* NEEDSWORK: This should load entries for domain servers for all known
* domains - the joined domain, other domains in the forest, and trusted
* domains in other forests. However, we don't yet discover any DCs other
* than the DCs for the joined domain.
*/
void
reload_dcs(void)
{
int i;
adutils_ad_t **new_dcs;
adutils_ad_t **old_dcs = _idmapdstate.dcs;
int new_num_dcs;
int old_num_dcs = _idmapdstate.num_dcs;
idmap_pg_config_t *pgcfg = &_idmapdstate.cfg->pgcfg;
if (pgcfg->use_ads == B_FALSE ||
pgcfg->domain_name == NULL) {
/*
* ADS disabled, or no domain name specified.
* Not using adutils. (but still can use lsa)
*/
new_dcs = NULL;
new_num_dcs = 0;
goto out;
}
if (pgcfg->domain_controller == NULL ||
pgcfg->domain_controller[0].host[0] == '\0') {
/*
* No DCs. Continue to use the previous AD config in case
* that's still good but auto-discovery had a transient failure.
* If that stops working we'll go into degraded mode anyways
* when it does.
*/
idmapdlog(LOG_INFO,
"Domain controller servers not configured/discoverable");
return;
}
new_num_dcs = 1;
new_dcs = calloc(new_num_dcs, sizeof (adutils_ad_t *));
if (new_dcs == NULL)
goto nomem;
if (adutils_ad_alloc(&new_dcs[0], pgcfg->domain_name,
ADUTILS_AD_DATA) != ADUTILS_SUCCESS)
goto nomem;
for (i = 0; pgcfg->domain_controller[i].host[0] != '\0'; i++) {
if (idmap_add_ds(new_dcs[0],
pgcfg->domain_controller[i].host,
pgcfg->domain_controller[i].port) != 0)
goto nomem;
}
/*
* NEEDSWORK: All we need here is to add the domain and SID for
* this DC to the list of domains supported by this entry. Isn't
* there an easier way to find the SID than to walk through the list
* of all of the domains in the forest?
*/
ad_disc_domainsinforest_t *dif = pgcfg->domains_in_forest;
if (dif != NULL) {
for (; dif->domain[0] != '\0'; dif++) {
if (domain_eq(pgcfg->domain_name, dif->domain)) {
if (adutils_add_domain(new_dcs[0],
dif->domain, dif->sid) != 0)
goto nomem;
break;
}
}
}
out:
_idmapdstate.dcs = new_dcs;
_idmapdstate.num_dcs = new_num_dcs;
if (old_dcs != NULL) {
for (i = 0; i < old_num_dcs; i++)
adutils_ad_free(&old_dcs[i]);
free(old_dcs);
}
return;
nomem:
degrade_svc(0, "out of memory");
if (new_dcs != NULL) {
if (new_dcs[0] != NULL)
adutils_ad_free(&new_dcs[0]);
free(new_dcs);
}
}
void
print_idmapdstate(void)
{
int i, j;
idmap_pg_config_t *pgcfg;
idmap_trustedforest_t *tf;
RDLOCK_CONFIG();
if (_idmapdstate.cfg == NULL) {
idmapdlog(LOG_INFO, "Null configuration");
UNLOCK_CONFIG();
return;
}
pgcfg = &_idmapdstate.cfg->pgcfg;
idmapdlog(LOG_DEBUG, "list_size_limit=%llu", pgcfg->list_size_limit);
idmapdlog(LOG_DEBUG, "max_threads=%llu", pgcfg->max_threads);
idmapdlog(LOG_DEBUG, "default_domain=%s",
CHECK_NULL(pgcfg->default_domain));
idmapdlog(LOG_DEBUG, "domain_name=%s", CHECK_NULL(pgcfg->domain_name));
idmapdlog(LOG_DEBUG, "machine_sid=%s", CHECK_NULL(pgcfg->machine_sid));
if (pgcfg->domain_controller == NULL ||
pgcfg->domain_controller[0].host[0] == '\0') {
idmapdlog(LOG_DEBUG, "No domain controllers known");
} else {
for (i = 0; pgcfg->domain_controller[i].host[0] != '\0'; i++)
idmapdlog(LOG_DEBUG, "domain_controller=%s port=%d",
pgcfg->domain_controller[i].host,
pgcfg->domain_controller[i].port);
}
idmapdlog(LOG_DEBUG, "forest_name=%s", CHECK_NULL(pgcfg->forest_name));
idmapdlog(LOG_DEBUG, "site_name=%s", CHECK_NULL(pgcfg->site_name));
if (pgcfg->global_catalog == NULL ||
pgcfg->global_catalog[0].host[0] == '\0') {
idmapdlog(LOG_DEBUG, "No global catalog servers known");
} else {
for (i = 0; pgcfg->global_catalog[i].host[0] != '\0'; i++)
idmapdlog(LOG_DEBUG, "global_catalog=%s port=%d",
pgcfg->global_catalog[i].host,
pgcfg->global_catalog[i].port);
}
if (pgcfg->domains_in_forest == NULL ||
pgcfg->domains_in_forest[0].domain[0] == '\0') {
idmapdlog(LOG_DEBUG, "No domains in forest %s known",
CHECK_NULL(pgcfg->forest_name));
} else {
for (i = 0; pgcfg->domains_in_forest[i].domain[0] != '\0'; i++)
idmapdlog(LOG_DEBUG, "domains in forest %s = %s",
CHECK_NULL(pgcfg->forest_name),
pgcfg->domains_in_forest[i].domain);
}
if (pgcfg->trusted_domains == NULL ||
pgcfg->trusted_domains[0].domain[0] == '\0') {
idmapdlog(LOG_DEBUG, "No trusted domains known");
} else {
for (i = 0; pgcfg->trusted_domains[i].domain[0] != '\0'; i++)
idmapdlog(LOG_DEBUG, "trusted domain = %s",
pgcfg->trusted_domains[i].domain);
}
for (i = 0; i < pgcfg->num_trusted_forests; i++) {
tf = &pgcfg->trusted_forests[i];
for (j = 0; tf->global_catalog[j].host[0] != '\0'; j++)
idmapdlog(LOG_DEBUG,
"trusted forest %s global_catalog=%s port=%d",
tf->forest_name,
tf->global_catalog[j].host,
tf->global_catalog[j].port);
for (j = 0; tf->domains_in_forest[j].domain[0] != '\0'; j++) {
if (tf->domains_in_forest[j].trusted) {
idmapdlog(LOG_DEBUG,
"trusted forest %s domain=%s",
tf->forest_name,
tf->domains_in_forest[j].domain);
}
}
}
idmapdlog(LOG_DEBUG, "directory_based_mapping=%s",
enum_lookup(pgcfg->directory_based_mapping, directory_mapping_map));
idmapdlog(LOG_DEBUG, "ad_unixuser_attr=%s",
CHECK_NULL(pgcfg->ad_unixuser_attr));
idmapdlog(LOG_DEBUG, "ad_unixgroup_attr=%s",
CHECK_NULL(pgcfg->ad_unixgroup_attr));
idmapdlog(LOG_DEBUG, "nldap_winname_attr=%s",
CHECK_NULL(pgcfg->nldap_winname_attr));
UNLOCK_CONFIG();
}
int
create_directory(const char *path, uid_t uid, gid_t gid)
{
int rc;
if ((rc = mkdir(path, 0700)) < 0 && errno != EEXIST) {
idmapdlog(LOG_ERR, "Error creating directory %s (%s)",
path, strerror(errno));
return (-1);
}
if (lchown(path, uid, gid) < 0) {
idmapdlog(LOG_ERR, "Error creating directory %s (%s)",
path, strerror(errno));
if (rc == 0)
(void) rmdir(path);
return (-1);
}
return (0);
}
/*
* This file and its contents are supplied under the terms of the
* Common Development and Distribution License ("CDDL"), version 1.0.
* You may only use this file in accordance with the terms of version
* 1.0 of the CDDL.
*
* A full copy of the text of the CDDL should have accompanied this
* source. A copy of the CDDL is also available via the Internet at
* http://www.illumos.org/license/CDDL.
*/
/*
* Copyright 2020 Nexenta by DDN, Inc. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/note.h>
#include <synch.h>
#include <thread.h>
#include <ads/dsgetdc.h>
#include "idmapd.h"
#include "libadutils.h"
#include "locate_plugin.h"
/* osconf.h - sigh */
#define KRB5_DEFAULT_PORT 88
#define DEFAULT_KADM5_PORT 749
#define DEFAULT_KPASSWD_PORT 464
/*
* This is an "override plugin" used by libkrb5. See:
* lib/gss_mechs/mech_krb5/krb5/os/locate_kdc.c
*
* The interface is based on:
* http://web.mit.edu/~kerberos/krb5-1.12/doc/plugindev/locate.html
*/
/*
* Called by krb5int_locate_server / override_locate_server
*/
krb5_error_code
_krb5_override_service_locator(
void *arg0,
enum locate_service_type svc,
const char *realm,
int socktype,
int family,
int (*cbfunc)(void *, int, struct sockaddr *),
void *cbdata)
{
_NOTE(ARGUNUSED(arg0))
idmap_pg_config_t *pgcfg;
ad_disc_ds_t *ds;
int rc = KRB5_PLUGIN_NO_HANDLE;
short port;
/*
* Is this a service we want to override?
*/
switch (svc) {
case locate_service_kdc:
case locate_service_master_kdc:
port = htons(KRB5_DEFAULT_PORT);
break;
case locate_service_kadmin:
port = htons(DEFAULT_KADM5_PORT);
break;
case locate_service_kpasswd:
port = htons(DEFAULT_KPASSWD_PORT);
break;
case locate_service_krb524:
default:
return (rc);
}
RDLOCK_CONFIG();
pgcfg = &_idmapdstate.cfg->pgcfg;
/*
* Is this a realm we want to override?
*/
if (pgcfg->domain_name == NULL)
goto out;
if (0 != strcasecmp(realm, pgcfg->domain_name))
goto out;
/*
* Yes, this is our domain. Have a DC?
*/
if ((ds = pgcfg->domain_controller) == NULL) {
rc = KRB5_REALM_CANT_RESOLVE;
goto out;
}
if ((ds->flags & DS_KDC_FLAG) == 0) {
idmapdlog(LOG_WARNING, "Domain Controller is not a KDC: "
"Kerberos auth may be slow");
goto out;
}
switch (family) {
case AF_UNSPEC:
break; /* OK */
case AF_INET:
case AF_INET6:
if (family == ds->addr.ss_family)
break; /* OK */
/* else fallthrough */
default:
rc = KRB5_ERR_NO_SERVICE;
goto out;
}
/*
* Provide the service address we have.
*/
switch (ds->addr.ss_family) {
case AF_INET: {
struct sockaddr_in sin;
struct sockaddr_in *dsa = (void *)&ds->addr;
(void) memset(&sin, 0, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = port;
(void) memcpy(&sin.sin_addr, &dsa->sin_addr,
sizeof (sin.sin_addr));
rc = cbfunc(cbdata, socktype, (struct sockaddr *)&sin);
break;
}
case AF_INET6: {
struct sockaddr_in6 sin6;
struct sockaddr_in6 *dsa6 = (void *)&ds->addr;
(void) memset(&sin6, 0, sizeof (sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = port;
(void) memcpy(&sin6.sin6_addr, &dsa6->sin6_addr,
sizeof (sin6.sin6_addr));
rc = cbfunc(cbdata, socktype, (struct sockaddr *)&sin6);
break;
}
default:
rc = KRB5_ERR_NO_SERVICE;
goto out;
}
/* rc from cbfunc is special. */
if (rc)
rc = ENOMEM;
out:
UNLOCK_CONFIG();
return (rc);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2011 Nexenta Systems, Inc. All rights reserved.
*/
/*
* native LDAP related utility routines
*/
#include "idmapd.h"
#include "idmap_priv.h"
#include "ns_sldap.h"
#include "nldaputils.h"
#include <assert.h>
/*
* The following are format strings used to construct LDAP search filters
* when looking up Native LDAP directory service. The _F_XXX_SSD format
* is used by the libsldap API if a corresponding SSD is defined in
* Native LDAP configuration. The SSD contains a string that replaces
* the first %s in _F_XXX_SSD. If no SSD is defined then the regular
* _F_XXX format is used.
*
* Note that '\\' needs to be represented as "\\5c" in LDAP filters.
*/
/* Native LDAP lookup using UNIX username */
#define _F_GETPWNAM "(&(objectClass=posixAccount)(uid=%s))"
#define _F_GETPWNAM_SSD "(&(%%s)(uid=%s))"
/*
* Native LDAP user lookup using names of well-known SIDs
* Note the use of 1$, 2$ in the format string which basically
* allows snprintf to re-use its first two arguments.
*/
#define _F_GETPWWNAMWK \
"(&(objectClass=posixAccount)(|(%s=%s)(%1$s=BUILTIN\\5c%2$s)))"
#define _F_GETPWWNAMWK_SSD "(&(%%s)(|(%s=%s)(%1$s=BUILTIN\\5c%2$s)))"
/* Native LDAP user lookup using winname@windomain OR windomain\winname */
#define _F_GETPWWNAMDOM \
"(&(objectClass=posixAccount)(|(%s=%s@%s)(%1$s=%3$s\\5c%2$s)))"
#define _F_GETPWWNAMDOM_SSD "(&(%%s)(|(%s=%s@%s)(%1$s=%3$s\\5c%2$s)))"
/* Native LDAP lookup using UID */
#define _F_GETPWUID "(&(objectClass=posixAccount)(uidNumber=%u))"
#define _F_GETPWUID_SSD "(&(%%s)(uidNumber=%u))"
/* Native LDAP lookup using UNIX groupname */
#define _F_GETGRNAM "(&(objectClass=posixGroup)(cn=%s))"
#define _F_GETGRNAM_SSD "(&(%%s)(cn=%s))"
/* Native LDAP group lookup using names of well-known SIDs */
#define _F_GETGRWNAMWK \
"(&(objectClass=posixGroup)(|(%s=%s)(%1$s=BUILTIN\\5c%2$s)))"
#define _F_GETGRWNAMWK_SSD "(&(%%s)(|(%s=%s)(%1$s=BUILTIN\\5c%2$s)))"
/* Native LDAP group lookup using winname@windomain OR windomain\winname */
#define _F_GETGRWNAMDOM \
"(&(objectClass=posixGroup)(|(%s=%s@%s)(%1$s=%3$s\\5c%2$s)))"
#define _F_GETGRWNAMDOM_SSD "(&(%%s)(|(%s=%s@%s)(%1$s=%3$s\\5c%2$s)))"
/* Native LDAP lookup using GID */
#define _F_GETGRGID "(&(objectClass=posixGroup)(gidNumber=%u))"
#define _F_GETGRGID_SSD "(&(%%s)(gidNumber=%u))"
/* Native LDAP attribute names */
#define UID "uid"
#define CN "cn"
#define UIDNUMBER "uidnumber"
#define GIDNUMBER "gidnumber"
#define DN "dn"
#define IS_NLDAP_RC_FATAL(x) ((x == NS_LDAP_MEMORY) ? 1 : 0)
typedef struct idmap_nldap_q {
char **winname;
char **windomain;
char **unixname;
uid_t *pid;
char **dn;
char **attr;
char **value;
int is_user;
idmap_retcode *rc;
int lrc;
ns_ldap_result_t *result;
ns_ldap_error_t *errorp;
char *filter;
char *udata;
} idmap_nldap_q_t;
typedef struct idmap_nldap_query_state {
const char *nldap_winname_attr;
const char *defdom;
int nqueries;
int qid;
int flag;
ns_ldap_list_batch_t *batch;
idmap_nldap_q_t queries[1];
} idmap_nldap_query_state_t;
/*
* This routine has been copied from lib/nsswitch/ldap/common/ldap_utils.c
* after removing the debug statements.
*
* This is a generic filter callback function for merging the filter
* from service search descriptor with an existing search filter. This
* routine expects userdata to contain a format string with a single %s
* in it, and will use the format string with sprintf() to insert the
* SSD filter.
*
* This routine and userdata are passed to the __ns_ldap_list_batch_add()
* API.
*
* Consider an example that uses __ns_ldap_list_batch_add() to lookup
* native LDAP directory using a given userid 'xy12345'. In this
* example the userdata will contain the filter "(&(%s)(cn=xy1234))".
* If a SSD is defined to replace the rfc2307bis specified filter
* i.e. (objectClass=posixAccount) by a site-specific filter
* say (department=sds) then this routine when called will produce
* "(&(department=sds)(uid=xy1234))" as the real search filter.
*/
static
int
merge_SSD_filter(const ns_ldap_search_desc_t *desc,
char **realfilter, const void *userdata)
{
int len;
char *checker;
if (realfilter == NULL)
return (NS_LDAP_INVALID_PARAM);
*realfilter = NULL;
if (desc == NULL || desc->filter == NULL || userdata == NULL)
return (NS_LDAP_INVALID_PARAM);
/* Parameter check. We only want one %s here, otherwise bail. */
len = 0; /* Reuse 'len' as "Number of %s hits"... */
checker = (char *)userdata;
do {
checker = strchr(checker, '%');
if (checker != NULL) {
if (len > 0 || *(checker + 1) != 's')
return (NS_LDAP_INVALID_PARAM);
len++; /* Got our %s. */
checker += 2;
} else if (len != 1)
return (NS_LDAP_INVALID_PARAM);
} while (checker != NULL);
len = strlen(userdata) + strlen(desc->filter) + 1;
*realfilter = (char *)malloc(len);
if (*realfilter == NULL)
return (NS_LDAP_MEMORY);
(void) sprintf(*realfilter, (char *)userdata, desc->filter);
return (NS_LDAP_SUCCESS);
}
static
char
hex_char(int n)
{
return ("0123456789abcdef"[n & 0xf]);
}
/*
* If the input string contains special characters that needs to be
* escaped before the string can be used in a LDAP filter then this
* function will return a new sanitized string. Otherwise this function
* returns the input string (This saves us un-necessary memory allocations
* especially when processing a batch of requests). The caller must free
* the returned string if it isn't the input string.
*
* The escape mechanism for LDAP filter is described in RFC2254 basically
* it's \hh where hh are the two hexadecimal digits representing the ASCII
* value of the encoded character (case of hh is not significant).
* Example: * -> \2a, ( -> \28, ) -> \29, \ -> \5c,
*
* outstring = sanitize_for_ldap_filter(instring);
* if (outstring == NULL)
* Out of memory
* else
* Use outstring
* if (outstring != instring)
* free(outstring);
* done
*/
char *
sanitize_for_ldap_filter(const char *str)
{
const char *p;
char *q, *s_str = NULL;
int n;
/* Get a count of special characters */
for (p = str, n = 0; *p; p++)
if (*p == '*' || *p == '(' || *p == ')' ||
*p == '\\' || *p == '%')
n++;
/* If count is zero then no need to sanitize */
if (n == 0)
return ((char *)str);
/* Create output buffer that will contain the sanitized value */
s_str = calloc(1, n * 2 + strlen(str) + 1);
if (s_str == NULL)
return (NULL);
for (p = str, q = s_str; *p; p++) {
if (*p == '*' || *p == '(' || *p == ')' ||
*p == '\\' || *p == '%') {
*q++ = '\\';
*q++ = hex_char(*p >> 4);
*q++ = hex_char(*p & 0xf);
} else
*q++ = *p;
}
return (s_str);
}
/*
* Map libsldap status to idmap status
*/
static
idmap_retcode
nldaprc2retcode(int rc)
{
switch (rc) {
case NS_LDAP_SUCCESS:
case NS_LDAP_SUCCESS_WITH_INFO:
return (IDMAP_SUCCESS);
case NS_LDAP_NOTFOUND:
return (IDMAP_ERR_NOTFOUND);
case NS_LDAP_MEMORY:
return (IDMAP_ERR_MEMORY);
case NS_LDAP_CONFIG:
return (IDMAP_ERR_NS_LDAP_CFG);
case NS_LDAP_OP_FAILED:
return (IDMAP_ERR_NS_LDAP_OP_FAILED);
case NS_LDAP_PARTIAL:
return (IDMAP_ERR_NS_LDAP_PARTIAL);
case NS_LDAP_INTERNAL:
return (IDMAP_ERR_INTERNAL);
case NS_LDAP_INVALID_PARAM:
return (IDMAP_ERR_ARG);
default:
return (IDMAP_ERR_OTHER);
}
/*NOTREACHED*/
}
/*
* Create a batch for native LDAP lookup.
*/
static
idmap_retcode
idmap_nldap_lookup_batch_start(int nqueries, idmap_nldap_query_state_t **qs)
{
idmap_nldap_query_state_t *s;
s = calloc(1, sizeof (*s) +
(nqueries - 1) * sizeof (idmap_nldap_q_t));
if (s == NULL)
return (IDMAP_ERR_MEMORY);
if (__ns_ldap_list_batch_start(&s->batch) != NS_LDAP_SUCCESS) {
free(s);
return (IDMAP_ERR_MEMORY);
}
s->nqueries = nqueries;
s->flag = NS_LDAP_KEEP_CONN;
*qs = s;
return (IDMAP_SUCCESS);
}
/*
* Add a lookup by winname request to the batch.
*/
static
idmap_retcode
idmap_nldap_bywinname_batch_add(idmap_nldap_query_state_t *qs,
const char *winname, const char *windomain, int is_user,
char **dn, char **attr, char **value,
char **unixname, uid_t *pid, idmap_retcode *rc)
{
idmap_nldap_q_t *q;
const char *db, *filter, *udata;
int flen, ulen, wksid = 0;
char *s_winname, *s_windomain;
const char **attrs;
const char *pwd_attrs[] = {UID, UIDNUMBER, NULL, NULL};
const char *grp_attrs[] = {CN, GIDNUMBER, NULL, NULL};
s_winname = s_windomain = NULL;
q = &(qs->queries[qs->qid++]);
q->unixname = unixname;
q->pid = pid;
q->rc = rc;
q->is_user = is_user;
q->dn = dn;
q->attr = attr;
q->value = value;
if (is_user) {
db = "passwd";
if (lookup_wksids_name2sid(winname, NULL, NULL, NULL, NULL,
NULL, NULL) == IDMAP_SUCCESS) {
filter = _F_GETPWWNAMWK;
udata = _F_GETPWWNAMWK_SSD;
wksid = 1;
} else if (windomain != NULL) {
filter = _F_GETPWWNAMDOM;
udata = _F_GETPWWNAMDOM_SSD;
} else {
*q->rc = IDMAP_ERR_DOMAIN_NOTFOUND;
goto errout;
}
pwd_attrs[2] = qs->nldap_winname_attr;
attrs = pwd_attrs;
} else {
db = "group";
if (lookup_wksids_name2sid(winname, NULL, NULL, NULL, NULL,
NULL, NULL) == IDMAP_SUCCESS) {
filter = _F_GETGRWNAMWK;
udata = _F_GETGRWNAMWK_SSD;
wksid = 1;
} else if (windomain != NULL) {
filter = _F_GETGRWNAMDOM;
udata = _F_GETGRWNAMDOM_SSD;
} else {
*q->rc = IDMAP_ERR_DOMAIN_NOTFOUND;
goto errout;
}
grp_attrs[2] = qs->nldap_winname_attr;
attrs = grp_attrs;
}
/*
* Sanitize names. No need to sanitize qs->nldap_winname_attr
* because if it contained any of the special characters then
* it would have been rejected by the function that reads it
* from the SMF config. LDAP attribute names can only contain
* letters, digits or hyphens.
*/
s_winname = sanitize_for_ldap_filter(winname);
if (s_winname == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
goto errout;
}
/* windomain could be NULL for names of well-known SIDs */
if (windomain != NULL) {
s_windomain = sanitize_for_ldap_filter(windomain);
if (s_windomain == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
goto errout;
}
}
/* Construct the filter and udata using snprintf. */
if (wksid) {
flen = snprintf(NULL, 0, filter, qs->nldap_winname_attr,
s_winname) + 1;
ulen = snprintf(NULL, 0, udata, qs->nldap_winname_attr,
s_winname) + 1;
} else {
flen = snprintf(NULL, 0, filter, qs->nldap_winname_attr,
s_winname, s_windomain) + 1;
ulen = snprintf(NULL, 0, udata, qs->nldap_winname_attr,
s_winname, s_windomain) + 1;
}
q->filter = malloc(flen);
if (q->filter == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
goto errout;
}
q->udata = malloc(ulen);
if (q->udata == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
goto errout;
}
if (wksid) {
(void) snprintf(q->filter, flen, filter,
qs->nldap_winname_attr, s_winname);
(void) snprintf(q->udata, ulen, udata,
qs->nldap_winname_attr, s_winname);
} else {
(void) snprintf(q->filter, flen, filter,
qs->nldap_winname_attr, s_winname, s_windomain);
(void) snprintf(q->udata, ulen, udata,
qs->nldap_winname_attr, s_winname, s_windomain);
}
if (s_winname != winname)
free(s_winname);
if (s_windomain != windomain)
free(s_windomain);
q->lrc = __ns_ldap_list_batch_add(qs->batch, db, q->filter,
merge_SSD_filter, attrs, NULL, qs->flag, &q->result,
&q->errorp, &q->lrc, NULL, q->udata);
if (IS_NLDAP_RC_FATAL(q->lrc))
return (nldaprc2retcode(q->lrc));
return (IDMAP_SUCCESS);
errout:
/* query q and its content will be freed by batch_release */
if (s_winname != winname)
free(s_winname);
if (s_windomain != windomain)
free(s_windomain);
return (*q->rc);
}
/*
* Add a lookup by uid/gid request to the batch.
*/
static
idmap_retcode
idmap_nldap_bypid_batch_add(idmap_nldap_query_state_t *qs,
uid_t pid, int is_user, char **dn, char **attr, char **value,
char **winname, char **windomain,
char **unixname, idmap_retcode *rc)
{
idmap_nldap_q_t *q;
const char *db, *filter, *udata;
int len;
const char **attrs;
const char *pwd_attrs[] = {UID, NULL, NULL};
const char *grp_attrs[] = {CN, NULL, NULL};
q = &(qs->queries[qs->qid++]);
q->winname = winname;
q->windomain = windomain;
q->unixname = unixname;
q->rc = rc;
q->is_user = is_user;
q->dn = dn;
q->attr = attr;
q->value = value;
if (is_user) {
db = "passwd";
filter = _F_GETPWUID;
udata = _F_GETPWUID_SSD;
pwd_attrs[1] = qs->nldap_winname_attr;
attrs = pwd_attrs;
} else {
db = "group";
filter = _F_GETGRGID;
udata = _F_GETGRGID_SSD;
grp_attrs[1] = qs->nldap_winname_attr;
attrs = grp_attrs;
}
len = snprintf(NULL, 0, filter, pid) + 1;
q->filter = malloc(len);
if (q->filter == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
return (IDMAP_ERR_MEMORY);
}
(void) snprintf(q->filter, len, filter, pid);
len = snprintf(NULL, 0, udata, pid) + 1;
q->udata = malloc(len);
if (q->udata == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
return (IDMAP_ERR_MEMORY);
}
(void) snprintf(q->udata, len, udata, pid);
q->lrc = __ns_ldap_list_batch_add(qs->batch, db, q->filter,
merge_SSD_filter, attrs, NULL, qs->flag, &q->result,
&q->errorp, &q->lrc, NULL, q->udata);
if (IS_NLDAP_RC_FATAL(q->lrc))
return (nldaprc2retcode(q->lrc));
return (IDMAP_SUCCESS);
}
/*
* Add a lookup by user/group name request to the batch.
*/
static
idmap_retcode
idmap_nldap_byunixname_batch_add(idmap_nldap_query_state_t *qs,
const char *unixname, int is_user,
char **dn, char **attr, char **value,
char **winname, char **windomain, uid_t *pid, idmap_retcode *rc)
{
idmap_nldap_q_t *q;
const char *db, *filter, *udata;
int len;
char *s_unixname = NULL;
const char **attrs;
const char *pwd_attrs[] = {UIDNUMBER, NULL, NULL};
const char *grp_attrs[] = {GIDNUMBER, NULL, NULL};
q = &(qs->queries[qs->qid++]);
q->winname = winname;
q->windomain = windomain;
q->pid = pid;
q->rc = rc;
q->is_user = is_user;
q->dn = dn;
q->attr = attr;
q->value = value;
if (is_user) {
db = "passwd";
filter = _F_GETPWNAM;
udata = _F_GETPWNAM_SSD;
pwd_attrs[1] = qs->nldap_winname_attr;
attrs = pwd_attrs;
} else {
db = "group";
filter = _F_GETGRNAM;
udata = _F_GETGRNAM_SSD;
grp_attrs[1] = qs->nldap_winname_attr;
attrs = grp_attrs;
}
s_unixname = sanitize_for_ldap_filter(unixname);
if (s_unixname == NULL) {
*q->rc = IDMAP_ERR_MEMORY;
return (IDMAP_ERR_MEMORY);
}
len = snprintf(NULL, 0, filter, s_unixname) + 1;
q->filter = malloc(len);
if (q->filter == NULL) {
if (s_unixname != unixname)
free(s_unixname);
*q->rc = IDMAP_ERR_MEMORY;
return (IDMAP_ERR_MEMORY);
}
(void) snprintf(q->filter, len, filter, s_unixname);
len = snprintf(NULL, 0, udata, s_unixname) + 1;
q->udata = malloc(len);
if (q->udata == NULL) {
if (s_unixname != unixname)
free(s_unixname);
*q->rc = IDMAP_ERR_MEMORY;
return (IDMAP_ERR_MEMORY);
}
(void) snprintf(q->udata, len, udata, s_unixname);
if (s_unixname != unixname)
free(s_unixname);
q->lrc = __ns_ldap_list_batch_add(qs->batch, db, q->filter,
merge_SSD_filter, attrs, NULL, qs->flag, &q->result,
&q->errorp, &q->lrc, NULL, q->udata);
if (IS_NLDAP_RC_FATAL(q->lrc))
return (nldaprc2retcode(q->lrc));
return (IDMAP_SUCCESS);
}
/*
* Free the batch
*/
static
void
idmap_nldap_lookup_batch_release(idmap_nldap_query_state_t *qs)
{
idmap_nldap_q_t *q;
int i;
if (qs->batch != NULL)
(void) __ns_ldap_list_batch_release(qs->batch);
for (i = 0; i < qs->qid; i++) {
q = &(qs->queries[i]);
free(q->filter);
free(q->udata);
if (q->errorp != NULL)
(void) __ns_ldap_freeError(&q->errorp);
if (q->result != NULL)
(void) __ns_ldap_freeResult(&q->result);
}
free(qs);
}
/*
* Process all requests added to the batch and then free the batch.
* The results for individual requests will be accessible using the
* pointers passed during idmap_nldap_lookup_batch_end.
*/
static
idmap_retcode
idmap_nldap_lookup_batch_end(idmap_nldap_query_state_t *qs)
{
idmap_nldap_q_t *q;
int i;
ns_ldap_entry_t *entry;
char **val, *end, *str, *name, *dom;
idmap_retcode rc = IDMAP_SUCCESS;
(void) __ns_ldap_list_batch_end(qs->batch);
qs->batch = NULL;
for (i = 0; i < qs->qid; i++) {
q = &(qs->queries[i]);
*q->rc = nldaprc2retcode(q->lrc);
if (*q->rc != IDMAP_SUCCESS)
continue;
if (q->result == NULL ||
!q->result->entries_count ||
(entry = q->result->entry) == NULL ||
!entry->attr_count) {
*q->rc = IDMAP_ERR_NOTFOUND;
continue;
}
/* Get uid/gid */
if (q->pid != NULL) {
val = __ns_ldap_getAttr(entry,
(q->is_user) ? UIDNUMBER : GIDNUMBER);
if (val != NULL && *val != NULL)
*q->pid = strtoul(*val, &end, 10);
}
/* Get unixname */
if (q->unixname != NULL) {
val = __ns_ldap_getAttr(entry,
(q->is_user) ? UID : CN);
if (val != NULL && *val != NULL) {
*q->unixname = strdup(*val);
if (*q->unixname == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
}
/* Get DN for how info */
if (q->dn != NULL) {
val = __ns_ldap_getAttr(entry, DN);
if (val != NULL && *val != NULL) {
*q->dn = strdup(*val);
if (*q->dn == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
}
/* Get nldap name mapping attr name for how info */
if (q->attr != NULL) {
*q->attr = strdup(qs->nldap_winname_attr);
if (*q->attr == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
/* Get nldap name mapping attr value for how info */
val = __ns_ldap_getAttr(entry, qs->nldap_winname_attr);
if (val == NULL || *val == NULL)
continue;
if (q->value != NULL) {
*q->value = strdup(*val);
if (*q->value == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
/* Get winname and windomain */
if (q->winname == NULL && q->windomain == NULL)
continue;
/*
* We need to split the value into winname and
* windomain. The value could be either in NT4
* style (i.e. dom\name) or AD-style (i.e. name@dom).
* We choose the first '\\' if it's in NT4 style and
* the last '@' if it's in AD-style for the split.
*/
name = dom = NULL;
if (lookup_wksids_name2sid(*val, NULL, NULL, NULL, NULL, NULL,
NULL) == IDMAP_SUCCESS) {
name = *val;
dom = NULL;
} else if ((str = strchr(*val, '\\')) != NULL) {
*str = '\0';
name = str + 1;
dom = *val;
} else if ((str = strrchr(*val, '@')) != NULL) {
*str = '\0';
name = *val;
dom = str + 1;
} else {
idmapdlog(LOG_INFO, "Domain-less "
"winname (%s) found in Native LDAP", *val);
*q->rc = IDMAP_ERR_NS_LDAP_BAD_WINNAME;
continue;
}
if (q->winname != NULL) {
*q->winname = strdup(name);
if (*q->winname == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
if (q->windomain != NULL && dom != NULL) {
*q->windomain = strdup(dom);
if (*q->windomain == NULL) {
rc = *q->rc = IDMAP_ERR_MEMORY;
goto out;
}
}
}
out:
(void) idmap_nldap_lookup_batch_release(qs);
return (rc);
}
/* ARGSUSED */
idmap_retcode
nldap_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
idmap_ids_res *result)
{
idmap_retcode retcode, rc1;
int i, add;
idmap_mapping *req;
idmap_id_res *res;
idmap_nldap_query_state_t *qs = NULL;
idmap_how *how;
if (state->nldap_nqueries == 0)
return (IDMAP_SUCCESS);
/* Create nldap lookup batch */
retcode = idmap_nldap_lookup_batch_start(state->nldap_nqueries, &qs);
if (retcode != IDMAP_SUCCESS) {
idmapdlog(LOG_ERR,
"Failed to create batch for native LDAP lookup");
goto out;
}
qs->nldap_winname_attr = state->nldap_winname_attr;
qs->defdom = state->defdom;
/* Add requests to the batch */
for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
req = &batch->idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
retcode = IDMAP_SUCCESS;
/* Skip if not marked for nldap lookup */
if (!(req->direction & _IDMAP_F_LOOKUP_NLDAP))
continue;
if (IS_ID_SID(req->id1)) {
/* win2unix request: */
/*
* When processing a win2unix request, nldap lookup
* is performed after AD lookup or a successful
* name-cache lookup. Therefore we should already
* have sid, winname and sidtype. Note that
* windomain could be NULL e.g. well-known SIDs.
*/
assert(req->id1name != NULL &&
(res->id.idtype == IDMAP_UID ||
res->id.idtype == IDMAP_GID));
/* Skip if we already have pid and unixname */
if (req->id2name != NULL &&
res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
res->retcode = IDMAP_SUCCESS;
continue;
}
/* Clear leftover value */
free(req->id2name);
req->id2name = NULL;
/* Lookup nldap by winname to get pid and unixname */
add = 1;
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how = &res->info.how;
how->map_type = IDMAP_MAP_TYPE_DS_NLDAP;
retcode = idmap_nldap_bywinname_batch_add(
qs, req->id1name, req->id1domain,
(res->id.idtype == IDMAP_UID) ? 1 : 0,
&how->idmap_how_u.nldap.dn,
&how->idmap_how_u.nldap.attr,
&how->idmap_how_u.nldap.value,
&req->id2name, &res->id.idmap_id_u.uid,
&res->retcode);
} else if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1)) {
/* unix2win request: */
/* Skip if we already have winname */
if (req->id2name != NULL) {
res->retcode = IDMAP_SUCCESS;
continue;
}
/* Clear old value */
free(req->id2domain);
req->id2domain = NULL;
/* Set how info */
idmap_how_clear(&res->info.how);
res->info.src = IDMAP_MAP_SRC_NEW;
how = &res->info.how;
how->map_type = IDMAP_MAP_TYPE_DS_NLDAP;
/* Lookup nldap by pid or unixname to get winname */
if (req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
add = 1;
retcode = idmap_nldap_bypid_batch_add(
qs, req->id1.idmap_id_u.uid,
(req->id1.idtype == IDMAP_UID) ? 1 : 0,
&how->idmap_how_u.nldap.dn,
&how->idmap_how_u.nldap.attr,
&how->idmap_how_u.nldap.value,
&req->id2name, &req->id2domain,
(req->id1name == NULL) ?
&req->id1name : NULL,
&res->retcode);
} else if (req->id1name != NULL) {
add = 1;
retcode = idmap_nldap_byunixname_batch_add(
qs, req->id1name,
(req->id1.idtype == IDMAP_UID) ? 1 : 0,
&how->idmap_how_u.nldap.dn,
&how->idmap_how_u.nldap.attr,
&how->idmap_how_u.nldap.value,
&req->id2name, &req->id2domain,
&req->id1.idmap_id_u.uid, &res->retcode);
}
}
/*
* nldap_batch_add API returns error only on fatal failures
* otherwise it returns success and the actual status
* is stored in the individual request (res->retcode).
* Stop adding requests to this batch on fatal failures
* (i.e. if retcode != success)
*/
if (retcode != IDMAP_SUCCESS)
break;
}
if (!add)
idmap_nldap_lookup_batch_release(qs);
else if (retcode != IDMAP_SUCCESS)
idmap_nldap_lookup_batch_release(qs);
else
retcode = idmap_nldap_lookup_batch_end(qs);
out:
for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
req = &batch->idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
if (!(req->direction & _IDMAP_F_LOOKUP_NLDAP))
continue;
/* Reset nldap flag */
req->direction &= ~(_IDMAP_F_LOOKUP_NLDAP);
/*
* As noted earlier retcode != success if there were fatal
* errors during batch_start and batch_adds. If so then set
* the status of each nldap request to that error.
*/
if (retcode != IDMAP_SUCCESS) {
res->retcode = retcode;
continue;
}
if (!add)
continue;
/*
* If we successfully retrieved winname from nldap entry
* then lookup winname2sid locally. If not found locally
* then mark this request for AD lookup.
*/
if (res->retcode == IDMAP_SUCCESS &&
req->id2name != NULL &&
res->id.idmap_id_u.sid.prefix == NULL &&
(IS_ID_UID(req->id1) || IS_ID_GID(req->id1))) {
rc1 = lookup_name2sid(state->cache,
req->id2name, req->id2domain, -1,
NULL, NULL,
&res->id.idmap_id_u.sid.prefix,
&res->id.idmap_id_u.sid.rid,
&res->id.idtype,
req, 1);
if (rc1 == IDMAP_ERR_NOTFOUND) {
req->direction |= _IDMAP_F_LOOKUP_AD;
state->ad_nqueries++;
} else
res->retcode = rc1;
}
/*
* Unset non-fatal errors in individual request. This allows
* the next pass to process other mapping mechanisms for
* this request.
*/
if (res->retcode != IDMAP_SUCCESS &&
res->retcode != IDMAP_ERR_NS_LDAP_BAD_WINNAME &&
!(IDMAP_FATAL_ERROR(res->retcode))) {
idmap_how_clear(&res->info.how);
res->retcode = IDMAP_SUCCESS;
}
}
state->nldap_nqueries = 0;
return (retcode);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _NLDAPUTILS_H
#define _NLDAPUTILS_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <synch.h>
#include <thread.h>
#include <libintl.h>
#include <strings.h>
#include <inttypes.h>
#include <rpcsvc/idmap_prot.h>
#include "idmapd.h"
#include "idmap_config.h"
#ifdef __cplusplus
extern "C" {
#endif
extern idmap_retcode nldap_lookup_one(lookup_state_t *, idmap_mapping *,
idmap_id_res *);
extern idmap_retcode nldap_lookup_batch(lookup_state_t *,
idmap_mapping_batch *, idmap_ids_res *);
extern char *sanitize_for_ldap_filter(const char *);
#ifdef __cplusplus
}
#endif
#endif /* _NLDAPUTILS_H */
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#include "idmap_prot.h"
#include <stdio.h>
#include <stdlib.h> /* getenv, exit */
#include <signal.h>
#include <rpc/pmap_clnt.h> /* for pmap_unset */
#include <string.h> /* strcmp */
#include <unistd.h> /* setsid */
#include <sys/types.h>
#include <memory.h>
#include <stropts.h>
#include <sys/resource.h> /* rlimit */
#include <syslog.h>
#ifndef SIG_PF
#define SIG_PF void(*)(int)
#endif
#ifdef DEBUG
#define RPC_SVC_FG
#endif
#define _RPCSVC_CLOSEDOWN 120
#if defined(_KERNEL)
#include <sys/nvpair.h>
#else
#include <libnvpair.h>
#endif
extern int _rpcpmstart; /* Started by a port monitor ? */
/* States a server can be in wrt request */
#define _IDLE 0
#define _SERVED 1
/* LINTED static unused if no main */
static int _rpcsvcstate = _IDLE; /* Set when a request is serviced */
static int _rpcsvccount = 0; /* Number of requests being serviced */
extern mutex_t _svcstate_lock; /* lock for _rpcsvcstate, _rpcsvccount */
#if defined(RPC_MSGOUT)
extern void RPC_MSGOUT(const char *, ...);
#else /* defined(RPC_MSGOUT) */
static void
RPC_MSGOUT(const char *fmt, char *msg)
{
#ifdef RPC_SVC_FG
if (_rpcpmstart)
syslog(LOG_ERR, fmt, msg);
else {
(void) fprintf(stderr, fmt, msg);
(void) putc('\n', stderr);
}
#else
syslog(LOG_ERR, fmt, msg);
#endif
}
#endif /* defined(RPC_MSGOUT) */
/* ARGSUSED */
int
_idmap_null_1(
void *argp,
void *result,
struct svc_req *rqstp)
{
return (idmap_null_1_svc(result, rqstp));
}
int
_idmap_get_mapped_ids_1(
idmap_mapping_batch *argp,
idmap_ids_res *result,
struct svc_req *rqstp)
{
return (idmap_get_mapped_ids_1_svc(*argp, result, rqstp));
}
int
_idmap_list_mappings_1(
idmap_list_mappings_1_argument *argp,
idmap_mappings_res *result,
struct svc_req *rqstp)
{
return (idmap_list_mappings_1_svc(
argp->lastrowid,
argp->limit,
argp->flag,
result, rqstp));
}
int
_idmap_list_namerules_1(
idmap_list_namerules_1_argument *argp,
idmap_namerules_res *result,
struct svc_req *rqstp)
{
return (idmap_list_namerules_1_svc(
argp->rule,
argp->lastrowid,
argp->limit,
result, rqstp));
}
int
_idmap_update_1(
idmap_update_batch *argp,
idmap_update_res *result,
struct svc_req *rqstp)
{
return (idmap_update_1_svc(*argp, result, rqstp));
}
int
_idmap_get_mapped_id_by_name_1(
idmap_mapping *argp,
idmap_mappings_res *result,
struct svc_req *rqstp)
{
return (idmap_get_mapped_id_by_name_1_svc(*argp, result, rqstp));
}
int
_idmap_get_prop_1(
idmap_prop_type *argp,
idmap_prop_res *result,
struct svc_req *rqstp)
{
return (idmap_get_prop_1_svc(*argp, result, rqstp));
}
int
_directory_get_common_1(
directory_get_common_1_argument *argp,
directory_results_rpc *result,
struct svc_req *rqstp)
{
return (directory_get_common_1_svc(
argp->ids,
argp->types,
argp->attrs,
result, rqstp));
}
int
_idmap_flush_1(
idmap_flush_op *argp,
idmap_retcode *result,
struct svc_req *rqstp)
{
return (idmap_flush_1_svc(*argp, result, rqstp));
}
void
idmap_prog_1(struct svc_req *rqstp, register SVCXPRT *transp)
{
union {
idmap_mapping_batch idmap_get_mapped_ids_1_arg;
idmap_list_mappings_1_argument idmap_list_mappings_1_arg;
idmap_list_namerules_1_argument idmap_list_namerules_1_arg;
idmap_update_batch idmap_update_1_arg;
idmap_mapping idmap_get_mapped_id_by_name_1_arg;
idmap_prop_type idmap_get_prop_1_arg;
directory_get_common_1_argument directory_get_common_1_arg;
idmap_flush_op idmap_flush_1_arg;
} argument;
union {
idmap_ids_res idmap_get_mapped_ids_1_res;
idmap_mappings_res idmap_list_mappings_1_res;
idmap_namerules_res idmap_list_namerules_1_res;
idmap_update_res idmap_update_1_res;
idmap_mappings_res idmap_get_mapped_id_by_name_1_res;
idmap_prop_res idmap_get_prop_1_res;
directory_results_rpc directory_get_common_1_res;
idmap_retcode idmap_flush_1_res;
} result;
bool_t retval;
xdrproc_t _xdr_argument, _xdr_result;
bool_t (*local)(char *, void *, struct svc_req *);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount++;
(void) mutex_unlock(&_svcstate_lock);
switch (rqstp->rq_proc) {
case IDMAP_NULL:
_xdr_argument = (xdrproc_t)
xdr_void;
_xdr_result = (xdrproc_t)
xdr_void;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_null_1;
break;
case IDMAP_GET_MAPPED_IDS:
_xdr_argument = (xdrproc_t)
xdr_idmap_mapping_batch;
_xdr_result = (xdrproc_t)
xdr_idmap_ids_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_get_mapped_ids_1;
break;
case IDMAP_LIST_MAPPINGS:
_xdr_argument = (xdrproc_t)
xdr_idmap_list_mappings_1_argument;
_xdr_result = (xdrproc_t)
xdr_idmap_mappings_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_list_mappings_1;
break;
case IDMAP_LIST_NAMERULES:
_xdr_argument = (xdrproc_t)
xdr_idmap_list_namerules_1_argument;
_xdr_result = (xdrproc_t)
xdr_idmap_namerules_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_list_namerules_1;
break;
case IDMAP_UPDATE:
_xdr_argument = (xdrproc_t)
xdr_idmap_update_batch;
_xdr_result = (xdrproc_t)
xdr_idmap_update_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_update_1;
break;
case IDMAP_GET_MAPPED_ID_BY_NAME:
_xdr_argument = (xdrproc_t)
xdr_idmap_mapping;
_xdr_result = (xdrproc_t)
xdr_idmap_mappings_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_get_mapped_id_by_name_1;
break;
case IDMAP_GET_PROP:
_xdr_argument = (xdrproc_t)
xdr_idmap_prop_type;
_xdr_result = (xdrproc_t)
xdr_idmap_prop_res;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_get_prop_1;
break;
case DIRECTORY_GET_COMMON:
_xdr_argument = (xdrproc_t)
xdr_directory_get_common_1_argument;
_xdr_result = (xdrproc_t)
xdr_directory_results_rpc;
local = (bool_t (*) (char *, void *, struct svc_req *))
_directory_get_common_1;
break;
case IDMAP_FLUSH:
_xdr_argument = (xdrproc_t)
xdr_idmap_flush_op;
_xdr_result = (xdrproc_t)
xdr_idmap_retcode;
local = (bool_t (*) (char *, void *, struct svc_req *))
_idmap_flush_1;
break;
default:
svcerr_noproc(transp);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
(void) memset((char *)&argument, 0, sizeof (argument));
if (!svc_getargs(transp, _xdr_argument, (caddr_t)&argument)) {
svcerr_decode(transp);
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
retval = (bool_t)(*local)((char *)&argument, (void *)&result, rqstp);
if (_xdr_result && retval > 0 &&
!svc_sendreply(transp, _xdr_result, (char *)&result)) {
svcerr_systemerr(transp);
}
if (!svc_freeargs(transp, _xdr_argument, (caddr_t)&argument)) {
RPC_MSGOUT("%s",
"unable to free arguments");
exit(1);
}
if (_xdr_result != NULL) {
if (!idmap_prog_1_freeresult(transp, _xdr_result,
(caddr_t)&result))
RPC_MSGOUT("%s",
"unable to free results");
}
(void) mutex_lock(&_svcstate_lock);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
(void) mutex_unlock(&_svcstate_lock);
return; /* CSTYLED */
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _SCHEMA_H
#define _SCHEMA_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Various macros (constant strings) containing:
*
* - CREATE TABLE/INDEX/TRIGGER/VIEW SQL
* - old versions of schema items that have changed
* - SQL to detect the version currently installed in a db
* - SQL to upgrade the schema from any older version to the current
* - the SQL to install the current version of the schema on a
* freshly created db is the SQL used to "upgrade" from "version 0"
*
* There is one set of such macros for the cache DB (CACHE_*) and
* another set for the persistent DB (DB_*). The macros ending in _SQL
* are used in arguments to init_db_instance().
*
* Schema version detection SQL has the following form:
*
* SELECT CASE (SELECT count(*) FROM sqlite_master) WHEN 0 THEN 0 ELSE
* (CASE (SELECT count(*) FROM sqlite_master WHERE sql = <original schema> ...)
* WHEN <correct count> THEN 1 ELSE (CASE (<v2 schema>) WHEN ... THEN 2
* ELSE -1 END) END AS version;
*
* That is, check that there is no schema else that the current schema
* sql matches the original schema, else the next version, ... and
* return an integer identifying the schema. Version numbers returned:
*
* -1 -> unknown schema (shouldn't happen)
* 0 -> no schema (brand new DB, install latest schema)
* 1 -> original schema (if != latest, then upgrade)
* . -> ... (if != latest, then upgrade)
* n -> latest schema (nothing to do)
*
* Upgrade SQL for the cache DB is simple: drop everything, create
* latest schema. This means losing ephemeral mappings, so idmapd must
* tell the kernel about that in its registration call.
*
* Upgrade SQL for the persistent DB is simple: drop the indexes, create
* temporary tables with the latest schema, insert into those from the
* old tables (transforming the data in the process), then drop the old
* tables, create the latest schema, restore the data from the temp.
* tables and drop the temp tables.
*
* Complex, but it avoids all sorts of packaging install/upgrade
* complexity, requiring reboots on patch.
*
* Conventions:
* - each TABLE/INDEX gets its own macro, and the SQL therein must not
* end in a semi-colon (';)
* - macros are named * TABLE_* for tables, INDEX_* for indexes,
* *_VERSION_SQL for SQL for determining version number,
* *_UPGRADE_FROM_v<version>_SQL for SQL for upgrading from some
* schema, *_LATEST_SQL for SQL for installing the latest schema.
* - some macros nest expansions of other macros
*
* The latest schema has two columns for Windows user/group name in
* tables where there used to be one. One of those columns contains the
* name as it came from the user or from AD, the other is set via a
* TRIGGER to be the lower-case version of the first, and we always
* search (and index) by the latter. This is for case-insensitivity.
*/
#define TABLE_IDMAP_CACHE_v1 \
"CREATE TABLE idmap_cache (" \
" sidprefix TEXT," \
" rid INTEGER," \
" windomain TEXT," \
" winname TEXT," \
" pid INTEGER," \
" unixname TEXT," \
" is_user INTEGER," \
" w2u INTEGER," \
" u2w INTEGER," \
" expiration INTEGER" \
")"
#define TABLE_IDMAP_CACHE_v2 \
"CREATE TABLE idmap_cache " \
"(" \
" sidprefix TEXT," \
" rid INTEGER," \
" windomain TEXT," \
" canon_winname TEXT," \
" winname TEXT," \
" pid INTEGER," \
" unixname TEXT," \
" is_user INTEGER," \
" is_wuser INTEGER," \
" w2u INTEGER," \
" u2w INTEGER," \
" expiration INTEGER" \
")"
#define TABLE_IDMAP_CACHE \
"CREATE TABLE idmap_cache " \
"(" \
" sidprefix TEXT," \
" rid INTEGER," \
" windomain TEXT," \
" canon_winname TEXT," \
" winname TEXT," \
" pid INTEGER," \
" unixname TEXT," \
" is_user INTEGER," \
" is_wuser INTEGER," \
" w2u INTEGER," \
" u2w INTEGER," \
" map_type INTEGER," \
" map_dn TEXT, "\
" map_attr TEXT, "\
" map_value TEXT, "\
" map_windomain TEXT, "\
" map_winname TEXT, "\
" map_unixname TEXT, "\
" map_is_nt4 INTEGER, "\
" expiration INTEGER" \
")"
#define INDEX_IDMAP_CACHE_SID_W2U_v1 \
"CREATE UNIQUE INDEX idmap_cache_sid_w2u ON idmap_cache" \
" (sidprefix, rid, w2u)"
#define INDEX_IDMAP_CACHE_SID_W2U \
"CREATE UNIQUE INDEX idmap_cache_sid_w2u ON idmap_cache" \
" (sidprefix, rid, is_user, w2u)"
#define INDEX_IDMAP_CACHE_PID_U2W \
"CREATE UNIQUE INDEX idmap_cache_pid_u2w ON idmap_cache" \
" (pid, is_user, u2w)"
#define TRIGGER_IDMAP_CACHE_TOLOWER_INSERT \
"CREATE TRIGGER idmap_cache_tolower_name_insert " \
"AFTER INSERT ON idmap_cache " \
"BEGIN " \
" UPDATE idmap_cache SET winname = lower_utf8(canon_winname)" \
" WHERE rowid = new.rowid;" \
"END"
#define TRIGGER_IDMAP_CACHE_TOLOWER_UPDATE \
"CREATE TRIGGER idmap_cache_tolower_name_update " \
"AFTER UPDATE ON idmap_cache " \
"BEGIN " \
" UPDATE idmap_cache SET winname = lower_utf8(canon_winname)" \
" WHERE rowid = new.rowid;" \
"END"
#define TABLE_NAME_CACHE \
"CREATE TABLE name_cache (" \
" sidprefix TEXT," \
" rid INTEGER," \
" name TEXT," \
" canon_name TEXT," \
" domain TEXT," \
" type INTEGER," \
" expiration INTEGER" \
")"
#define TABLE_NAME_CACHE_v1 \
"CREATE TABLE name_cache (" \
" sidprefix TEXT," \
" rid INTEGER," \
" name TEXT," \
" domain TEXT," \
" type INTEGER," \
" expiration INTEGER" \
")"
#define TRIGGER_NAME_CACHE_TOLOWER_INSERT \
"CREATE TRIGGER name_cache_tolower_name_insert " \
"AFTER INSERT ON name_cache " \
"BEGIN " \
" UPDATE name_cache SET name = lower_utf8(canon_name)" \
" WHERE rowid = new.rowid;" \
"END"
#define TRIGGER_NAME_CACHE_TOLOWER_UPDATE \
"CREATE TRIGGER name_cache_tolower_name_update " \
"AFTER UPDATE ON name_cache " \
"BEGIN " \
" UPDATE name_cache SET name = lower_utf8(canon_name)" \
" WHERE rowid = new.rowid;" \
"END"
#define INDEX_NAME_CACHE_SID \
"CREATE UNIQUE INDEX name_cache_sid ON name_cache" \
" (sidprefix, rid)"
#define INDEX_NAME_CACHE_NAME \
"CREATE UNIQUE INDEX name_cache_name ON name_cache" \
" (name, domain)"
#define CACHE_INSTALL_SQL \
TABLE_IDMAP_CACHE ";" \
INDEX_IDMAP_CACHE_SID_W2U ";" \
INDEX_IDMAP_CACHE_PID_U2W ";" \
TRIGGER_IDMAP_CACHE_TOLOWER_INSERT ";" \
TRIGGER_IDMAP_CACHE_TOLOWER_UPDATE ";" \
TABLE_NAME_CACHE ";" \
INDEX_NAME_CACHE_SID ";" \
INDEX_NAME_CACHE_NAME ";" \
TRIGGER_NAME_CACHE_TOLOWER_INSERT ";" \
TRIGGER_NAME_CACHE_TOLOWER_UPDATE ";"
#define CACHE_VERSION_SQL \
"SELECT CASE (SELECT count(*) FROM sqlite_master) WHEN 0 THEN 0 ELSE " \
"(CASE (SELECT count(*) FROM sqlite_master WHERE " \
"sql = '" TABLE_IDMAP_CACHE_v1 "' OR " \
"sql = '" INDEX_IDMAP_CACHE_SID_W2U_v1 "' OR " \
"sql = '" INDEX_IDMAP_CACHE_PID_U2W "' OR " \
"sql = '" TABLE_NAME_CACHE_v1 "' OR " \
"sql = '" INDEX_NAME_CACHE_SID "') " \
"WHEN 5 THEN 1 ELSE " \
"(CASE (SELECT count(*) FROM sqlite_master WHERE " \
"sql = '" TABLE_IDMAP_CACHE_v2"' OR " \
"sql = '" INDEX_IDMAP_CACHE_SID_W2U "' OR " \
"sql = '" INDEX_IDMAP_CACHE_PID_U2W "' OR " \
"sql = '" TRIGGER_IDMAP_CACHE_TOLOWER_INSERT "' OR " \
"sql = '" TRIGGER_IDMAP_CACHE_TOLOWER_UPDATE "' OR " \
"sql = '" TABLE_NAME_CACHE "' OR " \
"sql = '" INDEX_NAME_CACHE_SID "' OR " \
"sql = '" INDEX_NAME_CACHE_NAME "' OR " \
"sql = '" TRIGGER_NAME_CACHE_TOLOWER_INSERT "' OR " \
"sql = '" TRIGGER_NAME_CACHE_TOLOWER_UPDATE "') " \
"WHEN 10 THEN 2 ELSE " \
"(CASE (SELECT count(*) FROM sqlite_master WHERE " \
"sql = '" TABLE_IDMAP_CACHE"' OR " \
"sql = '" INDEX_IDMAP_CACHE_SID_W2U "' OR " \
"sql = '" INDEX_IDMAP_CACHE_PID_U2W "' OR " \
"sql = '" TRIGGER_IDMAP_CACHE_TOLOWER_INSERT "' OR " \
"sql = '" TRIGGER_IDMAP_CACHE_TOLOWER_UPDATE "' OR " \
"sql = '" TABLE_NAME_CACHE "' OR " \
"sql = '" INDEX_NAME_CACHE_SID "' OR " \
"sql = '" INDEX_NAME_CACHE_NAME "' OR " \
"sql = '" TRIGGER_NAME_CACHE_TOLOWER_INSERT "' OR " \
"sql = '" TRIGGER_NAME_CACHE_TOLOWER_UPDATE "') " \
"WHEN 10 THEN 3 ELSE -1 END) END) END) END AS version;"
#define CACHE_UPGRADE_FROM_v1_SQL \
"DROP TABLE idmap_cache;" \
"DROP TABLE name_cache;" \
CACHE_INSTALL_SQL
#define CACHE_UPGRADE_FROM_v2_SQL \
"DROP TABLE idmap_cache;" \
"DROP TABLE name_cache;" \
CACHE_INSTALL_SQL
#define CACHE_VERSION 3
#define TABLE_NAMERULES_v1 \
"CREATE TABLE namerules (" \
" is_user INTEGER NOT NULL," \
" windomain TEXT," \
" winname TEXT NOT NULL," \
" is_nt4 INTEGER NOT NULL," \
" unixname NOT NULL," \
" w2u_order INTEGER," \
" u2w_order INTEGER" \
")"
#define TABLE_NAMERULES_BODY \
"(" \
" is_user INTEGER NOT NULL," \
" is_wuser INTEGER NOT NULL," \
" windomain TEXT," \
" winname_display TEXT NOT NULL," \
" winname TEXT," \
" is_nt4 INTEGER NOT NULL," \
" unixname NOT NULL," \
" w2u_order INTEGER," \
" u2w_order INTEGER" \
")"
#define TABLE_NAMERULES \
"CREATE TABLE namerules " \
TABLE_NAMERULES_BODY
#define INDEX_NAMERULES_W2U_v1 \
"CREATE UNIQUE INDEX namerules_w2u ON namerules" \
" (winname, windomain, is_user, w2u_order)"
#define INDEX_NAMERULES_W2U \
"CREATE UNIQUE INDEX namerules_w2u ON namerules" \
" (winname, windomain, is_user, is_wuser, w2u_order)"
#define INDEX_NAMERULES_U2W \
"CREATE UNIQUE INDEX namerules_u2w ON namerules" \
" (unixname, is_user, u2w_order)"
#define TRIGGER_NAMERULES_TOLOWER_BODY \
"BEGIN " \
" UPDATE namerules SET winname = lower_utf8(winname_display)" \
" WHERE rowid = new.rowid;" \
"END"
#define TRIGGER_NAMERULES_TOLOWER_INSERT \
"CREATE TRIGGER namerules_tolower_name_insert " \
"AFTER INSERT ON namerules " \
TRIGGER_NAMERULES_TOLOWER_BODY
#define TRIGGER_NAMERULES_TOLOWER_UPDATE \
"CREATE TRIGGER namerules_tolower_name_update " \
"AFTER UPDATE ON namerules " \
TRIGGER_NAMERULES_TOLOWER_BODY
#define TRIGGER_NAMERULES_UNIQUE_BODY \
" SELECT CASE (SELECT count(*) FROM namerules AS n" \
" WHERE n.unixname = NEW.unixname AND" \
" n.is_user = NEW.is_user AND" \
" (n.winname != lower(NEW.winname_display) OR" \
" n.windomain != NEW.windomain ) AND" \
" n.u2w_order = NEW.u2w_order AND" \
" n.is_wuser != NEW.is_wuser) > 0" \
" WHEN 1 THEN" \
" raise(ROLLBACK, 'Conflicting w2u namerules')"\
" END; " \
"END"
#define TRIGGER_NAMERULES_UNIQUE_INSERT \
"CREATE TRIGGER namerules_unique_insert " \
"BEFORE INSERT ON namerules " \
"BEGIN " \
TRIGGER_NAMERULES_UNIQUE_BODY
#define TRIGGER_NAMERULES_UNIQUE_UPDATE \
"CREATE TRIGGER namerules_unique_update " \
"BEFORE INSERT ON namerules " \
"BEGIN " \
TRIGGER_NAMERULES_UNIQUE_BODY
#define DB_INSTALL_SQL \
TABLE_NAMERULES ";" \
INDEX_NAMERULES_W2U ";" \
INDEX_NAMERULES_U2W ";" \
TRIGGER_NAMERULES_TOLOWER_INSERT ";" \
TRIGGER_NAMERULES_TOLOWER_UPDATE ";" \
TRIGGER_NAMERULES_UNIQUE_INSERT ";" \
TRIGGER_NAMERULES_UNIQUE_UPDATE ";"
#define DB_VERSION_SQL \
"SELECT CASE (SELECT count(*) FROM sqlite_master) WHEN 0 THEN 0 ELSE " \
"(CASE (SELECT count(*) FROM sqlite_master WHERE " \
"sql = '" TABLE_NAMERULES_v1 "' OR " \
"sql = '" INDEX_NAMERULES_W2U_v1 "' OR " \
"sql = '" INDEX_NAMERULES_U2W "') " \
"WHEN 3 THEN 1 ELSE "\
"(CASE (SELECT count(*) FROM sqlite_master WHERE " \
"sql = '" TABLE_NAMERULES "' OR " \
"sql = '" INDEX_NAMERULES_W2U "' OR " \
"sql = '" INDEX_NAMERULES_U2W "' OR " \
"sql = '" TRIGGER_NAMERULES_TOLOWER_INSERT "' OR " \
"sql = '" TRIGGER_NAMERULES_TOLOWER_UPDATE "' OR " \
"sql = \"" TRIGGER_NAMERULES_UNIQUE_INSERT "\" OR " \
"sql = \"" TRIGGER_NAMERULES_UNIQUE_UPDATE "\") " \
"WHEN 7 THEN 2 ELSE -1 END) END) END AS version;"
/* SQL for upgrading an existing name rules DB. Includes DB_INSTALL_SQL */
#define DB_UPGRADE_FROM_v1_SQL \
"CREATE TABLE namerules_new " TABLE_NAMERULES_BODY ";" \
"INSERT INTO namerules_new SELECT is_user, is_user, windomain, " \
"winname, winname, is_nt4, unixname, w2u_order, u2w_order " \
"FROM namerules;" \
"DROP TABLE namerules;" \
DB_INSTALL_SQL \
"INSERT INTO namerules SELECT * FROM namerules_new;" \
"DROP TABLE namerules_new;"
#define DB_VERSION 2
#ifdef __cplusplus
}
#endif
#endif /* _SCHEMA_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
*/
/*
* Service routines
*/
#include "idmapd.h"
#include "idmap_priv.h"
#include "nldaputils.h"
#include <signal.h>
#include <thread.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sid.h>
#include <ucred.h>
#include <pwd.h>
#include <auth_attr.h>
#include <secdb.h>
#include <sys/u8_textprep.h>
#include <note.h>
#define _VALIDATE_LIST_CB_DATA(col, val, siz)\
retcode = validate_list_cb_data(cb_data, argc, argv, col,\
(uchar_t **)val, siz);\
if (retcode == IDMAP_NEXT) {\
result->retcode = IDMAP_NEXT;\
return (0);\
} else if (retcode < 0) {\
result->retcode = retcode;\
return (1);\
}
#define PROCESS_LIST_SVC_SQL(rcode, db, dbname, sql, limit, flag, cb, res, len)\
rcode = process_list_svc_sql(db, dbname, sql, limit, flag, cb, res);\
if (rcode == IDMAP_ERR_BUSY)\
res->retcode = IDMAP_ERR_BUSY;\
else if (rcode == IDMAP_SUCCESS && len == 0)\
res->retcode = IDMAP_ERR_NOTFOUND;
#define STRDUP_OR_FAIL(to, from) \
if ((from) == NULL) \
to = NULL; \
else { \
if ((to = strdup(from)) == NULL) \
return (1); \
}
#define STRDUP_CHECK(to, from) \
if ((from) != NULL) { \
to = strdup(from); \
if (to == NULL) { \
result->retcode = IDMAP_ERR_MEMORY; \
goto out; \
} \
}
/* ARGSUSED */
bool_t
idmap_null_1_svc(void *result, struct svc_req *rqstp)
{
return (TRUE);
}
/*
* RPC layer allocates empty strings to replace NULL char *.
* This utility function frees these empty strings.
*/
static
void
sanitize_mapping_request(idmap_mapping *req)
{
if (EMPTY_STRING(req->id1name)) {
free(req->id1name);
req->id1name = NULL;
}
if (EMPTY_STRING(req->id1domain)) {
free(req->id1domain);
req->id1domain = NULL;
}
if (EMPTY_STRING(req->id2name)) {
free(req->id2name);
req->id2name = NULL;
}
if (EMPTY_STRING(req->id2domain)) {
free(req->id2domain);
req->id2domain = NULL;
}
req->direction = _IDMAP_F_DONE;
}
static
int
validate_mapped_id_by_name_req(idmap_mapping *req)
{
int e;
if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1))
return (IDMAP_SUCCESS);
if (IS_ID_SID(req->id1)) {
if (!EMPTY_STRING(req->id1name) &&
u8_validate(req->id1name, strlen(req->id1name),
NULL, U8_VALIDATE_ENTIRE, &e) < 0)
return (IDMAP_ERR_BAD_UTF8);
if (!EMPTY_STRING(req->id1domain) &&
u8_validate(req->id1domain, strlen(req->id1domain),
NULL, U8_VALIDATE_ENTIRE, &e) < 0)
return (IDMAP_ERR_BAD_UTF8);
}
return (IDMAP_SUCCESS);
}
static
int
validate_rule(idmap_namerule *rule)
{
int e;
if (!EMPTY_STRING(rule->winname) &&
u8_validate(rule->winname, strlen(rule->winname),
NULL, U8_VALIDATE_ENTIRE, &e) < 0)
return (IDMAP_ERR_BAD_UTF8);
if (!EMPTY_STRING(rule->windomain) &&
u8_validate(rule->windomain, strlen(rule->windomain),
NULL, U8_VALIDATE_ENTIRE, &e) < 0)
return (IDMAP_ERR_BAD_UTF8);
return (IDMAP_SUCCESS);
}
static
bool_t
validate_rules(idmap_update_batch *batch)
{
idmap_update_op *up;
int i;
for (i = 0; i < batch->idmap_update_batch_len; i++) {
up = &(batch->idmap_update_batch_val[i]);
if (validate_rule(&(up->idmap_update_op_u.rule))
!= IDMAP_SUCCESS)
return (IDMAP_ERR_BAD_UTF8);
}
return (IDMAP_SUCCESS);
}
/* ARGSUSED */
bool_t
idmap_get_mapped_ids_1_svc(idmap_mapping_batch batch,
idmap_ids_res *result, struct svc_req *rqstp)
{
sqlite *cache = NULL, *db = NULL;
lookup_state_t state;
idmap_retcode retcode;
uint_t i;
idmap_mapping *req;
idmap_id_res *res;
boolean_t any_tracing;
int rc;
/* Init */
(void) memset(result, 0, sizeof (*result));
(void) memset(&state, 0, sizeof (state));
/* Return success if nothing was requested */
if (batch.idmap_mapping_batch_len < 1)
goto out;
/* Get cache handle */
result->retcode = get_cache_handle(&cache);
if (result->retcode != IDMAP_SUCCESS)
goto out;
state.cache = cache;
/* Get db handle */
result->retcode = get_db_handle(&db);
if (result->retcode != IDMAP_SUCCESS)
goto out;
state.db = db;
/* Allocate result array */
result->ids.ids_val = calloc(batch.idmap_mapping_batch_len,
sizeof (idmap_id_res));
if (result->ids.ids_val == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
result->retcode = IDMAP_ERR_MEMORY;
goto out;
}
result->ids.ids_len = batch.idmap_mapping_batch_len;
/* Allocate hash table to check for duplicate sids */
state.sid_history = calloc(batch.idmap_mapping_batch_len,
sizeof (*state.sid_history));
if (state.sid_history == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
result->retcode = IDMAP_ERR_MEMORY;
goto out;
}
state.sid_history_size = batch.idmap_mapping_batch_len;
for (i = 0; i < state.sid_history_size; i++) {
state.sid_history[i].key = state.sid_history_size;
state.sid_history[i].next = state.sid_history_size;
}
state.batch = &batch;
state.result = result;
/* Get directory-based name mapping info */
result->retcode = load_cfg_in_state(&state);
if (result->retcode != IDMAP_SUCCESS)
goto out;
/* Init our 'done' flags */
state.sid2pid_done = state.pid2sid_done = TRUE;
any_tracing = B_FALSE;
/* First stage */
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
if (TRACING(req))
any_tracing = B_TRUE;
state.curpos = i;
(void) sanitize_mapping_request(req);
TRACE(req, res, "Start mapping");
if (IS_ID_SID(req->id1)) {
retcode = sid2pid_first_pass(
&state,
req,
res);
} else if (IS_ID_UID(req->id1)) {
retcode = pid2sid_first_pass(
&state,
req,
res, 1);
} else if (IS_ID_GID(req->id1)) {
retcode = pid2sid_first_pass(
&state,
req,
res, 0);
} else {
res->retcode = IDMAP_ERR_IDTYPE;
continue;
}
if (IDMAP_FATAL_ERROR(retcode)) {
result->retcode = retcode;
goto out;
}
}
/* Check if we are done */
if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
goto out;
/*
* native LDAP lookups:
* pid2sid:
* - nldap or mixed mode. Lookup nldap by pid or unixname to get
* winname.
* sid2pid:
* - nldap mode. Got winname and sid (either given or found in
* name_cache). Lookup nldap by winname to get pid and
* unixname.
*/
if (state.nldap_nqueries) {
retcode = nldap_lookup_batch(&state, &batch, result);
if (IDMAP_FATAL_ERROR(retcode)) {
TRACE(req, res, "Native LDAP lookup error=%d", retcode);
result->retcode = retcode;
goto out;
}
if (any_tracing) {
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
res = &result->ids.ids_val[i];
req = &batch.idmap_mapping_batch_val[i];
if (IDMAP_ERROR(res->retcode)) {
TRACE(req, res,
"Native LDAP lookup error=%d",
res->retcode);
} else {
TRACE(req, res, "Native LDAP lookup");
}
}
}
}
/*
* AD lookups:
* pid2sid:
* - nldap or mixed mode. Got winname from nldap lookup.
* winname2sid could not be resolved locally. Lookup AD
* by winname to get sid.
* - ad mode. Got unixname. Lookup AD by unixname to get
* winname and sid.
* sid2pid:
* - ad or mixed mode. Lookup AD by sid or winname to get
* winname, sid and unixname.
* - any mode. Got either sid or winname but not both. Lookup
* AD by sid or winname to get winname, sid.
*/
if (state.ad_nqueries) {
retcode = ad_lookup_batch(&state, &batch, result);
if (IDMAP_FATAL_ERROR(retcode)) {
TRACE(req, res, "AD lookup error=%d", retcode);
result->retcode = retcode;
goto out;
}
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
res = &result->ids.ids_val[i];
req = &batch.idmap_mapping_batch_val[i];
if (res->retcode == IDMAP_ERR_DOMAIN_NOTFOUND &&
req->id1.idmap_id_u.sid.prefix != NULL &&
req->id1name != NULL) {
/*
* If AD lookup failed Domain Not Found but
* we have a winname and SID, it means that
* - LSA succeeded
* - it's a request a cross-forest trust
* and
* - we were looking for directory-based
* mapping information.
* In that case, we're OK, just go on.
*
* If this seems more convoluted than it
* should be, it is - really, we probably
* shouldn't even be attempting AD lookups
* in this situation, but that's a more
* intricate cleanup that will have to wait
* for later.
*/
res->retcode = IDMAP_SUCCESS;
TRACE(req, res,
"AD lookup - domain not found (ignored)");
continue;
}
}
}
/*
* native LDAP lookups:
* sid2pid:
* - nldap mode. Got winname and sid from AD lookup. Lookup nldap
* by winname to get pid and unixname.
*/
if (state.nldap_nqueries) {
retcode = nldap_lookup_batch(&state, &batch, result);
if (IDMAP_FATAL_ERROR(retcode)) {
TRACE(req, res, "Native LDAP lookup error=%d", retcode);
result->retcode = retcode;
goto out;
}
if (any_tracing) {
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
res = &result->ids.ids_val[i];
req = &batch.idmap_mapping_batch_val[i];
TRACE(req, res, "Native LDAP lookup");
}
}
}
/* Reset 'done' flags */
state.sid2pid_done = state.pid2sid_done = TRUE;
/* Second stage */
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
state.curpos = i;
if (IS_ID_SID(req->id1)) {
retcode = sid2pid_second_pass(
&state,
req,
res);
} else if (IS_ID_UID(req->id1)) {
retcode = pid2sid_second_pass(
&state,
req,
res, 1);
} else if (IS_ID_GID(req->id1)) {
retcode = pid2sid_second_pass(
&state,
req,
res, 0);
} else {
/* First stage has already set the error */
continue;
}
if (IDMAP_FATAL_ERROR(retcode)) {
result->retcode = retcode;
goto out;
}
}
/* Check if we are done */
if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
goto out;
/* Reset our 'done' flags */
state.sid2pid_done = state.pid2sid_done = TRUE;
/* Update cache in a single transaction */
rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, "BEGIN TRANSACTION;");
if (rc != IDMAP_SUCCESS)
goto out;
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
state.curpos = i;
if (IS_ID_SID(req->id1)) {
(void) update_cache_sid2pid(
&state,
req,
res);
} else if ((IS_ID_UID(req->id1)) ||
(IS_ID_GID(req->id1))) {
(void) update_cache_pid2sid(
&state,
req,
res);
}
}
/* Commit if we have at least one successful update */
if (state.sid2pid_done == FALSE || state.pid2sid_done == FALSE)
rc = sql_exec_no_cb(cache, IDMAP_CACHENAME,
"COMMIT TRANSACTION;");
else
rc = sql_exec_no_cb(cache, IDMAP_CACHENAME,
"END TRANSACTION;");
if (rc != IDMAP_SUCCESS) {
/* If (eg.) commit fails, make sure to close the TX. */
(void) sql_exec_no_cb(cache, IDMAP_CACHENAME,
"ROLLBACK TRANSACTION;");
}
out:
if (rc == IDMAP_ERR_DB || result->retcode == IDMAP_ERR_DB)
kill_cache_handle(cache);
cleanup_lookup_state(&state);
if (IDMAP_ERROR(result->retcode)) {
if (any_tracing) {
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
TRACE(req, res,
"Failure code %d", result->retcode);
}
}
xdr_free(xdr_idmap_ids_res, (caddr_t)result);
result->ids.ids_len = 0;
result->ids.ids_val = NULL;
} else {
if (any_tracing) {
for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
TRACE(req, res, "Done");
}
}
}
result->retcode = idmap_stat4prot(result->retcode);
for (i = 0; i < result->ids.ids_len; i++) {
req = &batch.idmap_mapping_batch_val[i];
res = &result->ids.ids_val[i];
if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO) &&
res->retcode == IDMAP_SUCCESS)
idmap_how_clear(&res->info.how);
}
return (TRUE);
}
/* ARGSUSED */
static
int
list_mappings_cb(void *parg, int argc, char **argv, char **colnames)
{
list_cb_data_t *cb_data;
char *str;
idmap_mappings_res *result;
idmap_retcode retcode;
int w2u, u2w;
char *end;
static int validated_column_names = 0;
idmap_how *how;
cb_data = (list_cb_data_t *)parg;
if (!validated_column_names) {
assert(strcmp(colnames[0], "rowid") == 0);
assert(strcmp(colnames[1], "sidprefix") == 0);
assert(strcmp(colnames[2], "rid") == 0);
assert(strcmp(colnames[3], "pid") == 0);
assert(strcmp(colnames[4], "w2u") == 0);
assert(strcmp(colnames[5], "u2w") == 0);
assert(strcmp(colnames[6], "windomain") == 0);
assert(strcmp(colnames[7], "canon_winname") == 0);
assert(strcmp(colnames[8], "unixname") == 0);
assert(strcmp(colnames[9], "is_user") == 0);
assert(strcmp(colnames[10], "is_wuser") == 0);
assert(strcmp(colnames[11], "map_type") == 0);
assert(strcmp(colnames[12], "map_dn") == 0);
assert(strcmp(colnames[13], "map_attr") == 0);
assert(strcmp(colnames[14], "map_value") == 0);
assert(strcmp(colnames[15], "map_windomain") == 0);
assert(strcmp(colnames[16], "map_winname") == 0);
assert(strcmp(colnames[17], "map_unixname") == 0);
assert(strcmp(colnames[18], "map_is_nt4") == 0);
validated_column_names = 1;
}
result = (idmap_mappings_res *)cb_data->result;
_VALIDATE_LIST_CB_DATA(19, &result->mappings.mappings_val,
sizeof (idmap_mapping));
result->mappings.mappings_len++;
if ((str = strdup(argv[1])) == NULL)
return (1);
result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.prefix =
str;
result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.rid =
strtoul(argv[2], &end, 10);
result->mappings.mappings_val[cb_data->next].id1.idtype =
strtol(argv[10], &end, 10) ? IDMAP_USID : IDMAP_GSID;
result->mappings.mappings_val[cb_data->next].id2.idmap_id_u.uid =
strtoul(argv[3], &end, 10);
result->mappings.mappings_val[cb_data->next].id2.idtype =
strtol(argv[9], &end, 10) ? IDMAP_UID : IDMAP_GID;
w2u = argv[4] ? strtol(argv[4], &end, 10) : 0;
u2w = argv[5] ? strtol(argv[5], &end, 10) : 0;
if (w2u > 0 && u2w == 0)
result->mappings.mappings_val[cb_data->next].direction =
IDMAP_DIRECTION_W2U;
else if (w2u == 0 && u2w > 0)
result->mappings.mappings_val[cb_data->next].direction =
IDMAP_DIRECTION_U2W;
else
result->mappings.mappings_val[cb_data->next].direction =
IDMAP_DIRECTION_BI;
STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1domain,
argv[6]);
STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1name,
argv[7]);
STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id2name,
argv[8]);
if (cb_data->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
how = &result->mappings.mappings_val[cb_data->next].info.how;
how->map_type = strtoul(argv[11], &end, 10);
switch (how->map_type) {
case IDMAP_MAP_TYPE_DS_AD:
how->idmap_how_u.ad.dn =
strdup(argv[12]);
how->idmap_how_u.ad.attr =
strdup(argv[13]);
how->idmap_how_u.ad.value =
strdup(argv[14]);
break;
case IDMAP_MAP_TYPE_DS_NLDAP:
how->idmap_how_u.nldap.dn =
strdup(argv[12]);
how->idmap_how_u.nldap.attr =
strdup(argv[13]);
how->idmap_how_u.nldap.value =
strdup(argv[14]);
break;
case IDMAP_MAP_TYPE_RULE_BASED:
how->idmap_how_u.rule.windomain =
strdup(argv[15]);
how->idmap_how_u.rule.winname =
strdup(argv[16]);
how->idmap_how_u.rule.unixname =
strdup(argv[17]);
how->idmap_how_u.rule.is_nt4 =
strtoul(argv[18], &end, 10);
how->idmap_how_u.rule.is_user =
strtol(argv[9], &end, 10);
how->idmap_how_u.rule.is_wuser =
strtol(argv[10], &end, 10);
break;
case IDMAP_MAP_TYPE_EPHEMERAL:
break;
case IDMAP_MAP_TYPE_LOCAL_SID:
break;
case IDMAP_MAP_TYPE_IDMU:
how->idmap_how_u.idmu.dn =
strdup(argv[12]);
how->idmap_how_u.idmu.attr =
strdup(argv[13]);
how->idmap_how_u.idmu.value =
strdup(argv[14]);
break;
default:
/* Unknown mapping type */
assert(FALSE);
}
}
result->lastrowid = strtoll(argv[0], &end, 10);
cb_data->next++;
result->retcode = IDMAP_SUCCESS;
return (0);
}
/* ARGSUSED */
bool_t
idmap_list_mappings_1_svc(int64_t lastrowid, uint64_t limit, int32_t flag,
idmap_mappings_res *result, struct svc_req *rqstp)
{
sqlite *cache = NULL;
char lbuf[30], rbuf[30];
uint64_t maxlimit;
idmap_retcode retcode;
char *sql = NULL;
time_t curtime;
(void) memset(result, 0, sizeof (*result));
/* Current time */
errno = 0;
if ((curtime = time(NULL)) == (time_t)-1) {
idmapdlog(LOG_ERR, "Failed to get current time (%s)",
strerror(errno));
retcode = IDMAP_ERR_INTERNAL;
goto out;
}
RDLOCK_CONFIG();
maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
UNLOCK_CONFIG();
/* Get cache handle */
result->retcode = get_cache_handle(&cache);
if (result->retcode != IDMAP_SUCCESS)
goto out;
result->retcode = IDMAP_ERR_INTERNAL;
/* Create LIMIT expression. */
if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
limit = maxlimit;
if (limit > 0)
(void) snprintf(lbuf, sizeof (lbuf),
"LIMIT %" PRIu64, limit + 1ULL);
else
lbuf[0] = '\0';
(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
/*
* Combine all the above into a giant SELECT statement that
* will return the requested mappings
*/
sql = sqlite_mprintf("SELECT rowid, sidprefix, rid, pid, w2u, "
"u2w, windomain, canon_winname, unixname, is_user, is_wuser, "
"map_type, map_dn, map_attr, map_value, map_windomain, "
"map_winname, map_unixname, map_is_nt4 "
"FROM idmap_cache WHERE %s AND "
"(pid >= 2147483648 OR (expiration = 0 OR "
"expiration ISNULL OR expiration > %d)) "
"%s;",
rbuf, curtime, lbuf);
if (sql == NULL) {
result->retcode = IDMAP_ERR_MEMORY;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
/* Execute the SQL statement and update the return buffer */
PROCESS_LIST_SVC_SQL(retcode, cache, IDMAP_CACHENAME, sql, limit,
flag, list_mappings_cb, result, result->mappings.mappings_len);
if (retcode == IDMAP_ERR_DB)
kill_cache_handle(cache);
out:
if (sql)
sqlite_freemem(sql);
if (IDMAP_ERROR(result->retcode))
xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
result->retcode = idmap_stat4prot(result->retcode);
return (TRUE);
}
/* ARGSUSED */
static
int
list_namerules_cb(void *parg, int argc, char **argv, char **colnames)
{
list_cb_data_t *cb_data;
idmap_namerules_res *result;
idmap_retcode retcode;
int w2u_order, u2w_order;
char *end;
static int validated_column_names = 0;
if (!validated_column_names) {
assert(strcmp(colnames[0], "rowid") == 0);
assert(strcmp(colnames[1], "is_user") == 0);
assert(strcmp(colnames[2], "is_wuser") == 0);
assert(strcmp(colnames[3], "windomain") == 0);
assert(strcmp(colnames[4], "winname_display") == 0);
assert(strcmp(colnames[5], "is_nt4") == 0);
assert(strcmp(colnames[6], "unixname") == 0);
assert(strcmp(colnames[7], "w2u_order") == 0);
assert(strcmp(colnames[8], "u2w_order") == 0);
validated_column_names = 1;
}
cb_data = (list_cb_data_t *)parg;
result = (idmap_namerules_res *)cb_data->result;
_VALIDATE_LIST_CB_DATA(9, &result->rules.rules_val,
sizeof (idmap_namerule));
result->rules.rules_len++;
result->rules.rules_val[cb_data->next].is_user =
strtol(argv[1], &end, 10);
result->rules.rules_val[cb_data->next].is_wuser =
strtol(argv[2], &end, 10);
STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].windomain,
argv[3]);
STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].winname,
argv[4]);
result->rules.rules_val[cb_data->next].is_nt4 =
strtol(argv[5], &end, 10);
STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].unixname,
argv[6]);
w2u_order = argv[7] ? strtol(argv[7], &end, 10) : 0;
u2w_order = argv[8] ? strtol(argv[8], &end, 10) : 0;
if (w2u_order > 0 && u2w_order == 0)
result->rules.rules_val[cb_data->next].direction =
IDMAP_DIRECTION_W2U;
else if (w2u_order == 0 && u2w_order > 0)
result->rules.rules_val[cb_data->next].direction =
IDMAP_DIRECTION_U2W;
else
result->rules.rules_val[cb_data->next].direction =
IDMAP_DIRECTION_BI;
result->lastrowid = strtoll(argv[0], &end, 10);
cb_data->next++;
result->retcode = IDMAP_SUCCESS;
return (0);
}
/* ARGSUSED */
bool_t
idmap_list_namerules_1_svc(idmap_namerule rule, uint64_t lastrowid,
uint64_t limit, idmap_namerules_res *result, struct svc_req *rqstp)
{
sqlite *db = NULL;
char lbuf[30], rbuf[30];
char *sql = NULL;
char *expr = NULL;
uint64_t maxlimit;
idmap_retcode retcode;
(void) memset(result, 0, sizeof (*result));
result->retcode = validate_rule(&rule);
if (result->retcode != IDMAP_SUCCESS)
goto out;
RDLOCK_CONFIG();
maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
UNLOCK_CONFIG();
/* Get db handle */
result->retcode = get_db_handle(&db);
if (result->retcode != IDMAP_SUCCESS)
goto out;
result->retcode = gen_sql_expr_from_rule(&rule, &expr);
if (result->retcode != IDMAP_SUCCESS)
goto out;
/* Create LIMIT expression. */
if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
limit = maxlimit;
if (limit > 0)
(void) snprintf(lbuf, sizeof (lbuf),
"LIMIT %" PRIu64, limit + 1ULL);
else
lbuf[0] = '\0';
(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
/*
* Combine all the above into a giant SELECT statement that
* will return the requested rules
*/
sql = sqlite_mprintf("SELECT rowid, is_user, is_wuser, windomain, "
"winname_display, is_nt4, unixname, w2u_order, u2w_order "
"FROM namerules WHERE "
" %s %s %s;",
rbuf, expr, lbuf);
if (sql == NULL) {
result->retcode = IDMAP_ERR_MEMORY;
idmapdlog(LOG_ERR, "Out of memory");
goto out;
}
/* Execute the SQL statement and update the return buffer */
PROCESS_LIST_SVC_SQL(retcode, db, IDMAP_DBNAME, sql, limit,
0, list_namerules_cb, result, result->rules.rules_len);
if (retcode == IDMAP_ERR_DB)
kill_db_handle(db);
out:
if (expr)
sqlite_freemem(expr);
if (sql)
sqlite_freemem(sql);
if (IDMAP_ERROR(result->retcode))
xdr_free(xdr_idmap_namerules_res, (caddr_t)result);
result->retcode = idmap_stat4prot(result->retcode);
return (TRUE);
}
#define IDMAP_RULES_AUTH "solaris.admin.idmap.rules"
static int
verify_rules_auth(struct svc_req *rqstp)
{
ucred_t *uc = NULL;
uid_t uid;
char buf[1024];
struct passwd pwd;
if (svc_getcallerucred(rqstp->rq_xprt, &uc) != 0) {
idmapdlog(LOG_ERR, "svc_getcallerucred failed during "
"authorization (%s)", strerror(errno));
return (-1);
}
uid = ucred_geteuid(uc);
if (uid == (uid_t)-1) {
idmapdlog(LOG_ERR, "ucred_geteuid failed during "
"authorization (%s)", strerror(errno));
ucred_free(uc);
return (-1);
}
if (getpwuid_r(uid, &pwd, buf, sizeof (buf)) == NULL) {
idmapdlog(LOG_ERR, "getpwuid_r(%u) failed during "
"authorization (%s)", uid, strerror(errno));
ucred_free(uc);
return (-1);
}
if (chkauthattr(IDMAP_RULES_AUTH, pwd.pw_name) != 1) {
idmapdlog(LOG_INFO, "%s is not authorized (%s)",
pwd.pw_name, IDMAP_RULES_AUTH);
ucred_free(uc);
return (-1);
}
ucred_free(uc);
return (1);
}
/*
* Meaning of the return values is the following: For retcode ==
* IDMAP_SUCCESS, everything went OK and error_index is
* undefined. Otherwise, error_index >=0 shows the failed batch
* element. errro_index == -1 indicates failure at the beginning,
* error_index == -2 at the end.
*/
/* ARGSUSED */
bool_t
idmap_update_1_svc(idmap_update_batch batch, idmap_update_res *res,
struct svc_req *rqstp)
{
sqlite *db = NULL;
idmap_update_op *up;
int i;
int trans = FALSE;
res->error_index = -1;
(void) memset(&res->error_rule, 0, sizeof (res->error_rule));
(void) memset(&res->conflict_rule, 0, sizeof (res->conflict_rule));
if (verify_rules_auth(rqstp) < 0) {
res->retcode = IDMAP_ERR_PERMISSION_DENIED;
goto out;
}
if (batch.idmap_update_batch_len == 0 ||
batch.idmap_update_batch_val == NULL) {
res->retcode = IDMAP_SUCCESS;
goto out;
}
res->retcode = validate_rules(&batch);
if (res->retcode != IDMAP_SUCCESS)
goto out;
/* Get db handle */
res->retcode = get_db_handle(&db);
if (res->retcode != IDMAP_SUCCESS)
goto out;
res->retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "BEGIN TRANSACTION;");
if (res->retcode != IDMAP_SUCCESS)
goto out;
trans = TRUE;
for (i = 0; i < batch.idmap_update_batch_len; i++) {
up = &batch.idmap_update_batch_val[i];
switch (up->opnum) {
case OP_NONE:
res->retcode = IDMAP_SUCCESS;
break;
case OP_ADD_NAMERULE:
res->retcode = add_namerule(db,
&up->idmap_update_op_u.rule);
break;
case OP_RM_NAMERULE:
res->retcode = rm_namerule(db,
&up->idmap_update_op_u.rule);
break;
case OP_FLUSH_NAMERULES:
res->retcode = flush_namerules(db);
break;
default:
res->retcode = IDMAP_ERR_NOTSUPPORTED;
break;
};
if (res->retcode != IDMAP_SUCCESS) {
res->error_index = i;
if (up->opnum == OP_ADD_NAMERULE ||
up->opnum == OP_RM_NAMERULE) {
idmap_stat r2 =
idmap_namerule_cpy(&res->error_rule,
&up->idmap_update_op_u.rule);
if (r2 != IDMAP_SUCCESS)
res->retcode = r2;
}
goto out;
}
}
out:
if (trans) {
if (res->retcode == IDMAP_SUCCESS) {
res->retcode =
sql_exec_no_cb(db, IDMAP_DBNAME,
"COMMIT TRANSACTION;");
if (res->retcode == IDMAP_SUCCESS) {
/*
* We've updated the rules. Expire the cache
* so that existing mappings will be
* reconsidered.
*/
res->retcode =
idmap_cache_flush(IDMAP_FLUSH_EXPIRE);
} else {
res->error_index = -2;
}
}
else
(void) sql_exec_no_cb(db, IDMAP_DBNAME,
"ROLLBACK TRANSACTION;");
}
if (res->retcode == IDMAP_ERR_DB)
kill_db_handle(db);
res->retcode = idmap_stat4prot(res->retcode);
return (TRUE);
}
static
int
copy_string(char **to, char *from)
{
if (EMPTY_STRING(from)) {
*to = NULL;
} else {
*to = strdup(from);
if (*to == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
return (IDMAP_ERR_MEMORY);
}
}
return (IDMAP_SUCCESS);
}
static
int
copy_id(idmap_id *to, idmap_id *from)
{
(void) memset(to, 0, sizeof (*to));
to->idtype = from->idtype;
if (IS_ID_SID(*from)) {
idmap_retcode retcode;
to->idmap_id_u.sid.rid = from->idmap_id_u.sid.rid;
retcode = copy_string(&to->idmap_id_u.sid.prefix,
from->idmap_id_u.sid.prefix);
return (retcode);
} else {
to->idmap_id_u.uid = from->idmap_id_u.uid;
return (IDMAP_SUCCESS);
}
}
static
int
copy_mapping(idmap_mapping *mapping, idmap_mapping *request)
{
idmap_retcode retcode;
(void) memset(mapping, 0, sizeof (*mapping));
mapping->flag = request->flag;
mapping->direction = _IDMAP_F_DONE;
retcode = copy_id(&mapping->id1, &request->id1);
if (retcode != IDMAP_SUCCESS)
goto errout;
retcode = copy_string(&mapping->id1domain, request->id1domain);
if (retcode != IDMAP_SUCCESS)
goto errout;
retcode = copy_string(&mapping->id1name, request->id1name);
if (retcode != IDMAP_SUCCESS)
goto errout;
retcode = copy_id(&mapping->id2, &request->id2);
if (retcode != IDMAP_SUCCESS)
goto errout;
retcode = copy_string(&mapping->id2domain, request->id2domain);
if (retcode != IDMAP_SUCCESS)
goto errout;
retcode = copy_string(&mapping->id2name, request->id2name);
if (retcode != IDMAP_SUCCESS)
goto errout;
return (IDMAP_SUCCESS);
errout:
if (IS_ID_SID(mapping->id1))
free(mapping->id1.idmap_id_u.sid.prefix);
free(mapping->id1domain);
free(mapping->id1name);
if (IS_ID_SID(mapping->id2))
free(mapping->id2.idmap_id_u.sid.prefix);
free(mapping->id2domain);
free(mapping->id2name);
(void) memset(mapping, 0, sizeof (*mapping));
return (retcode);
}
/* ARGSUSED */
bool_t
idmap_get_mapped_id_by_name_1_svc(idmap_mapping request,
idmap_mappings_res *result, struct svc_req *rqstp)
{
idmap_mapping_batch batch_request;
idmap_ids_res batch_result;
idmap_mapping *map;
/* Clear out things we might want to xdr_free on error */
(void) memset(&batch_result, 0, sizeof (batch_result));
(void) memset(result, 0, sizeof (*result));
result->retcode = validate_mapped_id_by_name_req(&request);
if (result->retcode != IDMAP_SUCCESS)
goto out;
/*
* Copy the request. We need to modify it, and
* what we have is a shallow copy. Freeing pointers from
* our copy will lead to problems, since the RPC framework
* has its own copy of those pointers. Besides, we need
* a copy to return.
*/
map = calloc(1, sizeof (idmap_mapping));
if (map == NULL) {
idmapdlog(LOG_ERR, "Out of memory");
result->retcode = IDMAP_ERR_MEMORY;
goto out;
}
/*
* Set up to return the filled-in mapping structure.
* Note that we xdr_free result on error, and that'll take
* care of freeing the mapping structure.
*/
result->mappings.mappings_val = map;
result->mappings.mappings_len = 1;
result->retcode = copy_mapping(map, &request);
if (result->retcode != IDMAP_SUCCESS)
goto out;
/* Set up for the request to the batch API */
batch_request.idmap_mapping_batch_val = map;
batch_request.idmap_mapping_batch_len = 1;
/* Do the real work. */
(void) idmap_get_mapped_ids_1_svc(batch_request,
&batch_result, rqstp);
/* Copy what we need out of the batch response */
if (batch_result.retcode != IDMAP_SUCCESS) {
result->retcode = batch_result.retcode;
goto out;
}
result->retcode = copy_id(&map->id2, &batch_result.ids.ids_val[0].id);
if (result->retcode != IDMAP_SUCCESS)
goto out;
map->direction = batch_result.ids.ids_val[0].direction;
result->retcode = batch_result.ids.ids_val[0].retcode;
idmap_info_mov(&map->info, &batch_result.ids.ids_val[0].info);
out:
if (IDMAP_FATAL_ERROR(result->retcode)) {
xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
result->mappings.mappings_len = 0;
result->mappings.mappings_val = NULL;
}
result->retcode = idmap_stat4prot(result->retcode);
xdr_free(xdr_idmap_ids_res, (char *)&batch_result);
return (TRUE);
}
/* ARGSUSED */
bool_t
idmap_get_prop_1_svc(idmap_prop_type request,
idmap_prop_res *result, struct svc_req *rqstp)
{
idmap_pg_config_t *pgcfg;
/* Init */
(void) memset(result, 0, sizeof (*result));
result->retcode = IDMAP_SUCCESS;
result->value.prop = request;
RDLOCK_CONFIG();
/* Just shortcuts: */
pgcfg = &_idmapdstate.cfg->pgcfg;
switch (request) {
case PROP_LIST_SIZE_LIMIT:
result->value.idmap_prop_val_u.intval = pgcfg->list_size_limit;
result->auto_discovered = FALSE;
break;
case PROP_DEFAULT_DOMAIN:
result->auto_discovered = FALSE;
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->default_domain);
break;
case PROP_DOMAIN_NAME:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->domain_name);
result->auto_discovered =
pgcfg->domain_name_auto_disc;
break;
case PROP_MACHINE_SID:
result->auto_discovered = FALSE;
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->machine_sid);
break;
case PROP_DOMAIN_CONTROLLER:
if (pgcfg->domain_controller != NULL) {
(void) memcpy(&result->value.idmap_prop_val_u.dsval,
pgcfg->domain_controller,
sizeof (idmap_ad_disc_ds_t));
}
result->auto_discovered = pgcfg->domain_controller_auto_disc;
break;
case PROP_FOREST_NAME:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->forest_name);
result->auto_discovered = pgcfg->forest_name_auto_disc;
break;
case PROP_SITE_NAME:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->site_name);
result->auto_discovered = pgcfg->site_name_auto_disc;
break;
case PROP_GLOBAL_CATALOG:
if (pgcfg->global_catalog != NULL) {
(void) memcpy(&result->value.idmap_prop_val_u.dsval,
pgcfg->global_catalog, sizeof (idmap_ad_disc_ds_t));
}
result->auto_discovered = pgcfg->global_catalog_auto_disc;
break;
case PROP_AD_UNIXUSER_ATTR:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->ad_unixuser_attr);
result->auto_discovered = FALSE;
break;
case PROP_AD_UNIXGROUP_ATTR:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->ad_unixgroup_attr);
result->auto_discovered = FALSE;
break;
case PROP_NLDAP_WINNAME_ATTR:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
pgcfg->nldap_winname_attr);
result->auto_discovered = FALSE;
break;
case PROP_DIRECTORY_BASED_MAPPING:
STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
enum_lookup(pgcfg->directory_based_mapping,
directory_mapping_map));
result->auto_discovered = FALSE;
break;
default:
result->retcode = IDMAP_ERR_PROP_UNKNOWN;
break;
}
out:
UNLOCK_CONFIG();
if (IDMAP_FATAL_ERROR(result->retcode)) {
xdr_free(xdr_idmap_prop_res, (caddr_t)result);
result->value.prop = PROP_UNKNOWN;
}
result->retcode = idmap_stat4prot(result->retcode);
return (TRUE);
}
int
idmap_flush_1_svc(
idmap_flush_op op,
idmap_retcode *result,
struct svc_req *rqstp)
{
NOTE(ARGUNUSED(rqstp))
if (verify_rules_auth(rqstp) < 0) {
*result = IDMAP_ERR_PERMISSION_DENIED;
return (TRUE);
}
*result = idmap_cache_flush(op);
return (TRUE);
}
/* ARGSUSED */
int
idmap_prog_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result,
caddr_t result)
{
xdr_free(xdr_result, result);
return (TRUE);
}
/*
* This function is called by rpc_svc.c when it encounters an error.
*/
NOTE(PRINTFLIKE(1))
void
idmap_rpc_msgout(const char *fmt, ...)
{
va_list va;
char buf[1000];
va_start(va, fmt);
(void) vsnprintf(buf, sizeof (buf), fmt, va);
va_end(va);
idmapdlog(LOG_ERR, "idmap RPC: %s", buf);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Information about well-known (builtin) names, and functions to retrieve
* information about them.
*/
#include <assert.h>
#include <string.h>
#include <libuutil.h>
#include "idmapd.h"
/*
* Table for well-known SIDs.
*
* Background:
*
* Some of the well-known principals are stored under:
* cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
* They belong to objectClass "foreignSecurityPrincipal". They don't have
* "samAccountName" nor "userPrincipalName" attributes. Their names are
* available in "cn" and "name" attributes. Some of these principals have a
* second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
* these duplicate entries have the stringified SID in the "name" and "cn"
* attributes instead of the actual name.
*
* Those of the form S-1-5-32-X are Builtin groups and are stored in the
* cn=builtin container (except, Power Users which is not stored in AD)
*
* These principals are and will remain constant. Therefore doing AD lookups
* provides no benefit. Also, using hard-coded table (and thus avoiding AD
* lookup) improves performance and avoids additional complexity in the
* adutils.c code. Moreover these SIDs can be used when no Active Directory
* is available (such as the CIFS server's "workgroup" mode).
*
* Notes:
* 1. Currently we don't support localization of well-known SID names,
* unlike Windows.
*
* 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
* here. AD does have normal user/group objects for these objects and
* can be looked up using the existing AD lookup code.
*
* 3. See comments above lookup_wksids_sid2pid() for more information
* on how we lookup the wksids table.
*
* 4. If this table contains two entries for a particular Windows name,
* so as to offer both UID and GID mappings, the preferred mapping (the
* one that matches Windows usage) must be listed first. That is the
* entry that will be used when the caller specifies IDMAP_POSIXID
* ("don't care") as the target.
*
* Entries here come from KB243330, MS-LSAT, and
* http://technet.microsoft.com/en-us/library/cc755854.aspx
* http://technet.microsoft.com/en-us/library/cc755925.aspx
* http://msdn.microsoft.com/en-us/library/cc980032(PROT.10).aspx
*/
static wksids_table_t wksids[] = {
/* S-1-0 Null Authority */
{"S-1-0", 0, "", "Nobody", 1, IDMAP_SENTINEL_PID, -1, 1},
/* S-1-1 World Authority */
{"S-1-1", 0, "", "Everyone", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-2 Local Authority */
{"S-1-2", 0, "", "Local", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-2", 1, "", "Console Logon", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-3 Creator Authority */
{"S-1-3", 0, "", "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
{"S-1-3", 1, "", "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
{"S-1-3", 2, "", "Creator Owner Server", 1, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-3", 3, "", "Creator Group Server", 0, IDMAP_SENTINEL_PID, -1, 1},
{"S-1-3", 4, "", "Owner Rights", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-4 Non-unique Authority */
/* S-1-5 NT Authority */
{"S-1-5", 1, "", "Dialup", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 2, "", "Network", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 3, "", "Batch", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 4, "", "Interactive", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-5-5-X-Y Logon Session */
{"S-1-5", 6, "", "Service", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 7, "", "Anonymous Logon", 0, GID_NOBODY, 0, 0},
{"S-1-5", 7, "", "Anonymous Logon", 0, UID_NOBODY, 1, 0},
{"S-1-5", 8, "", "Proxy", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 9, "", "Enterprise Domain Controllers", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 10, "", "Self", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 11, "", "Authenticated Users", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 12, "", "Restricted", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 13, "", "Terminal Server Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 14, "", "Remote Interactive Logon", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 15, "", "This Organization", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 17, "", "IUSR", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 18, "", "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
{"S-1-5", 19, "", "Local Service", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 20, "", "Network Service", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-5-21-<domain> Machine-local definitions */
{NULL, 498, NULL, "Enterprise Read-only Domain Controllers", 0,
IDMAP_SENTINEL_PID, -1, -1},
{NULL, 500, NULL, "Administrator", 1, IDMAP_SENTINEL_PID, 1, -1},
{NULL, 501, NULL, "Guest", 1, IDMAP_SENTINEL_PID, 1, -1},
{NULL, 502, NULL, "KRBTGT", 1, IDMAP_SENTINEL_PID, 1, -1},
{NULL, 512, NULL, "Domain Admins", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 513, NULL, "Domain Users", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 514, NULL, "Domain Guests", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 515, NULL, "Domain Computers", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 516, NULL, "Domain Controllers", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 517, NULL, "Cert Publishers", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 518, NULL, "Schema Admins", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 519, NULL, "Enterprise Admins", 0, IDMAP_SENTINEL_PID, -1, -1},
{NULL, 520, NULL, "Global Policy Creator Owners", 0,
IDMAP_SENTINEL_PID, -1, -1},
{NULL, 533, NULL, "RAS and IAS Servers", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-5-32 BUILTIN */
{"S-1-5-32", 544, "BUILTIN", "Administrators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 545, "BUILTIN", "Users", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 546, "BUILTIN", "Guests", 0, IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 547, "BUILTIN", "Power Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 548, "BUILTIN", "Account Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 549, "BUILTIN", "Server Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 550, "BUILTIN", "Print Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 551, "BUILTIN", "Backup Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 552, "BUILTIN", "Replicator", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 554, "BUILTIN", "Pre-Windows 2000 Compatible Access", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 555, "BUILTIN", "Remote Desktop Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 556, "BUILTIN", "Network Configuration Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 557, "BUILTIN", "Incoming Forest Trust Builders", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 558, "BUILTIN", "Performance Monitor Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 559, "BUILTIN", "Performance Log Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 560, "BUILTIN", "Windows Authorization Access Group", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 561, "BUILTIN", "Terminal Server License Servers", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 562, "BUILTIN", "Distributed COM Users", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 568, "BUILTIN", "IIS_IUSRS", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 569, "BUILTIN", "Cryptographic Operators", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 573, "BUILTIN", "Event Log Readers", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-32", 574, "BUILTIN", "Certificate Service DCOM Access", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5", 33, "", "Write Restricted", 0, IDMAP_SENTINEL_PID, -1, -1},
/* S-1-5-64 NT Authority */
{"S-1-5-64", 10, "", "NTLM Authentication", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-64", 14, "", "SChannel Authentication", 0,
IDMAP_SENTINEL_PID, -1, -1},
{"S-1-5-64", 21, "", "Digest Authentication", 0,
IDMAP_SENTINEL_PID, -1, -1},
/* S-1-5-80-a-b-c-d NT Service */
{"S-1-5", 1000, "", "Other Organization", 0,
IDMAP_SENTINEL_PID, -1, -1},
/* S-1-7 Internet$ */
/*
* S-1-16 Mandatory Label
* S-1-16-0 Untrusted Mandatory Level
* S-1-16-4096 Low Mandatory Level
* S-1-16-8192 Medium Mandatory Level
* S-1-16-8448 Medium Plus Mandatory Level
* S-1-16-12288 High Mandatory Level
* S-1-16-16384 System Mandatory Level
* S-1-16-20480 Protected Process Mandatory Level
*/
};
/*
* Find a wksid entry for the specified Windows name and domain, of the
* specified type.
*
* Ignore entries intended only for U2W use.
*/
const
wksids_table_t *
find_wksid_by_name(const char *name, const char *domain, idmap_id_type type)
{
int i;
RDLOCK_CONFIG();
int len = strlen(_idmapdstate.hostname);
char my_host_name[len + 1];
(void) strcpy(my_host_name, _idmapdstate.hostname);
UNLOCK_CONFIG();
for (i = 0; i < UU_NELEM(wksids); i++) {
/* Check to see if this entry yields the desired type */
switch (type) {
case IDMAP_UID:
if (wksids[i].is_user == 0)
continue;
break;
case IDMAP_GID:
if (wksids[i].is_user == 1)
continue;
break;
case IDMAP_POSIXID:
break;
default:
assert(FALSE);
}
if (strcasecmp(wksids[i].winname, name) != 0)
continue;
if (!EMPTY_STRING(domain)) {
const char *dom;
if (wksids[i].domain != NULL) {
dom = wksids[i].domain;
} else {
dom = my_host_name;
}
if (strcasecmp(dom, domain) != 0)
continue;
}
/*
* We have a Windows name, so ignore entries that are only
* usable for mapping UNIX->Windows. (Note: the current
* table does not have any such entries.)
*/
if (wksids[i].direction == IDMAP_DIRECTION_U2W)
continue;
return (&wksids[i]);
}
return (NULL);
}
/*
* Find a wksid entry for the specified SID, of the specified type.
*
* Ignore entries intended only for U2W use.
*/
const
wksids_table_t *
find_wksid_by_sid(const char *sid, int rid, idmap_id_type type)
{
int i;
RDLOCK_CONFIG();
int len = strlen(_idmapdstate.cfg->pgcfg.machine_sid);
char my_machine_sid[len + 1];
(void) strcpy(my_machine_sid, _idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
for (i = 0; i < UU_NELEM(wksids); i++) {
int sidcmp;
/* Check to see if this entry yields the desired type */
switch (type) {
case IDMAP_UID:
if (wksids[i].is_user == 0)
continue;
break;
case IDMAP_GID:
if (wksids[i].is_user == 1)
continue;
break;
case IDMAP_POSIXID:
break;
default:
assert(FALSE);
}
if (wksids[i].sidprefix != NULL) {
sidcmp = strcasecmp(wksids[i].sidprefix, sid);
} else {
sidcmp = strcasecmp(my_machine_sid, sid);
}
if (sidcmp != 0)
continue;
if (wksids[i].rid != rid)
continue;
/*
* We have a SID, so ignore entries that are only usable
* for mapping UNIX->Windows. (Note: the current table
* does not have any such entries.)
*/
if (wksids[i].direction == IDMAP_DIRECTION_U2W)
continue;
return (&wksids[i]);
}
return (NULL);
}
/*
* Find a wksid entry for the specified pid, of the specified type.
* Ignore entries that do not specify U2W mappings.
*/
const
wksids_table_t *
find_wksid_by_pid(uid_t pid, int is_user)
{
int i;
if (pid == IDMAP_SENTINEL_PID)
return (NULL);
for (i = 0; i < UU_NELEM(wksids); i++) {
if (wksids[i].pid == pid &&
wksids[i].is_user == is_user &&
(wksids[i].direction == IDMAP_DIRECTION_BI ||
wksids[i].direction == IDMAP_DIRECTION_U2W)) {
return (&wksids[i]);
}
}
return (NULL);
}
/*
* It is probably a bug that both this and find_wksid_by_sid exist,
* but for now the distinction is primarily that one takes {machinesid,rid}
* and the other takes a full SID.
*/
const
wksids_table_t *
find_wk_by_sid(char *sid)
{
int i;
RDLOCK_CONFIG();
int len = strlen(_idmapdstate.cfg->pgcfg.machine_sid);
char my_machine_sid[len + 1];
(void) strcpy(my_machine_sid, _idmapdstate.cfg->pgcfg.machine_sid);
UNLOCK_CONFIG();
for (i = 0; i < UU_NELEM(wksids); i++) {
int len;
const char *prefix;
char *p;
unsigned long rid;
if (wksids[i].sidprefix == NULL)
prefix = my_machine_sid;
else
prefix = wksids[i].sidprefix;
len = strlen(prefix);
/*
* Check to see whether the SID we're looking for starts
* with this prefix, then a -, then a single RID, and it's
* the right RID.
*/
if (strncasecmp(sid, prefix, len) != 0)
continue;
if (sid[len] != '-')
continue;
rid = strtoul(sid + len + 1, &p, 10);
if (*p != '\0')
continue;
if (rid != wksids[i].rid)
continue;
return (&wksids[i]);
}
return (NULL);
}
|