File: JNDIRealm.java

package info (click to toggle)
tomcat10 10.1.52-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,900 kB
  • sloc: java: 375,756; xml: 59,410; jsp: 4,741; sh: 1,381; perl: 324; makefile: 25; ansic: 14
file content (3162 lines) | stat: -rw-r--r-- 109,520 bytes parent folder | download | duplicates (3)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.catalina.realm;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.naming.AuthenticationException;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.StartTlsRequest;
import javax.naming.ldap.StartTlsResponse;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import org.apache.catalina.LifecycleException;
import org.apache.tomcat.util.buf.StringUtils;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSName;

/**
 * <p>
 * Implementation of <strong>Realm</strong> that works with a directory server accessed via the Java Naming and
 * Directory Interface (JNDI) APIs. The following constraints are imposed on the data structure in the underlying
 * directory server:
 * </p>
 * <ul>
 * <li>Each user that can be authenticated is represented by an individual element in the top level
 * <code>DirContext</code> that is accessed via the <code>connectionURL</code> property.</li>
 * <li>If a socket connection cannot be made to the <code>connectURL</code> an attempt will be made to use the
 * <code>alternateURL</code> if it exists.</li>
 * <li>Each user element has a distinguished name that can be formed by substituting the presented username into a
 * pattern configured by the <code>userPattern</code> property.</li>
 * <li>Alternatively, if the <code>userPattern</code> property is not specified, a unique element can be located by
 * searching the directory context. In this case:
 * <ul>
 * <li>The <code>userSearch</code> pattern specifies the search filter after substitution of the username.</li>
 * <li>The <code>userBase</code> property can be set to the element that is the base of the subtree containing users. If
 * not specified, the search base is the top-level context.</li>
 * <li>The <code>userSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
 * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
 * </ul>
 * </li>
 * <li>The user may be authenticated by binding to the directory with the username and password presented. This method
 * is used when the <code>userPassword</code> property is not specified.</li>
 * <li>The user may be authenticated by retrieving the value of an attribute from the directory and comparing it
 * explicitly with the value presented by the user. This method is used when the <code>userPassword</code> property is
 * specified, in which case:
 * <ul>
 * <li>The element for this user must contain an attribute named by the <code>userPassword</code> property.
 * <li>The value of the user password attribute is either a cleartext String, or the result of passing a cleartext
 * String through the <code>RealmBase.digest()</code> method (using the standard digest support included in
 * <code>RealmBase</code>).
 * <li>The user is considered to be authenticated if the presented credentials (after being passed through
 * <code>RealmBase.digest()</code>) are equal to the retrieved value for the user password attribute.</li>
 * </ul>
 * </li>
 * <li>Each group of users that has been assigned a particular role may be represented by an individual element in the
 * top level <code>DirContext</code> that is accessed via the <code>connectionURL</code> property. This element has the
 * following characteristics:
 * <ul>
 * <li>The set of all possible groups of interest can be selected by a search pattern configured by the
 * <code>roleSearch</code> property.</li>
 * <li>The <code>roleSearch</code> pattern optionally includes pattern replacements "{0}" for the distinguished name,
 * and/or "{1}" for the username, and/or "{2}" the value of an attribute from the user's directory entry (the attribute
 * is specified by the <code>userRoleAttribute</code> property), of the authenticated user for which roles will be
 * retrieved.</li>
 * <li>The <code>roleBase</code> property can be set to the element that is the base of the search for matching roles.
 * If not specified, the entire context will be searched.</li>
 * <li>The <code>roleSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
 * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
 * <li>The element includes an attribute (whose name is configured by the <code>roleName</code> property) containing the
 * name of the role represented by this element.</li>
 * </ul>
 * </li>
 * <li>In addition, roles may be represented by the values of an attribute in the user's element whose name is
 * configured by the <code>userRoleName</code> property.</li>
 * <li>A default role can be assigned to each user that was successfully authenticated by setting the
 * <code>commonRole</code> property to the name of this role. The role doesn't have to exist in the directory.</li>
 * <li>If the directory server contains nested roles, you can search for them by setting <code>roleNested</code> to
 * <code>true</code>. The default value is <code>false</code>, so role searches will not find nested roles.</li>
 * <li>Note that the standard <code>&lt;security-role-ref&gt;</code> element in the web application deployment
 * descriptor allows applications to refer to roles programmatically by names other than those used in the directory
 * server itself.</li>
 * </ul>
 */
public class JNDIRealm extends RealmBase {

    /**
     * Constant that holds the name of the environment property for specifying the manner in which aliases should be
     * dereferenced.
     */
    public static final String DEREF_ALIASES = "java.naming.ldap.derefAliases";

    private static final String AUTHENTICATION_NAME_GSSAPI = "GSSAPI";


    /**
     * The type of authentication to use
     */
    protected String authentication = null;

    /**
     * The connection username for the server we will contact.
     */
    protected String connectionName = null;

    /**
     * The connection password for the server we will contact.
     */
    protected String connectionPassword = null;

    /**
     * The connection URL for the server we will contact.
     */
    protected String connectionURL = null;

    /**
     * The JNDI context factory used to acquire our InitialContext. By default, assumes use of an LDAP server using the
     * standard JNDI LDAP provider.
     */
    protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

    /**
     * How aliases should be dereferenced during search operations.
     */
    protected String derefAliases = null;

    /**
     * The protocol that will be used in the communication with the directory server.
     */
    protected String protocol = null;

    /**
     * Should we ignore PartialResultExceptions when iterating over NamingEnumerations? Microsoft Active Directory often
     * returns referrals, which lead to PartialResultExceptions. Unfortunately there's no stable way to detect, if the
     * Exceptions really come from an AD referral. Set to true to ignore PartialResultExceptions.
     */
    protected boolean adCompat = false;

    /**
     * How should we handle referrals? Microsoft Active Directory often returns referrals. If you need to follow them
     * set referrals to "follow". Caution: if your DNS is not part of AD, the LDAP client lib might try to resolve your
     * domain name in DNS to find another LDAP server.
     */
    protected String referrals = null;

    /**
     * The base element for user searches.
     */
    protected String userBase = "";

    /**
     * The message format used to search for a user, with "{0}" marking the spot where the username goes.
     */
    protected String userSearch = null;

    /**
     * When searching for users, should the search be performed as the user currently being authenticated? If false,
     * {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous connection
     * will be used.
     */
    private boolean userSearchAsUser = false;

    /**
     * Should we search the entire subtree for matching users?
     */
    protected boolean userSubtree = false;

    /**
     * The attribute name used to retrieve the user password.
     */
    protected String userPassword = null;

    /**
     * The name of the attribute inside the users directory entry where the value will be taken to search for roles This
     * attribute is not used during a nested search
     */
    protected String userRoleAttribute = null;

    /**
     * A string of LDAP user patterns or paths, ":"-separated These will be used to form the distinguished name of a
     * user, with "{0}" marking the spot where the specified username goes. This is similar to userPattern, but allows
     * for multiple searches for a user.
     */
    protected String[] userPatternArray = null;

    /**
     * The message format used to form the distinguished name of a user, with "{0}" marking the spot where the specified
     * username goes.
     */
    protected String userPattern = null;

    /**
     * The base element for role searches.
     */
    protected String roleBase = "";

    /**
     * The name of an attribute in the user's entry containing roles for that user
     */
    protected String userRoleName = null;

    /**
     * The name of the attribute containing roles held elsewhere
     */
    protected String roleName = null;

    /**
     * The message format used to select roles for a user, with "{0}" marking the spot where the distinguished name of
     * the user goes. The "{1}" and "{2}" are described in the Configuration Reference.
     */
    protected String roleSearch = null;

    /**
     * Should we search the entire subtree for matching memberships?
     */
    protected boolean roleSubtree = false;

    /**
     * Should we look for nested group in order to determine roles?
     */
    protected boolean roleNested = false;

    /**
     * When searching for user roles, should the search be performed as the user currently being authenticated? If
     * false, {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous
     * connection will be used.
     */
    protected boolean roleSearchAsUser = false;

    /**
     * An alternate URL, to which, we should connect if connectionURL fails.
     */
    protected String alternateURL;

    /**
     * The number of connection attempts. If greater than zero we use the alternate url.
     */
    protected int connectionAttempt = 0;

    /**
     * Add this role to every authenticated user
     */
    protected String commonRole = null;

    /**
     * The timeout, in milliseconds, to use when trying to create a connection to the directory. The default is 5000 (5
     * seconds).
     */
    protected String connectionTimeout = "5000";

    /**
     * The timeout, in milliseconds, to use when trying to read from a connection to the directory. The default is 5000
     * (5 seconds).
     */
    protected String readTimeout = "5000";

    /**
     * The sizeLimit (also known as the countLimit) to use when the realm is configured with {@link #userSearch}. Zero
     * for no limit.
     */
    protected long sizeLimit = 0;

    /**
     * The timeLimit (in milliseconds) to use when the realm is configured with {@link #userSearch}. Zero for no limit.
     */
    protected int timeLimit = 0;

    /**
     * Should delegated credentials from the SPNEGO authenticator be used if available
     */
    protected boolean useDelegatedCredential = true;

    /**
     * The QOP that should be used for the connection to the LDAP server after authentication. This value is used to set
     * the <code>javax.security.sasl.qop</code> environment property for the LDAP connection.
     */
    protected String spnegoDelegationQop = "auth-conf";

    /**
     * Whether to use TLS for connections
     */
    private boolean useStartTls = false;

    private StartTlsResponse tls = null;

    /**
     * The list of enabled cipher suites used for establishing tls connections. <code>null</code> means to use the
     * default cipher suites.
     */
    private String[] cipherSuitesArray = null;

    /**
     * Verifier for hostnames in a StartTLS secured connection. <code>null</code> means to use the default verifier.
     */
    private HostnameVerifier hostnameVerifier = null;

    /**
     * {@link SSLSocketFactory} to use when connection with StartTLS enabled.
     */
    private SSLSocketFactory sslSocketFactory = null;

    /**
     * Name of the class of the {@link SSLSocketFactory}. <code>null</code> means to use the default factory.
     */
    private String sslSocketFactoryClassName;

    /**
     * Comma separated list of cipher suites to use for StartTLS. If empty, the default suites are used.
     */
    private String cipherSuites;

    /**
     * Name of the class of the {@link HostnameVerifier}. <code>null</code> means to use the default verifier.
     */
    private String hostNameVerifierClassName;

    /**
     * The ssl Protocol which will be used by StartTLS.
     */
    private String sslProtocol;

    private boolean forceDnHexEscape = false;

    /**
     * Non pooled connection to our directory server.
     */
    protected JNDIConnection singleConnection;

    /**
     * The lock to ensure single connection thread safety.
     */
    protected final Lock singleConnectionLock = new ReentrantLock();

    /**
     * Connection pool.
     */
    protected SynchronizedStack<JNDIConnection> connectionPool = null;

    /**
     * The pool size limit. If 1, pooling is not used.
     */
    protected int connectionPoolSize = 1;

    /**
     * Whether to use context ClassLoader or default ClassLoader. True means use context ClassLoader, and True is the
     * default value.
     */
    protected boolean useContextClassLoader = true;


    // ------------------------------------------------------------- Properties

    public boolean getForceDnHexEscape() {
        return forceDnHexEscape;
    }


    public void setForceDnHexEscape(boolean forceDnHexEscape) {
        this.forceDnHexEscape = forceDnHexEscape;
    }


    /**
     * @return the type of authentication to use.
     */
    public String getAuthentication() {
        return authentication;
    }


    /**
     * Set the type of authentication to use.
     *
     * @param authentication The authentication
     */
    public void setAuthentication(String authentication) {
        this.authentication = authentication;
    }


    /**
     * @return the connection username for this Realm.
     */
    public String getConnectionName() {
        return this.connectionName;
    }


    /**
     * Set the connection username for this Realm.
     *
     * @param connectionName The new connection username
     */
    public void setConnectionName(String connectionName) {
        this.connectionName = connectionName;
    }


    /**
     * @return the connection password for this Realm.
     */
    public String getConnectionPassword() {
        return this.connectionPassword;
    }


    /**
     * Set the connection password for this Realm.
     *
     * @param connectionPassword The new connection password
     */
    public void setConnectionPassword(String connectionPassword) {
        this.connectionPassword = connectionPassword;
    }


    /**
     * @return the connection URL for this Realm.
     */
    public String getConnectionURL() {
        return this.connectionURL;
    }


    /**
     * Set the connection URL for this Realm.
     *
     * @param connectionURL The new connection URL
     */
    public void setConnectionURL(String connectionURL) {
        this.connectionURL = connectionURL;
    }


    /**
     * @return the JNDI context factory for this Realm.
     */
    public String getContextFactory() {
        return this.contextFactory;
    }


    /**
     * Set the JNDI context factory for this Realm.
     *
     * @param contextFactory The new context factory
     */
    public void setContextFactory(String contextFactory) {
        this.contextFactory = contextFactory;
    }


    /**
     * @return the derefAliases setting to be used.
     */
    public String getDerefAliases() {
        return derefAliases;
    }


    /**
     * Set the value for derefAliases to be used when searching the directory.
     *
     * @param derefAliases New value of property derefAliases.
     */
    public void setDerefAliases(String derefAliases) {
        this.derefAliases = derefAliases;
    }


    /**
     * @return the protocol to be used.
     */
    public String getProtocol() {
        return protocol;
    }


    /**
     * Set the protocol for this Realm.
     *
     * @param protocol The new protocol.
     */
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }


    /**
     * @return the current settings for handling PartialResultExceptions
     */
    public boolean getAdCompat() {
        return adCompat;
    }


    /**
     * How do we handle PartialResultExceptions? True: ignore all PartialResultExceptions.
     *
     * @param adCompat <code>true</code> to ignore partial results
     */
    public void setAdCompat(boolean adCompat) {
        this.adCompat = adCompat;
    }


    /**
     * @return the current settings for handling JNDI referrals.
     */
    public String getReferrals() {
        return referrals;
    }


    /**
     * How do we handle JNDI referrals? ignore, follow, or throw (see javax.naming.Context.REFERRAL for more
     * information).
     *
     * @param referrals The referral handling
     */
    public void setReferrals(String referrals) {
        this.referrals = referrals;
    }


    /**
     * @return the base element for user searches.
     */
    public String getUserBase() {
        return this.userBase;
    }


    /**
     * Set the base element for user searches.
     *
     * @param userBase The new base element
     */
    public void setUserBase(String userBase) {
        this.userBase = userBase;
    }


    /**
     * @return the message format pattern for selecting users in this Realm.
     */
    public String getUserSearch() {
        return this.userSearch;
    }


    /**
     * Set the message format pattern for selecting users in this Realm.
     *
     * @param userSearch The new user search pattern
     */
    public void setUserSearch(String userSearch) {
        this.userSearch = userSearch;
        singleConnection = create();
    }


    public boolean isUserSearchAsUser() {
        return userSearchAsUser;
    }


    public void setUserSearchAsUser(boolean userSearchAsUser) {
        this.userSearchAsUser = userSearchAsUser;
    }


    /**
     * @return the "search subtree for users" flag.
     */
    public boolean getUserSubtree() {
        return this.userSubtree;
    }


    /**
     * Set the "search subtree for users" flag.
     *
     * @param userSubtree The new search flag
     */
    public void setUserSubtree(boolean userSubtree) {
        this.userSubtree = userSubtree;
    }


    /**
     * @return the user role name attribute name for this Realm.
     */
    public String getUserRoleName() {
        return userRoleName;
    }


    /**
     * Set the user role name attribute name for this Realm.
     *
     * @param userRoleName The new userRole name attribute name
     */
    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }


    /**
     * @return the base element for role searches.
     */
    public String getRoleBase() {
        return this.roleBase;
    }


    /**
     * Set the base element for role searches.
     *
     * @param roleBase The new base element
     */
    public void setRoleBase(String roleBase) {
        this.roleBase = roleBase;
        singleConnection = create();
    }


    /**
     * @return the role name attribute name for this Realm.
     */
    public String getRoleName() {
        return this.roleName;
    }


    /**
     * Set the role name attribute name for this Realm.
     *
     * @param roleName The new role name attribute name
     */
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }


    /**
     * @return the message format pattern for selecting roles in this Realm.
     */
    public String getRoleSearch() {
        return this.roleSearch;
    }


    /**
     * Set the message format pattern for selecting roles in this Realm.
     *
     * @param roleSearch The new role search pattern
     */
    public void setRoleSearch(String roleSearch) {
        this.roleSearch = roleSearch;
        singleConnection = create();
    }


    public boolean isRoleSearchAsUser() {
        return roleSearchAsUser;
    }


    public void setRoleSearchAsUser(boolean roleSearchAsUser) {
        this.roleSearchAsUser = roleSearchAsUser;
    }


    /**
     * @return the "search subtree for roles" flag.
     */
    public boolean getRoleSubtree() {
        return this.roleSubtree;
    }


    /**
     * Set the "search subtree for roles" flag.
     *
     * @param roleSubtree The new search flag
     */
    public void setRoleSubtree(boolean roleSubtree) {
        this.roleSubtree = roleSubtree;
    }


    /**
     * @return the "The nested group search flag" flag.
     */
    public boolean getRoleNested() {
        return this.roleNested;
    }


    /**
     * Set the "search subtree for roles" flag.
     *
     * @param roleNested The nested group search flag
     */
    public void setRoleNested(boolean roleNested) {
        this.roleNested = roleNested;
    }


    /**
     * @return the password attribute used to retrieve the user password.
     */
    public String getUserPassword() {
        return this.userPassword;
    }


    /**
     * Set the password attribute used to retrieve the user password.
     *
     * @param userPassword The new password attribute
     */
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }


    public String getUserRoleAttribute() {
        return userRoleAttribute;
    }


    public void setUserRoleAttribute(String userRoleAttribute) {
        this.userRoleAttribute = userRoleAttribute;
    }

    /**
     * @return the message format pattern for selecting users in this Realm.
     */
    public String getUserPattern() {
        return this.userPattern;
    }


    /**
     * Set the message format pattern for selecting users in this Realm. This may be one simple pattern, or multiple
     * patterns to be tried, separated by parentheses. (for example, either "cn={0}", or "(cn={0})(cn={0},o=myorg)" Full
     * LDAP search strings are also supported, but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is also
     * valid. Complex search strings with &amp;, etc are NOT supported.
     *
     * @param userPattern The new user pattern
     */
    public void setUserPattern(String userPattern) {
        this.userPattern = userPattern;
        if (userPattern == null) {
            userPatternArray = null;
        } else {
            userPatternArray = parseUserPatternString(userPattern);
            singleConnection = create();
        }
    }


    /**
     * Getter for property alternateURL.
     *
     * @return Value of property alternateURL.
     */
    public String getAlternateURL() {
        return this.alternateURL;
    }


    /**
     * Setter for property alternateURL.
     *
     * @param alternateURL New value of property alternateURL.
     */
    public void setAlternateURL(String alternateURL) {
        this.alternateURL = alternateURL;
    }


    /**
     * @return the common role
     */
    public String getCommonRole() {
        return commonRole;
    }


    /**
     * Set the common role
     *
     * @param commonRole The common role
     */
    public void setCommonRole(String commonRole) {
        this.commonRole = commonRole;
    }


    /**
     * @return the connection timeout.
     */
    public String getConnectionTimeout() {
        return connectionTimeout;
    }


    /**
     * Set the connection timeout.
     *
     * @param timeout The new connection timeout
     */
    public void setConnectionTimeout(String timeout) {
        this.connectionTimeout = timeout;
    }


    /**
     * @return the read timeout.
     */
    public String getReadTimeout() {
        return readTimeout;
    }


    /**
     * Set the read timeout.
     *
     * @param timeout The new read timeout
     */
    public void setReadTimeout(String timeout) {
        this.readTimeout = timeout;
    }


    public long getSizeLimit() {
        return sizeLimit;
    }


    public void setSizeLimit(long sizeLimit) {
        this.sizeLimit = sizeLimit;
    }


    public int getTimeLimit() {
        return timeLimit;
    }


    public void setTimeLimit(int timeLimit) {
        this.timeLimit = timeLimit;
    }


    public boolean isUseDelegatedCredential() {
        return useDelegatedCredential;
    }


    public void setUseDelegatedCredential(boolean useDelegatedCredential) {
        this.useDelegatedCredential = useDelegatedCredential;
    }


    public String getSpnegoDelegationQop() {
        return spnegoDelegationQop;
    }


    public void setSpnegoDelegationQop(String spnegoDelegationQop) {
        this.spnegoDelegationQop = spnegoDelegationQop;
    }


    /**
     * @return flag whether to use StartTLS for connections to the ldap server
     */
    public boolean getUseStartTls() {
        return useStartTls;
    }


    /**
     * Flag whether StartTLS should be used when connecting to the ldap server
     *
     * @param useStartTls {@code true} when StartTLS should be used. Default is {@code false}.
     */
    public void setUseStartTls(boolean useStartTls) {
        this.useStartTls = useStartTls;
    }


    /**
     * @return array of the allowed cipher suites when connections are made using StartTLS
     */
    private String[] getCipherSuitesArray() {
        if (cipherSuites == null || cipherSuitesArray != null) {
            return cipherSuitesArray;
        }
        this.cipherSuites = this.cipherSuites.trim();
        if (this.cipherSuites.isEmpty()) {
            containerLog.warn(sm.getString("jndiRealm.emptyCipherSuites"));
            this.cipherSuitesArray = null;
        } else {
            this.cipherSuitesArray = StringUtils.splitCommaSeparated(cipherSuites);
            if (containerLog.isTraceEnabled()) {
                containerLog.trace(sm.getString("jndiRealm.cipherSuites", Arrays.toString(this.cipherSuitesArray)));
            }
        }
        return this.cipherSuitesArray;
    }


    /**
     * Set the allowed cipher suites when opening a connection using StartTLS. The cipher suites are expected as a comma
     * separated list.
     *
     * @param suites comma separated list of allowed cipher suites
     */
    public void setCipherSuites(String suites) {
        this.cipherSuites = suites;
    }


    /**
     * @return the connection pool size, or the default value 1 if pooling is disabled
     */
    public int getConnectionPoolSize() {
        return connectionPoolSize;
    }


    /**
     * Set the connection pool size
     *
     * @param connectionPoolSize the new pool size
     */
    public void setConnectionPoolSize(int connectionPoolSize) {
        this.connectionPoolSize = connectionPoolSize;
    }


    /**
     * @return name of the {@link HostnameVerifier} class used for connections using StartTLS, or the empty string, if
     *             the default verifier should be used.
     */
    public String getHostnameVerifierClassName() {
        if (this.hostnameVerifier == null) {
            return "";
        }
        return this.hostnameVerifier.getClass().getCanonicalName();
    }


    /**
     * Set the {@link HostnameVerifier} to be used when opening connections using StartTLS. An instance of the given
     * class name will be constructed using the default constructor.
     *
     * @param verifierClassName class name of the {@link HostnameVerifier} to be constructed
     */
    public void setHostnameVerifierClassName(String verifierClassName) {
        if (verifierClassName != null) {
            this.hostNameVerifierClassName = verifierClassName.trim();
        } else {
            this.hostNameVerifierClassName = null;
        }
    }


    /**
     * @return the {@link HostnameVerifier} to use for peer certificate verification when opening connections using
     *             StartTLS.
     */
    public HostnameVerifier getHostnameVerifier() {
        if (this.hostnameVerifier != null) {
            return this.hostnameVerifier;
        }
        if (this.hostNameVerifierClassName == null || hostNameVerifierClassName.isEmpty()) {
            return null;
        }
        try {
            Object o = constructInstance(hostNameVerifierClassName);
            if (o instanceof HostnameVerifier) {
                this.hostnameVerifier = (HostnameVerifier) o;
                return this.hostnameVerifier;
            } else {
                throw new IllegalArgumentException(
                        sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName));
            }
        } catch (ReflectiveOperationException | SecurityException e) {
            throw new IllegalArgumentException(
                    sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName), e);
        }
    }


    /**
     * Set the {@link SSLSocketFactory} to be used when opening connections using StartTLS. An instance of the factory
     * with the given name will be created using the default constructor. The SSLSocketFactory can also be set using
     * {@link JNDIRealm#setSslProtocol(String) setSslProtocol(String)}.
     *
     * @param factoryClassName class name of the factory to be constructed
     */
    public void setSslSocketFactoryClassName(String factoryClassName) {
        this.sslSocketFactoryClassName = factoryClassName;
    }


    /**
     * Set the ssl protocol to be used for connections using StartTLS.
     *
     * @param protocol one of the allowed ssl protocol names
     */
    public void setSslProtocol(String protocol) {
        this.sslProtocol = protocol;
    }


    /**
     * @return the array of supported ssl protocols by the default {@link SSLContext}
     */
    private String[] getSupportedSslProtocols() {
        try {
            SSLContext sslContext = SSLContext.getDefault();
            return sslContext.getSupportedSSLParameters().getProtocols();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(sm.getString("jndiRealm.exception"), e);
        }
    }


    private Object constructInstance(String className) throws ReflectiveOperationException {
        Class<?> clazz = Class.forName(className);
        return clazz.getConstructor().newInstance();
    }


    /**
     * Sets whether to use the context or default ClassLoader. True means use context ClassLoader.
     *
     * @param useContext True means use context ClassLoader
     */
    public void setUseContextClassLoader(boolean useContext) {
        useContextClassLoader = useContext;
    }


    /**
     * Returns whether to use the context or default ClassLoader. True means to use the context ClassLoader.
     *
     * @return The value of useContextClassLoader
     */
    public boolean isUseContextClassLoader() {
        return useContextClassLoader;
    }


    // ---------------------------------------------------------- Realm Methods

    /**
     * {@inheritDoc}
     * <p>
     * If there are any errors with the JNDI connection, executing the query or anything we return null (don't
     * authenticate). This event is also logged, and the connection will be closed so that a subsequent request will
     * automatically re-open it.
     */
    @Override
    public Principal authenticate(String username, String credentials) {

        ClassLoader ocl = null;
        Thread currentThread = null;
        JNDIConnection connection = null;
        Principal principal;

        try {
            // https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
            // This can move back to open() once it is known that Tomcat must be
            // running on a JVM that includes a fix for
            // https://bugs.openjdk.java.net/browse/JDK-8273874
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }

            // Ensure that we have a directory context available
            connection = get();

            try {

                // Occasionally the directory context will time out. Try one more
                // time before giving up.

                // Authenticate the specified username if possible
                principal = authenticate(connection, username, credentials);

            } catch (NullPointerException | NamingException e) {
                /*
                 * BZ 61313 NamingException may or may not indicate an error that is recoverable via fail over.
                 * Therefore, a decision needs to be made whether to fail over or not. Generally, attempting to fail
                 * over when it is not appropriate is better than not failing over when it is appropriate so the code
                 * always attempts to fail over for NamingExceptions.
                 */

                /*
                 * BZ 42449 Catch NPE - Kludge Sun's LDAP provider with broken SSL.
                 */

                // log the exception so we know it's there.
                containerLog.info(sm.getString("jndiRealm.exception.retry"), e);

                // close the connection so we know it will be reopened.
                close(connection);
                closePooledConnections();

                // open a new directory context.
                connection = get();

                // Try the authentication again.
                principal = authenticate(connection, username, credentials);
            }


            // Release this context
            release(connection);

            // Return the authenticated Principal (if any)
            return principal;

        } catch (Exception e) {

            // Log the problem for posterity
            containerLog.error(sm.getString("jndiRealm.exception"), e);

            // close the connection so we know it will be reopened.
            close(connection);
            closePooledConnections();

            // Return "not authenticated" for this request
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("Returning null principal.");
            }
            return null;
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /**
     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
     * <code>null</code>.
     *
     * @param connection  The directory context
     * @param username    Username of the Principal to look up
     * @param credentials Password or other credentials to use in authenticating this username
     *
     * @return the associated principal, or <code>null</code> if there is none.
     *
     * @exception NamingException if a directory server error occurs
     */
    protected Principal authenticate(JNDIConnection connection, String username, String credentials)
            throws NamingException {

        if (username == null || username.isEmpty() || credentials == null || credentials.isEmpty()) {
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("username null or empty: returning null principal.");
            }
            return null;
        }

        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            // https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
            // This can move back to open() once it is known that Tomcat must be
            // running on a JVM that includes a fix for
            // https://bugs.openjdk.java.net/browse/JDK-8273874
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }

            if (userPatternArray != null) {
                for (int curUserPattern = 0; curUserPattern < userPatternArray.length; curUserPattern++) {
                    // Retrieve user information
                    User user = getUser(connection, username, credentials, curUserPattern);
                    if (user != null) {
                        try {
                            // Check the user's credentials
                            if (checkCredentials(connection.context, user, credentials)) {
                                // Search for additional roles
                                List<String> roles = getRoles(connection, user);
                                if (containerLog.isTraceEnabled()) {
                                    containerLog.trace("Found roles: " + ((roles == null) ? "" : roles.toString()));
                                }
                                return new GenericPrincipal(username, roles);
                            }
                        } catch (InvalidNameException ine) {
                            // Log the problem for posterity
                            containerLog.warn(sm.getString("jndiRealm.exception"), ine);
                            // ignore; this is probably due to a name not fitting
                            // the search path format exactly, as in a fully-qualified
                            // name being munged into a search path
                            // that already contains cn= or vice versa
                        }
                    }
                }
                return null;
            } else {
                // Retrieve user information
                User user = getUser(connection, username, credentials);
                if (user == null) {
                    return null;
                }

                // Check the user's credentials
                if (!checkCredentials(connection.context, user, credentials)) {
                    return null;
                }

                // Search for additional roles
                List<String> roles = getRoles(connection, user);
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Found roles: " + ((roles == null) ? "" : roles.toString()));
                }

                // Create and return a suitable Principal for this user
                return new GenericPrincipal(username, roles);
            }
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
     * https://bugs.openjdk.java.net/browse/JDK-8273874
     */
    @Override
    public Principal authenticate(String username) {
        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            return super.authenticate(username);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
     * https://bugs.openjdk.java.net/browse/JDK-8273874
     */
    @Override
    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
            String qop, String realm, String digestA2, String algorithm) {
        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            return super.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realm, digestA2, algorithm);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
     * https://bugs.openjdk.java.net/browse/JDK-8273874
     */
    @Override
    public Principal authenticate(X509Certificate[] certs) {
        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            return super.authenticate(certs);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
     * https://bugs.openjdk.java.net/browse/JDK-8273874
     */
    @Override
    public Principal authenticate(GSSContext gssContext, boolean storeCred) {
        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            return super.authenticate(gssContext, storeCred);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    /*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
     * https://bugs.openjdk.java.net/browse/JDK-8273874
     */
    @Override
    public Principal authenticate(GSSName gssName, GSSCredential gssCredential) {
        ClassLoader ocl = null;
        Thread currentThread = null;
        try {
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            return super.authenticate(gssName, gssCredential);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }
    }


    // ------------------------------------------------------ Protected Methods

    /**
     * Return a User object containing information about the user with the specified username, if found in the
     * directory; otherwise return <code>null</code>.
     *
     * @param connection The directory context
     * @param username   Username to be looked up
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     *
     * @see #getUser(JNDIConnection, String, String, int)
     */
    protected User getUser(JNDIConnection connection, String username) throws NamingException {
        return getUser(connection, username, null, -1);
    }


    /**
     * Return a User object containing information about the user with the specified username, if found in the
     * directory; otherwise return <code>null</code>.
     *
     * @param connection  The directory context
     * @param username    Username to be looked up
     * @param credentials User credentials (optional)
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     *
     * @see #getUser(JNDIConnection, String, String, int)
     */
    protected User getUser(JNDIConnection connection, String username, String credentials) throws NamingException {
        return getUser(connection, username, credentials, -1);
    }


    /**
     * Return a User object containing information about the user with the specified username, if found in the
     * directory; otherwise return <code>null</code>. If the <code>userPassword</code> configuration attribute is
     * specified, the value of that attribute is retrieved from the user's directory entry. If the
     * <code>userRoleName</code> configuration attribute is specified, all values of that attribute are retrieved from
     * the directory entry.
     *
     * @param connection     The directory context
     * @param username       Username to be looked up
     * @param credentials    User credentials (optional)
     * @param curUserPattern Index into userPatternFormatArray
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     */
    protected User getUser(JNDIConnection connection, String username, String credentials, int curUserPattern)
            throws NamingException {

        User user;

        // Get attributes to retrieve from user entry
        List<String> list = new ArrayList<>();
        if (userPassword != null) {
            list.add(userPassword);
        }
        if (userRoleName != null) {
            list.add(userRoleName);
        }
        if (userRoleAttribute != null) {
            list.add(userRoleAttribute);
        }
        String[] attrIds = list.toArray(new String[0]);

        // Use pattern or search for user entry
        if (userPatternArray != null && curUserPattern >= 0) {
            user = getUserByPattern(connection, username, credentials, attrIds, curUserPattern);
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("Found user by pattern [" + user + "]");
            }
        } else {
            boolean thisUserSearchAsUser = isUserSearchAsUser();
            try {
                if (thisUserSearchAsUser) {
                    userCredentialsAdd(connection.context, username, credentials);
                }
                user = getUserBySearch(connection, username, attrIds);
            } finally {
                if (thisUserSearchAsUser) {
                    userCredentialsRemove(connection.context);
                }
            }
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("Found user by search [" + user + "]");
            }
        }
        if (userPassword == null && credentials != null && user != null) {
            // The password is available. Insert it since it may be required for
            // role searches.
            return new User(user.getUserName(), user.getDN(), credentials, user.getRoles(), user.getUserRoleId());
        }

        return user;
    }


    /**
     * Use the distinguished name to locate the directory entry for the user with the specified username and return a
     * User object; otherwise return <code>null</code>.
     *
     * @param context  The directory context
     * @param username The username
     * @param attrIds  String[]containing names of attributes to
     * @param dn       Distinguished name of the user retrieve.
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     */
    protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn)
            throws NamingException {

        // If no attributes are requested, no need to look for them
        if (attrIds == null || attrIds.length == 0) {
            return new User(username, dn, null, null, null);
        }

        // Get required attributes from user entry
        Attributes attrs;
        try {
            attrs = context.getAttributes(dn, attrIds);
        } catch (NameNotFoundException e) {
            return null;
        }
        if (attrs == null) {
            return null;
        }

        // Retrieve value of userPassword
        String password = null;
        if (userPassword != null) {
            password = getAttributeValue(userPassword, attrs);
        }

        String userRoleAttrValue = null;
        if (userRoleAttribute != null) {
            userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
        }

        // Retrieve values of userRoleName attribute
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, null);
        }

        return new User(username, dn, password, roles, userRoleAttrValue);
    }


    /**
     * Use the <code>UserPattern</code> configuration attribute to locate the directory entry for the user with the
     * specified username and return a User object; otherwise return <code>null</code>.
     *
     * @param connection     The directory context
     * @param username       The username
     * @param credentials    User credentials (optional)
     * @param attrIds        String[]containing names of attributes to
     * @param curUserPattern Index into userPatternFormatArray
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     *
     * @see #getUserByPattern(DirContext, String, String[], String)
     */
    protected User getUserByPattern(JNDIConnection connection, String username, String credentials, String[] attrIds,
            int curUserPattern) throws NamingException {

        User user;

        if (username == null || userPatternArray[curUserPattern] == null) {
            return null;
        }

        // Form the DistinguishedName from the user pattern.
        // Escape in case username contains a character with special meaning in
        // an attribute value.
        String dn = connection.userPatternFormatArray[curUserPattern]
                .format(new String[] { doAttributeValueEscaping(username) });

        try {
            user = getUserByPattern(connection.context, username, attrIds, dn);
        } catch (NameNotFoundException e) {
            return null;
        } catch (NamingException e) {
            // If the getUserByPattern() call fails, try it again with the
            // credentials of the user that we're searching for
            try {
                userCredentialsAdd(connection.context, dn, credentials);

                user = getUserByPattern(connection.context, username, attrIds, dn);
            } finally {
                userCredentialsRemove(connection.context);
            }
        }
        return user;
    }


    /**
     * Search the directory to return a User object containing information about the user with the specified username,
     * if found in the directory; otherwise return <code>null</code>.
     *
     * @param connection The directory context
     * @param username   The username
     * @param attrIds    String[]containing names of attributes to retrieve.
     *
     * @return the User object
     *
     * @exception NamingException if a directory server error occurs
     */
    protected User getUserBySearch(JNDIConnection connection, String username, String[] attrIds)
            throws NamingException {

        if (username == null || connection.userSearchFormat == null) {
            return null;
        }

        // Form the search filter
        // Escape in case username contains a character with special meaning in
        // a search filter.
        String filter = connection.userSearchFormat.format(new String[] { doFilterEscaping(username) });

        // Set up the search controls
        SearchControls constraints = new SearchControls();

        if (userSubtree) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        constraints.setCountLimit(sizeLimit);
        constraints.setTimeLimit(timeLimit);

        // Specify the attributes to be retrieved
        if (attrIds == null) {
            attrIds = new String[0];
        }
        constraints.setReturningAttributes(attrIds);

        NamingEnumeration<SearchResult> results = connection.context.search(userBase, filter, constraints);

        try {
            // Fail if no entries found
            try {
                if (results == null || !results.hasMore()) {
                    return null;
                }
            } catch (PartialResultException ex) {
                if (!adCompat) {
                    throw ex;
                } else {
                    return null;
                }
            }

            // Get result for the first entry found
            SearchResult result = results.next();

            // Check no further entries were found
            try {
                if (results.hasMore()) {
                    if (containerLog.isInfoEnabled()) {
                        containerLog.info(sm.getString("jndiRealm.multipleEntries", username));
                    }
                    return null;
                }
            } catch (PartialResultException ex) {
                if (!adCompat) {
                    throw ex;
                }
            }

            String dn = getDistinguishedName(connection.context, userBase, result);

            if (containerLog.isTraceEnabled()) {
                containerLog.trace("  entry found for " + username + " with dn " + dn);
            }

            // Get the entry's attributes
            Attributes attrs = result.getAttributes();
            if (attrs == null) {
                return null;
            }

            // Retrieve value of userPassword
            String password = null;
            if (userPassword != null) {
                password = getAttributeValue(userPassword, attrs);
            }

            String userRoleAttrValue = null;
            if (userRoleAttribute != null) {
                userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
            }

            // Retrieve values of userRoleName attribute
            ArrayList<String> roles = null;
            if (userRoleName != null) {
                roles = addAttributeValues(userRoleName, attrs, null);
            }

            return new User(username, dn, password, roles, userRoleAttrValue);
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }


    /**
     * Check whether the given User can be authenticated with the given credentials. If the <code>userPassword</code>
     * configuration attribute is specified, the credentials previously retrieved from the directory are compared
     * explicitly with those presented by the user. Otherwise, the presented credentials are checked by binding to the
     * directory as the user.
     *
     * @param context     The directory context
     * @param user        The User to be authenticated
     * @param credentials The credentials presented by the user
     *
     * @return <code>true</code> if the credentials are validated
     *
     * @exception NamingException if a directory server error occurs
     */
    protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException {

        boolean validated;

        if (userPassword == null) {
            validated = bindAsUser(context, user, credentials);
        } else {
            validated = compareCredentials(context, user, credentials);
        }

        if (containerLog.isTraceEnabled()) {
            if (validated) {
                containerLog.trace(sm.getString("jndiRealm.authenticateSuccess", user.getUserName()));
            } else {
                containerLog.trace(sm.getString("jndiRealm.authenticateFailure", user.getUserName()));
            }
        }
        return validated;
    }


    /**
     * Check whether the credentials presented by the user match those retrieved from the directory.
     *
     * @param context     The directory context
     * @param info        The User to be authenticated
     * @param credentials Authentication credentials
     *
     * @return <code>true</code> if the credentials are validated
     *
     * @exception NamingException if a directory server error occurs
     */
    protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException {
        // Validate the credentials specified by the user
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  validating credentials");
        }

        if (info == null || credentials == null) {
            return false;
        }

        String password = info.getPassword();

        return getCredentialHandler().matches(credentials, password);
    }


    /**
     * Check credentials by binding to the directory as the user
     *
     * @param context     The directory context
     * @param user        The User to be authenticated
     * @param credentials Authentication credentials
     *
     * @return <code>true</code> if the credentials are validated
     *
     * @exception NamingException if a directory server error occurs
     */
    protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException {

        if (credentials == null || user == null) {
            return false;
        }

        // This is returned from the directory so will be attribute value
        // escaped if required
        String dn = user.getDN();
        if (dn == null) {
            return false;
        }

        // Validate the credentials specified by the user
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  validating credentials by binding as the user");
        }

        boolean validated = false;
        Hashtable<?,?> preservedEnvironment = context.getEnvironment();

        // Elicit an LDAP bind operation using the provided user credentials
        try {
            userCredentialsAdd(context, dn, credentials);
            // Need to make sure GSSAPI SASL authentication is not used if configured
            if (AUTHENTICATION_NAME_GSSAPI.equals(preservedEnvironment.get(Context.SECURITY_AUTHENTICATION))) {
                context.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
            }
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("  binding as " + dn);
            }
            context.getAttributes("", null);
            validated = true;
        } catch (AuthenticationException e) {
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("  bind attempt failed", e);
            }
        } finally {
            // Restore GSSAPI SASL if previously configured
            restoreEnvironmentParameter(context, Context.SECURITY_AUTHENTICATION, preservedEnvironment);
            userCredentialsRemove(context);
        }

        return validated;
    }


    /**
     * Configure the context to use the provided credentials for authentication.
     *
     * @param context     DirContext to configure
     * @param dn          Distinguished name of user
     * @param credentials Credentials of user
     *
     * @exception NamingException if a directory server error occurs
     */
    private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException {
        // Set up security environment to bind as the user
        context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
        context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
    }


    /**
     * Configure the context to use {@link #connectionName} and {@link #connectionPassword} if specified or an anonymous
     * connection if those attributes are not specified.
     *
     * @param context DirContext to configure
     *
     * @exception NamingException if a directory server error occurs
     */
    private void userCredentialsRemove(DirContext context) throws NamingException {
        // Restore the original security environment
        if (connectionName != null) {
            context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionName);
        } else {
            context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
        }

        if (connectionPassword != null) {
            context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword);
        } else {
            context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
        }
    }


    /**
     * Return a List of roles associated with the given User. Any roles present in the user's directory entry are
     * supplemented by a directory search. If no roles are associated with this user, a zero-length List is returned.
     *
     * @param connection The directory context we are searching
     * @param user       The User to be checked
     *
     * @return the list of role names
     *
     * @exception NamingException if a directory server error occurs
     */
    protected List<String> getRoles(JNDIConnection connection, User user) throws NamingException {

        if (user == null) {
            return null;
        }

        // This is returned from the directory so will be attribute value
        // escaped if required
        String dn = user.getDN();
        // This is the name the user provided to the authentication process so
        // it will not be escaped
        String username = user.getUserName();
        String userRoleId = user.getUserRoleId();

        if (dn == null || username == null) {
            return null;
        }

        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  getRoles(" + dn + ")");
        }

        // Start with roles retrieved from the user entry
        List<String> list = new ArrayList<>();
        List<String> userRoles = user.getRoles();
        if (userRoles != null) {
            list.addAll(userRoles);
        }
        if (commonRole != null) {
            list.add(commonRole);
        }

        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  Found " + list.size() + " user internal roles");
            containerLog.trace("  Found user internal roles " + list.toString());
        }

        // Are we configured to do role searches?
        if (connection.roleFormat == null || roleName == null) {
            return list;
        }

        // Set up parameters for an appropriate search filter
        // The dn is already attribute value escaped but the others are not
        // This is a filter so all input will require filter escaping
        String filter = connection.roleFormat
                .format(new String[] { doFilterEscaping(dn), doFilterEscaping(doAttributeValueEscaping(username)),
                        doFilterEscaping(doAttributeValueEscaping(userRoleId)) });
        SearchControls controls = new SearchControls();
        if (roleSubtree) {
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        controls.setReturningAttributes(new String[] { roleName });

        String base;
        if (connection.roleBaseFormat != null) {
            NameParser np = connection.context.getNameParser("");
            Name name = np.parse(dn);
            String[] nameParts = new String[name.size()];
            for (int i = 0; i < name.size(); i++) {
                // May have been returned with \<char> escaping rather than
                // \<hex><hex>. Make sure it is \<hex><hex>.
                nameParts[i] = convertToHexEscape(name.get(i));
            }
            base = connection.roleBaseFormat.format(nameParts);
        } else {
            base = "";
        }

        // Perform the configured search and process the results
        NamingEnumeration<SearchResult> results =
                searchAsUser(connection.context, user, base, filter, controls, isRoleSearchAsUser());

        if (results == null) {
            return list; // Should never happen, but just in case ...
        }

        Map<String,String> groupMap = new HashMap<>();
        try {
            while (results.hasMore()) {
                SearchResult result = results.next();
                Attributes attrs = result.getAttributes();
                if (attrs == null) {
                    continue;
                }
                String dname = getDistinguishedName(connection.context, base, result);
                String name = getAttributeValue(roleName, attrs);
                if (name != null && dname != null) {
                    groupMap.put(dname, name);
                }
            }
        } catch (PartialResultException ex) {
            if (!adCompat) {
                throw ex;
            }
        } finally {
            results.close();
        }

        if (containerLog.isTraceEnabled()) {
            Set<Entry<String,String>> entries = groupMap.entrySet();
            containerLog.trace("  Found " + entries.size() + " direct roles");
            for (Entry<String,String> entry : entries) {
                containerLog.trace("  Found direct role " + entry.getKey() + " -> " + entry.getValue());
            }
        }

        // if nested group search is enabled, perform searches for nested groups until no new group is found
        if (getRoleNested()) {

            // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in
            // Directory Groups". It avoids group slurping and handles cyclic group memberships as well.
            // See http://middleware.internet2.edu/dir/ for details

            Map<String,String> newGroups = new HashMap<>(groupMap);
            while (!newGroups.isEmpty()) {
                Map<String,String> newThisRound = new HashMap<>(); // Stores the groups we find in this iteration

                for (Entry<String,String> group : newGroups.entrySet()) {
                    // Group key is already value escaped if required
                    // Group value is not value escaped
                    // Everything needs to be filter escaped
                    filter = connection.roleFormat.format(new String[] { doFilterEscaping(group.getKey()),
                            doFilterEscaping(doAttributeValueEscaping(group.getValue())),
                            doFilterEscaping(doAttributeValueEscaping(group.getValue())) });

                    if (containerLog.isTraceEnabled()) {
                        containerLog
                                .trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
                    }

                    results = searchAsUser(connection.context, user, base, filter, controls, isRoleSearchAsUser());

                    try {
                        while (results.hasMore()) {
                            SearchResult result = results.next();
                            Attributes attrs = result.getAttributes();
                            if (attrs == null) {
                                continue;
                            }
                            String dname = getDistinguishedName(connection.context, roleBase, result);
                            String name = getAttributeValue(roleName, attrs);
                            if (name != null && dname != null && !groupMap.containsKey(dname)) {
                                groupMap.put(dname, name);
                                newThisRound.put(dname, name);

                                if (containerLog.isTraceEnabled()) {
                                    containerLog.trace("  Found nested role " + dname + " -> " + name);
                                }
                            }
                        }
                    } catch (PartialResultException ex) {
                        if (!adCompat) {
                            throw ex;
                        }
                    } finally {
                        results.close();
                    }
                }

                newGroups = newThisRound;
            }
        }

        list.addAll(groupMap.values());
        return list;
    }


    /**
     * Perform the search on the context as the {@code dn}, when {@code searchAsUser} is {@code true}, otherwise search
     * the context with the default credentials.
     *
     * @param context      context to search on
     * @param user         user to bind on
     * @param base         base to start the search from
     * @param filter       filter to use for the search
     * @param controls     controls to use for the search
     * @param searchAsUser {@code true} when the search should be done as user, or {@code false} for using the default
     *                         credentials
     *
     * @return enumeration with all found entries
     *
     * @throws NamingException if a directory server error occurs
     */
    private NamingEnumeration<SearchResult> searchAsUser(DirContext context, User user, String base, String filter,
            SearchControls controls, boolean searchAsUser) throws NamingException {
        NamingEnumeration<SearchResult> results;
        try {
            if (searchAsUser) {
                userCredentialsAdd(context, user.getDN(), user.getPassword());
            }
            results = context.search(base, filter, controls);
        } finally {
            if (searchAsUser) {
                userCredentialsRemove(context);
            }
        }
        return results;
    }


    /**
     * Return a String representing the value of the specified attribute.
     *
     * @param attrId Attribute name
     * @param attrs  Attributes containing the required value
     *
     * @return the attribute value
     *
     * @exception NamingException if a directory server error occurs
     */
    private String getAttributeValue(String attrId, Attributes attrs) throws NamingException {

        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  retrieving attribute " + attrId);
        }

        if (attrId == null || attrs == null) {
            return null;
        }

        Attribute attr = attrs.get(attrId);
        if (attr == null) {
            return null;
        }
        Object value = attr.get();
        if (value == null) {
            return null;
        }
        String valueString;
        if (value instanceof byte[]) {
            valueString = new String((byte[]) value);
        } else {
            valueString = value.toString();
        }

        return valueString;
    }


    /**
     * Add values of a specified attribute to a list
     *
     * @param attrId Attribute name
     * @param attrs  Attributes containing the new values
     * @param values ArrayList containing values found so far
     *
     * @return the list of attribute values
     *
     * @exception NamingException if a directory server error occurs
     */
    private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
            throws NamingException {

        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  retrieving values for attribute " + attrId);
        }
        if (attrId == null || attrs == null) {
            return values;
        }
        if (values == null) {
            values = new ArrayList<>();
        }
        Attribute attr = attrs.get(attrId);
        if (attr == null) {
            return values;
        }
        NamingEnumeration<?> e = attr.getAll();
        try {
            while (e.hasMore()) {
                String value = (String) e.next();
                values.add(value);
            }
        } catch (PartialResultException ex) {
            if (!adCompat) {
                throw ex;
            }
        } finally {
            e.close();
        }
        return values;
    }


    /**
     * Close any open connection to the directory server for this Realm.
     *
     * @param connection The directory context to be closed
     */
    protected void close(JNDIConnection connection) {

        // Do nothing if there is no opened connection
        if (connection == null || connection.context == null) {
            if (connectionPool == null) {
                singleConnectionLock.unlock();
            }
            return;
        }

        // Close tls startResponse if used
        if (tls != null) {
            try {
                tls.close();
            } catch (IOException ioe) {
                containerLog.error(sm.getString("jndiRealm.tlsClose"), ioe);
            }
        }
        // Close our opened connection
        try {
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("Closing directory context");
            }
            connection.context.close();
        } catch (NamingException e) {
            containerLog.error(sm.getString("jndiRealm.close"), e);
        }
        connection.context = null;
        // The lock will be reacquired before any manipulation of the connection
        if (connectionPool == null) {
            singleConnectionLock.unlock();
        }
    }


    /**
     * Close all pooled connections.
     */
    protected void closePooledConnections() {
        if (connectionPool != null) {
            // Close any pooled connections as they might be bad as well
            synchronized (connectionPool) {
                JNDIConnection connection;
                while ((connection = connectionPool.pop()) != null) {
                    close(connection);
                }
            }
        }
    }


    @Override
    protected String getPassword(String username) {
        String userPassword = getUserPassword();
        if (userPassword == null || userPassword.isEmpty()) {
            return null;
        }

        JNDIConnection connection = null;
        User user;
        try {
            // Ensure that we have a directory context available
            connection = get();

            // Occasionally the directory context will time out. Try one more
            // time before giving up.
            try {
                user = getUser(connection, username, null);
            } catch (NullPointerException | NamingException e) {
                // log the exception so we know it's there.
                containerLog.info(sm.getString("jndiRealm.exception.retry"), e);

                // close the connection so we know it will be reopened.
                close(connection);
                closePooledConnections();

                // open a new directory context.
                connection = get();

                // Try the authentication again.
                user = getUser(connection, username, null);
            }

            // Release this context
            release(connection);

            if (user == null) {
                // User should be found...
                return null;
            } else {
                // ... and have a password
                return user.getPassword();
            }
        } catch (Exception e) {
            // Log the problem for posterity
            containerLog.error(sm.getString("jndiRealm.exception"), e);
            // close the connection so we know it will be reopened.
            close(connection);
            closePooledConnections();
            return null;
        }
    }


    @Override
    protected Principal getPrincipal(String username) {
        return getPrincipal(username, null);
    }


    @Override
    protected Principal getPrincipal(GSSName gssName, GSSCredential gssCredential) {
        String name = gssName.toString();

        if (isStripRealmForGss()) {
            int i = name.indexOf('@');
            if (i > 0) {
                // Zero so we don't leave a zero length name
                name = name.substring(0, i);
            }
        }

        return getPrincipal(name, gssCredential);
    }


    protected Principal getPrincipal(String username, GSSCredential gssCredential) {

        JNDIConnection connection = null;
        Principal principal;

        try {
            // Ensure that we have a directory context available
            connection = get();

            // Occasionally the directory context will time out. Try one more
            // time before giving up.
            try {

                // Authenticate the specified username if possible
                principal = getPrincipal(connection, username, gssCredential);

            } catch (NamingException e) {
                /*
                 * While we would like to catch specialized exceptions like CommunicationException and
                 * ServiceUnavailableException, some network communication problems are reported as this general
                 * exception. This is fixed in Java 18 by https://bugs.openjdk.org/browse/JDK-8273402
                 */
                // log the exception so we know it's there.
                containerLog.info(sm.getString("jndiRealm.exception.retry"), e);

                // close the connection so we know it will be reopened.
                close(connection);
                closePooledConnections();

                // open a new directory context.
                connection = get();

                // Try the authentication again.
                principal = getPrincipal(connection, username, gssCredential);
            }

            // Release this context
            release(connection);

            // Return the authenticated Principal (if any)
            return principal;

        } catch (Exception e) {
            // Log the problem for posterity
            containerLog.error(sm.getString("jndiRealm.exception"), e);

            // close the connection so we know it will be reopened.
            close(connection);
            closePooledConnections();

            // Return "not authenticated" for this request
            return null;
        }
    }


    /**
     * Get the principal associated with the specified username.
     *
     * @param connection    The directory context
     * @param username      The username
     * @param gssCredential The credentials
     *
     * @return the Principal associated with the given certificate.
     *
     * @exception NamingException if a directory server error occurs
     */
    protected Principal getPrincipal(JNDIConnection connection, String username, GSSCredential gssCredential)
            throws NamingException {

        User user;
        List<String> roles = null;
        Hashtable<?,?> preservedEnvironment = null;
        DirContext context = connection.context;

        try {
            if (gssCredential != null && isUseDelegatedCredential()) {
                // Preserve the current context environment parameters
                preservedEnvironment = context.getEnvironment();
                // Set up context
                context.addToEnvironment(Context.SECURITY_AUTHENTICATION, AUTHENTICATION_NAME_GSSAPI);
                context.addToEnvironment("javax.security.sasl.server.authentication", "true");
                context.addToEnvironment("javax.security.sasl.qop", spnegoDelegationQop);
                // Note: Subject already set in SPNEGO authenticator so no need
                // for Subject.doAs() here
            }
            user = getUser(connection, username);
            if (user != null) {
                roles = getRoles(connection, user);
            }
        } finally {
            if (gssCredential != null && isUseDelegatedCredential()) {
                restoreEnvironmentParameter(context, Context.SECURITY_AUTHENTICATION, preservedEnvironment);
                restoreEnvironmentParameter(context, "javax.security.sasl.server.authentication", preservedEnvironment);
                restoreEnvironmentParameter(context, "javax.security.sasl.qop", preservedEnvironment);
            }
        }

        if (user != null) {
            return new GenericPrincipal(user.getUserName(), roles, null, null, gssCredential, null);
        }

        return null;
    }


    private void restoreEnvironmentParameter(DirContext context, String parameterName,
            Hashtable<?,?> preservedEnvironment) {
        try {
            context.removeFromEnvironment(parameterName);
            if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
                context.addToEnvironment(parameterName, preservedEnvironment.get(parameterName));
            }
        } catch (NamingException e) {
            // Ignore
        }
    }


    /**
     * Open (if necessary) and return a connection to the configured directory server for this Realm.
     *
     * @return the connection
     *
     * @exception NamingException if a directory server error occurs
     */
    protected JNDIConnection get() throws NamingException {
        JNDIConnection connection;
        // Use the pool if available, otherwise use the single connection
        if (connectionPool != null) {
            connection = connectionPool.pop();
            if (connection == null) {
                connection = create();
            }
        } else {
            singleConnectionLock.lock();
            if (singleConnection == null) {
                singleConnection = create();
            }
            connection = singleConnection;
        }
        if (connection.context == null) {
            open(connection);
        }
        return connection;
    }


    /**
     * Release our use of this connection so that it can be recycled.
     *
     * @param connection The directory context to release
     */
    protected void release(JNDIConnection connection) {
        if (connectionPool != null) {
            if (connection != null) {
                if (!connectionPool.push(connection)) {
                    // Any connection that doesn't end back to the pool must be closed
                    close(connection);
                }
            }
        } else {
            singleConnectionLock.unlock();
        }
    }


    /**
     * Create a new connection wrapper, along with the message formats.
     *
     * @return the new connection
     */
    protected JNDIConnection create() {
        return new JNDIConnection(userSearch, userPatternArray, roleBase, roleSearch);
    }


    /**
     * Create a new connection to the directory server.
     *
     * @param connection The directory server connection wrapper
     *
     * @throws NamingException if a directory server error occurs
     */
    protected void open(JNDIConnection connection) throws NamingException {
        try {
            // Ensure that we have a directory context available
            connection.context = createDirContext(getDirectoryContextEnvironment());
        } catch (Exception e) {
            if (alternateURL == null || alternateURL.isEmpty()) {
                // No alternate URL. Re-throw the exception.
                throw e;
            }
            connectionAttempt = 1;
            // log the first exception.
            containerLog.info(sm.getString("jndiRealm.exception.retry"), e);
            // Try connecting to the alternate url.
            connection.context = createDirContext(getDirectoryContextEnvironment());
        } finally {
            // reset it in case the connection times out.
            // the primary may come back.
            connectionAttempt = 0;
        }
    }


    @Override
    public boolean isAvailable() {
        // Simple best effort check
        return (connectionPool != null || singleConnection.context != null);
    }


    private DirContext createDirContext(Hashtable<String,String> env) throws NamingException {
        if (useStartTls) {
            return createTlsDirContext(env);
        } else {
            return new InitialDirContext(env);
        }
    }


    private SSLSocketFactory getSSLSocketFactory() {
        if (sslSocketFactory != null) {
            return sslSocketFactory;
        }
        final SSLSocketFactory result;
        if (this.sslSocketFactoryClassName != null && !sslSocketFactoryClassName.trim().isEmpty()) {
            result = createSSLSocketFactoryFromClassName(this.sslSocketFactoryClassName);
        } else {
            result = createSSLContextFactoryFromProtocol(sslProtocol);
        }
        this.sslSocketFactory = result;
        return result;
    }


    private SSLSocketFactory createSSLSocketFactoryFromClassName(String className) {
        try {
            Object o = constructInstance(className);
            if (o instanceof SSLSocketFactory) {
                return (SSLSocketFactory) o;
            } else {
                throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className));
            }
        } catch (ReflectiveOperationException | SecurityException e) {
            throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className), e);
        }
    }


    private SSLSocketFactory createSSLContextFactoryFromProtocol(String protocol) {
        try {
            SSLContext sslContext;
            if (protocol != null) {
                sslContext = SSLContext.getInstance(protocol);
                sslContext.init(null, null, null);
            } else {
                sslContext = SSLContext.getDefault();
            }
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            List<String> allowedProtocols = Arrays.asList(getSupportedSslProtocols());
            throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol", protocol, allowedProtocols),
                    e);
        }
    }


    /**
     * Create a tls enabled LdapContext and set the StartTlsResponse tls instance variable.
     *
     * @param env Environment to use for context creation
     *
     * @return configured {@link LdapContext}
     *
     * @throws NamingException when something goes wrong while negotiating the connection
     */
    private DirContext createTlsDirContext(Hashtable<String,String> env) throws NamingException {
        Map<String,Object> savedEnv = new HashMap<>();
        for (String key : Arrays.asList(Context.SECURITY_AUTHENTICATION, Context.SECURITY_CREDENTIALS,
                Context.SECURITY_PRINCIPAL, Context.SECURITY_PROTOCOL)) {
            Object entry = env.remove(key);
            if (entry != null) {
                savedEnv.put(key, entry);
            }
        }
        LdapContext result = null;
        try {
            result = new InitialLdapContext(env, null);
            tls = (StartTlsResponse) result.extendedOperation(new StartTlsRequest());
            if (getHostnameVerifier() != null) {
                tls.setHostnameVerifier(getHostnameVerifier());
            }
            if (getCipherSuitesArray() != null) {
                tls.setEnabledCipherSuites(getCipherSuitesArray());
            }
            try {
                SSLSession negotiate = tls.negotiate(getSSLSocketFactory());
                containerLog.debug(sm.getString("jndiRealm.negotiatedTls", negotiate.getProtocol()));
            } catch (IOException ioe) {
                NamingException ne = new NamingException(ioe.getMessage());
                ne.initCause(ioe);
                throw ne;
            }
        } finally {
            if (result != null) {
                for (Map.Entry<String,Object> savedEntry : savedEnv.entrySet()) {
                    result.addToEnvironment(savedEntry.getKey(), savedEntry.getValue());
                }
            }
        }
        return result;
    }


    /**
     * Create our directory context configuration.
     *
     * @return java.util.Hashtable the configuration for the directory context.
     */
    protected Hashtable<String,String> getDirectoryContextEnvironment() {

        Hashtable<String,String> env = new Hashtable<>();

        // Configure our directory context environment.
        if (containerLog.isTraceEnabled() && connectionAttempt == 0) {
            containerLog.trace("Connecting to URL " + connectionURL);
        } else if (containerLog.isTraceEnabled() && connectionAttempt > 0) {
            containerLog.trace("Connecting to URL " + alternateURL);
        }
        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
        if (connectionName != null) {
            env.put(Context.SECURITY_PRINCIPAL, connectionName);
        }
        if (connectionPassword != null) {
            env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
        }
        if (connectionURL != null && connectionAttempt == 0) {
            env.put(Context.PROVIDER_URL, connectionURL);
        } else if (alternateURL != null && connectionAttempt > 0) {
            env.put(Context.PROVIDER_URL, alternateURL);
        }
        if (authentication != null) {
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
        }
        if (protocol != null) {
            env.put(Context.SECURITY_PROTOCOL, protocol);
        }
        if (referrals != null) {
            env.put(Context.REFERRAL, referrals);
        }
        if (derefAliases != null) {
            env.put(DEREF_ALIASES, derefAliases);
        }
        if (connectionTimeout != null) {
            env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout);
        }
        if (readTimeout != null) {
            env.put("com.sun.jndi.ldap.read.timeout", readTimeout);
        }

        return env;
    }


    // ------------------------------------------------------ Lifecycle Methods

    /**
     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
     *                                   used
     */
    @Override
    protected void startInternal() throws LifecycleException {

        if (connectionPoolSize != 1) {
            connectionPool = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, connectionPoolSize);
        }

        // Check to see if the connection to the directory can be opened
        ClassLoader ocl = null;
        Thread currentThread = null;
        JNDIConnection connection = null;
        try {
            // https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
            // This can move back to open() once it is known that Tomcat must be
            // running on a JVM that includes a fix for
            // https://bugs.openjdk.java.net/browse/JDK-8273874
            if (!isUseContextClassLoader()) {
                currentThread = Thread.currentThread();
                ocl = currentThread.getContextClassLoader();
                currentThread.setContextClassLoader(this.getClass().getClassLoader());
            }
            connection = get();
        } catch (NamingException e) {
            // A failure here is not fatal as the directory may be unavailable
            // now but available later. Unavailability of the directory is not
            // fatal once the Realm has started so there is no reason for it to
            // be fatal when the Realm starts.
            containerLog.error(sm.getString("jndiRealm.open"), e);
        } finally {
            release(connection);
            if (currentThread != null) {
                currentThread.setContextClassLoader(ocl);
            }
        }

        super.startInternal();
    }


    /**
     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error that needs to be reported
     */
    @Override
    protected void stopInternal() throws LifecycleException {
        super.stopInternal();
        // Close any open directory server connection
        if (connectionPool == null) {
            singleConnectionLock.lock();
            close(singleConnection);
        } else {
            closePooledConnections();
            connectionPool = null;
        }
    }


    /**
     * Given a string containing LDAP patterns for user locations (separated by parentheses in a pseudo-LDAP search
     * string format - "(location1)(location2)"), returns an array of those paths. Real LDAP search strings are
     * supported as well (though only the "|" "OR" type).
     *
     * @param userPatternString - a string LDAP search paths surrounded by parentheses
     *
     * @return a parsed string array
     */
    protected String[] parseUserPatternString(String userPatternString) {

        if (userPatternString != null) {
            List<String> pathList = new ArrayList<>();
            int startParenLoc = userPatternString.indexOf('(');
            if (startParenLoc == -1) {
                // no parens here; return whole thing
                return new String[] { userPatternString };
            }
            while (startParenLoc > -1) {
                // weed out escaped open parens and parens enclosing the
                // whole statement (in the case of valid LDAP search
                // strings: (|(something)(somethingelse))
                while ((userPatternString.charAt(startParenLoc + 1) == '|') ||
                        (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\')) {
                    startParenLoc = userPatternString.indexOf('(', startParenLoc + 1);
                }
                int endParenLoc = userPatternString.indexOf(')', startParenLoc + 1);
                // weed out escaped end-parens
                while (userPatternString.charAt(endParenLoc - 1) == '\\') {
                    endParenLoc = userPatternString.indexOf(')', endParenLoc + 1);
                }
                String nextPathPart = userPatternString.substring(startParenLoc + 1, endParenLoc);
                pathList.add(nextPathPart);
                startParenLoc = userPatternString.indexOf('(', endParenLoc + 1);
            }
            return pathList.toArray(new String[0]);
        }
        return null;
    }


    /**
     * Given an LDAP search string, returns the string with certain characters escaped according to RFC 2254 guidelines.
     * The character mapping is as follows: char -&gt; Replacement --------------------------- * -&gt; \2a ( -&gt; \28 )
     * -&gt; \29 \ -&gt; \5c \0 -&gt; \00
     *
     * @param inString string to escape according to RFC 2254 guidelines
     *
     * @return String the escaped/encoded result
     */
    protected String doFilterEscaping(String inString) {
        if (inString == null) {
            return null;
        }
        StringBuilder buf = new StringBuilder(inString.length());
        for (int i = 0; i < inString.length(); i++) {
            char c = inString.charAt(i);
            switch (c) {
                case '\\':
                    buf.append("\\5c");
                    break;
                case '*':
                    buf.append("\\2a");
                    break;
                case '(':
                    buf.append("\\28");
                    break;
                case ')':
                    buf.append("\\29");
                    break;
                case '\0':
                    buf.append("\\00");
                    break;
                default:
                    buf.append(c);
                    break;
            }
        }
        return buf.toString();
    }


    /**
     * Returns the distinguished name of a search result.
     *
     * @param context Our DirContext
     * @param base    The base DN
     * @param result  The search result
     *
     * @return String containing the distinguished name
     *
     * @exception NamingException if a directory server error occurs
     */
    protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException {
        // Get the entry's distinguished name. For relative results, this means
        // we need to composite a name with the base name, the context name, and
        // the result name. For non-relative names, use the returned name.
        String resultName = result.getName();
        Name name;
        if (result.isRelative()) {
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("  search returned relative name: " + resultName);
            }
            NameParser parser = context.getNameParser("");
            Name contextName = parser.parse(context.getNameInNamespace());
            Name baseName = parser.parse(base);

            // Bugzilla 32269
            Name entryName = parser.parse(new CompositeName(resultName).get(0));

            name = contextName.addAll(baseName);
            name = name.addAll(entryName);
        } else {
            if (containerLog.isTraceEnabled()) {
                containerLog.trace("  search returned absolute name: " + resultName);
            }
            try {
                // Normalize the name by running it through the name parser.
                NameParser parser = context.getNameParser("");
                URI userNameUri = new URI(resultName);
                String pathComponent = userNameUri.getPath();
                // Should not ever have an empty path component, since that is /{DN}
                if (pathComponent.isEmpty()) {
                    throw new InvalidNameException(sm.getString("jndiRealm.invalidName", resultName));
                }
                name = parser.parse(pathComponent.substring(1));
            } catch (URISyntaxException e) {
                throw new InvalidNameException(sm.getString("jndiRealm.invalidName", resultName));
            }
        }

        if (getForceDnHexEscape()) {
            // Bug 63026
            return convertToHexEscape(name.toString());
        } else {
            return name.toString();
        }
    }


    /**
     * Implements the necessary escaping to represent an attribute value as a String as per RFC 4514.
     *
     * @param input The original attribute value
     *
     * @return The string representation of the attribute value
     */
    protected String doAttributeValueEscaping(String input) {
        if (input == null) {
            return null;
        }
        int len = input.length();
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < len; i++) {
            char c = input.charAt(i);
            switch (c) {
                case ' ': {
                    if (i == 0 || i == (len - 1)) {
                        result.append("\\20");
                    } else {
                        result.append(c);
                    }
                    break;
                }
                case '#': {
                    if (i == 0) {
                        result.append("\\23");
                    } else {
                        result.append(c);
                    }
                    break;
                }
                case '\"': {
                    result.append("\\22");
                    break;
                }
                case '+': {
                    result.append("\\2B");
                    break;
                }
                case ',': {
                    result.append("\\2C");
                    break;
                }
                case ';': {
                    result.append("\\3B");
                    break;
                }
                case '<': {
                    result.append("\\3C");
                    break;
                }
                case '>': {
                    result.append("\\3E");
                    break;
                }
                case '\\': {
                    result.append("\\5C");
                    break;
                }
                case '\u0000': {
                    result.append("\\00");
                    break;
                }
                default:
                    result.append(c);
            }

        }

        return result.toString();
    }


    protected static String convertToHexEscape(String input) {
        if (input.indexOf('\\') == -1) {
            // No escaping present. Return original.
            return input;
        }

        // +6 allows for 3 escaped characters by default
        StringBuilder result = new StringBuilder(input.length() + 6);
        boolean previousSlash = false;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);

            if (previousSlash) {
                switch (c) {
                    case ' ': {
                        result.append("\\20");
                        break;
                    }
                    case '\"': {
                        result.append("\\22");
                        break;
                    }
                    case '#': {
                        result.append("\\23");
                        break;
                    }
                    case '+': {
                        result.append("\\2B");
                        break;
                    }
                    case ',': {
                        result.append("\\2C");
                        break;
                    }
                    case ';': {
                        result.append("\\3B");
                        break;
                    }
                    case '<': {
                        result.append("\\3C");
                        break;
                    }
                    case '=': {
                        result.append("\\3D");
                        break;
                    }
                    case '>': {
                        result.append("\\3E");
                        break;
                    }
                    case '\\': {
                        result.append("\\5C");
                        break;
                    }
                    default:
                        result.append('\\');
                        result.append(c);
                }
                previousSlash = false;
            } else {
                if (c == '\\') {
                    previousSlash = true;
                } else {
                    result.append(c);
                }
            }
        }

        if (previousSlash) {
            result.append('\\');
        }

        return result.toString();
    }


    // ------------------------------------------------------ Protected Classes

    /**
     * A protected class representing a User
     */
    protected static class User {

        private final String username;
        private final String dn;
        private final String password;
        private final List<String> roles;
        private final String userRoleId;

        public User(String username, String dn, String password, List<String> roles, String userRoleId) {
            this.username = username;
            this.dn = dn;
            this.password = password;
            if (roles == null) {
                this.roles = Collections.emptyList();
            } else {
                this.roles = Collections.unmodifiableList(roles);
            }
            this.userRoleId = userRoleId;
        }

        public String getUserName() {
            return username;
        }

        public String getDN() {
            return dn;
        }

        public String getPassword() {
            return password;
        }

        public List<String> getRoles() {
            return roles;
        }

        public String getUserRoleId() {
            return userRoleId;
        }
    }


    /**
     * Class holding the connection to the directory plus the associated non thread safe message formats.
     */
    protected static class JNDIConnection {

        /**
         * The MessageFormat object associated with the current <code>userSearch</code>.
         */
        public final MessageFormat userSearchFormat;

        /**
         * An array of MessageFormat objects associated with the current <code>userPatternArray</code>.
         */
        public final MessageFormat[] userPatternFormatArray;

        /**
         * The MessageFormat object associated with the current <code>roleBase</code>.
         */
        public final MessageFormat roleBaseFormat;

        /**
         * The MessageFormat object associated with the current <code>roleSearch</code>.
         */
        public final MessageFormat roleFormat;

        /**
         * The directory context linking us to our directory server.
         */
        public volatile DirContext context = null;


        public JNDIConnection(String userSearch, String[] userPatternArray, String roleBase, String roleSearch) {
            if (userSearch == null) {
                userSearchFormat = null;
            } else {
                userSearchFormat = new MessageFormat(userSearch);
            }

            if (userPatternArray == null) {
                userPatternFormatArray = null;
            } else {
                int len = userPatternArray.length;
                userPatternFormatArray = new MessageFormat[len];
                for (int i = 0; i < len; i++) {
                    userPatternFormatArray[i] = new MessageFormat(userPatternArray[i]);
                }
            }

            if (roleBase == null) {
                roleBaseFormat = null;
            } else {
                roleBaseFormat = new MessageFormat(roleBase);
            }

            if (roleSearch == null) {
                roleFormat = null;
            } else {
                roleFormat = new MessageFormat(roleSearch);
            }
        }
    }
}