mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noel Rouvignac
04.57.2013 ed3418eb31bd54b0768b791ca5de353eaa7288c6
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2011-2013 ForgeRock AS.
 */
package org.opends.server.extensions;
 
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
 
import javax.net.ssl.*;
 
import org.opends.messages.Message;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.meta.
  LDAPPassThroughAuthenticationPolicyCfgDefn.MappingPolicy;
import org.opends.server.admin.std.server.*;
import org.opends.server.api.*;
import org.opends.server.config.ConfigException;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyOperation;
import org.opends.server.loggers.debug.DebugLogger;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.protocols.asn1.ASN1Exception;
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.protocols.ldap.*;
import org.opends.server.schema.GeneralizedTimeSyntax;
import org.opends.server.schema.SchemaConstants;
import org.opends.server.schema.UserPasswordSyntax;
import org.opends.server.tools.LDAPReader;
import org.opends.server.tools.LDAPWriter;
import org.opends.server.types.*;
import org.opends.server.util.TimeThread;
 
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.config.ConfigConstants.*;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
/**
 * LDAP pass through authentication policy implementation.
 */
public final class LDAPPassThroughAuthenticationPolicyFactory implements
    AuthenticationPolicyFactory<LDAPPassThroughAuthenticationPolicyCfg>
{
 
  // TODO: handle password policy response controls? AD?
  // TODO: custom aliveness pings
  // TODO: improve debug logging and error messages.
 
  /**
   * A simplistic load-balancer connection factory implementation using
   * approximately round-robin balancing.
   */
  static abstract class AbstractLoadBalancer implements ConnectionFactory,
      Runnable
  {
    /**
     * A connection which automatically retries operations on other servers.
     */
    private final class FailoverConnection implements Connection
    {
      private Connection connection;
      private MonitoredConnectionFactory factory;
      private final int startIndex;
      private int nextIndex;
 
 
 
      private FailoverConnection(final int startIndex)
          throws DirectoryException
      {
        this.startIndex = nextIndex = startIndex;
 
        DirectoryException lastException;
        do
        {
          factory = factories[nextIndex];
          if (factory.isAvailable)
          {
            try
            {
              connection = factory.getConnection();
              incrementNextIndex();
              return;
            }
            catch (final DirectoryException e)
            {
              // Ignore this error and try the next factory.
              if (debugEnabled())
              {
                TRACER.debugCaught(DebugLogLevel.ERROR, e);
              }
              lastException = e;
            }
          }
          else
          {
            lastException = factory.lastException;
          }
          incrementNextIndex();
        }
        while (nextIndex != startIndex);
 
        // All the factories have been tried so give up and throw the exception.
        throw lastException;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void close()
      {
        connection.close();
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public ByteString search(final DN baseDN, final SearchScope scope,
          final SearchFilter filter) throws DirectoryException
      {
        for (;;)
        {
          try
          {
            return connection.search(baseDN, scope, filter);
          }
          catch (final DirectoryException e)
          {
            if (debugEnabled())
            {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }
            handleDirectoryException(e);
          }
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void simpleBind(final ByteString username,
          final ByteString password) throws DirectoryException
      {
        for (;;)
        {
          try
          {
            connection.simpleBind(username, password);
            return;
          }
          catch (final DirectoryException e)
          {
            if (debugEnabled())
            {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }
            handleDirectoryException(e);
          }
        }
      }
 
 
 
      private void handleDirectoryException(final DirectoryException e)
          throws DirectoryException
      {
        // If the error does not indicate that the connection has failed, then
        // pass this back to the caller.
        if (!isServiceError(e.getResultCode()))
        {
          throw e;
        }
 
        // The associated server is unavailable, so close the connection and
        // try the next connection factory.
        connection.close();
        factory.lastException = e;
        factory.isAvailable = false; // publishes lastException
 
        while (nextIndex != startIndex)
        {
          factory = factories[nextIndex];
          if (factory.isAvailable)
          {
            try
            {
              connection = factory.getConnection();
              incrementNextIndex();
              return;
            }
            catch (final DirectoryException de)
            {
              // Ignore this error and try the next factory.
              if (debugEnabled())
              {
                TRACER.debugCaught(DebugLogLevel.ERROR, de);
              }
            }
          }
          incrementNextIndex();
        }
 
        // All the factories have been tried so give up and throw the exception.
        throw e;
      }
 
 
 
      private void incrementNextIndex()
      {
        // Try the next index.
        if (++nextIndex == maxIndex)
        {
          nextIndex = 0;
        }
      }
 
    }
 
 
 
    /**
     * A connection factory which caches its online/offline state in order to
     * avoid unnecessary connection attempts when it is known to be offline.
     */
    private final class MonitoredConnectionFactory implements ConnectionFactory
    {
      private final ConnectionFactory factory;
 
      // isAvailable acts as memory barrier for lastException.
      private volatile boolean isAvailable = true;
      private DirectoryException lastException = null;
 
 
 
      private MonitoredConnectionFactory(final ConnectionFactory factory)
      {
        this.factory = factory;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void close()
      {
        factory.close();
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public Connection getConnection() throws DirectoryException
      {
        try
        {
          final Connection connection = factory.getConnection();
          isAvailable = true;
          return connection;
        }
        catch (final DirectoryException e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
          lastException = e;
          isAvailable = false; // publishes lastException
          throw e;
        }
      }
    }
 
 
 
    private final MonitoredConnectionFactory[] factories;
    private final int maxIndex;
    private final ScheduledFuture<?> monitorFuture;
 
 
 
    /**
     * Creates a new abstract load-balancer.
     *
     * @param factories
     *          The list of underlying connection factories.
     * @param scheduler
     *          The monitoring scheduler.
     */
    AbstractLoadBalancer(final ConnectionFactory[] factories,
        final ScheduledExecutorService scheduler)
    {
      this.factories = new MonitoredConnectionFactory[factories.length];
      this.maxIndex = factories.length;
 
      for (int i = 0; i < maxIndex; i++)
      {
        this.factories[i] = new MonitoredConnectionFactory(factories[i]);
      }
 
      this.monitorFuture = scheduler.scheduleWithFixedDelay(this, 5, 5,
          TimeUnit.SECONDS);
    }
 
 
 
    /**
     * Close underlying connection pools.
     */
    @Override
    public final void close()
    {
      monitorFuture.cancel(true);
 
      for (final ConnectionFactory factory : factories)
      {
        factory.close();
      }
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final Connection getConnection() throws DirectoryException
    {
      final int startIndex = getStartIndex();
      return new FailoverConnection(startIndex);
    }
 
 
 
    /**
     * Try to connect to any offline connection factories.
     */
    @Override
    public void run()
    {
      for (final MonitoredConnectionFactory factory : factories)
      {
        if (!factory.isAvailable)
        {
          try
          {
            factory.getConnection().close();
          }
          catch (final DirectoryException e)
          {
            if (debugEnabled())
            {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }
          }
        }
      }
    }
 
 
 
    /**
     * Return the start which should be used for the next connection attempt.
     *
     * @return The start which should be used for the next connection attempt.
     */
    abstract int getStartIndex();
 
  }
 
 
 
  /**
   * A factory which returns pre-authenticated connections for searches.
   * <p>
   * Package private for testing.
   */
  static final class AuthenticatedConnectionFactory implements
      ConnectionFactory
  {
 
    private final ConnectionFactory factory;
    private final DN username;
    private final String password;
 
 
 
    /**
     * Creates a new authenticated connection factory which will bind on
     * connect.
     *
     * @param factory
     *          The underlying connection factory whose connections are to be
     *          authenticated.
     * @param username
     *          The username taken from the configuration.
     * @param password
     *          The password taken from the configuration.
     */
    AuthenticatedConnectionFactory(final ConnectionFactory factory,
        final DN username, final String password)
    {
      this.factory = factory;
      this.username = username;
      this.password = password;
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public void close()
    {
      factory.close();
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public Connection getConnection() throws DirectoryException
    {
      final Connection connection = factory.getConnection();
      if (username != null && !username.isNullDN() && password != null
          && password.length() > 0)
      {
        try
        {
          connection.simpleBind(ByteString.valueOf(username.toString()),
              ByteString.valueOf(password));
        }
        catch (final DirectoryException e)
        {
          connection.close();
          throw e;
        }
      }
      return connection;
    }
 
  }
 
 
 
  /**
   * An LDAP connection which will be used in order to search for or
   * authenticate users.
   */
  static interface Connection extends Closeable
  {
 
    /**
     * Closes this connection.
     */
    @Override
    void close();
 
 
 
    /**
     * Returns the name of the user whose entry matches the provided search
     * criteria. This will return CLIENT_SIDE_NO_RESULTS_RETURNED/NO_SUCH_OBJECT
     * if no search results were returned, or CLIENT_SIDE_MORE_RESULTS_TO_RETURN
     * if too many results were returned.
     *
     * @param baseDN
     *          The search base DN.
     * @param scope
     *          The search scope.
     * @param filter
     *          The search filter.
     * @return The name of the user whose entry matches the provided search
     *         criteria.
     * @throws DirectoryException
     *           If the search returned no entries, more than one entry, or if
     *           the search failed unexpectedly.
     */
    ByteString search(DN baseDN, SearchScope scope, SearchFilter filter)
        throws DirectoryException;
 
 
 
    /**
     * Performs a simple bind for the user.
     *
     * @param username
     *          The user name (usually a bind DN).
     * @param password
     *          The user's password.
     * @throws DirectoryException
     *           If the credentials were invalid, or the authentication failed
     *           unexpectedly.
     */
    void simpleBind(ByteString username, ByteString password)
        throws DirectoryException;
  }
 
 
 
  /**
   * An interface for obtaining connections: users of this interface will obtain
   * a connection, perform a single operation (search or bind), and then close
   * it.
   */
  static interface ConnectionFactory extends Closeable
  {
    /**
     * {@inheritDoc}
     * <p>
     * Must never throw an exception.
     */
    @Override
    void close();
 
 
 
    /**
     * Returns a connection which can be used in order to search for or
     * authenticate users.
     *
     * @return The connection.
     * @throws DirectoryException
     *           If an unexpected error occurred while attempting to obtain a
     *           connection.
     */
    Connection getConnection() throws DirectoryException;
  }
 
 
 
  /**
   * PTA connection pool.
   * <p>
   * Package private for testing.
   */
  static final class ConnectionPool implements ConnectionFactory
  {
 
    /**
     * Pooled connection's intercept close and release connection back to the
     * pool.
     */
    private final class PooledConnection implements Connection
    {
      private Connection connection;
      private boolean connectionIsClosed = false;
 
 
 
      private PooledConnection(final Connection connection)
      {
        this.connection = connection;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void close()
      {
        if (!connectionIsClosed)
        {
          connectionIsClosed = true;
 
          // Guarded by PolicyImpl
          if (poolIsClosed)
          {
            connection.close();
          }
          else
          {
            connectionPool.offer(connection);
          }
 
          connection = null;
          availableConnections.release();
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public ByteString search(final DN baseDN, final SearchScope scope,
          final SearchFilter filter) throws DirectoryException
      {
        try
        {
          return connection.search(baseDN, scope, filter);
        }
        catch (final DirectoryException e1)
        {
          // Fail immediately if the result indicates that the operation failed
          // for a reason other than connection/server failure.
          reconnectIfConnectionFailure(e1);
 
          // The connection has failed, so retry the operation using the new
          // connection.
          try
          {
            return connection.search(baseDN, scope, filter);
          }
          catch (final DirectoryException e2)
          {
            // If the connection has failed again then give up: don't put the
            // connection back in the pool.
            closeIfConnectionFailure(e2);
            throw e2;
          }
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void simpleBind(final ByteString username,
          final ByteString password) throws DirectoryException
      {
        try
        {
          connection.simpleBind(username, password);
        }
        catch (final DirectoryException e1)
        {
          // Fail immediately if the result indicates that the operation failed
          // for a reason other than connection/server failure.
          reconnectIfConnectionFailure(e1);
 
          // The connection has failed, so retry the operation using the new
          // connection.
          try
          {
            connection.simpleBind(username, password);
          }
          catch (final DirectoryException e2)
          {
            // If the connection has failed again then give up: don't put the
            // connection back in the pool.
            closeIfConnectionFailure(e2);
            throw e2;
          }
        }
      }
 
 
 
      private void closeIfConnectionFailure(final DirectoryException e)
          throws DirectoryException
      {
        if (isServiceError(e.getResultCode()))
        {
          connectionIsClosed = true;
          connection.close();
          connection = null;
          availableConnections.release();
        }
      }
 
 
 
      private void reconnectIfConnectionFailure(final DirectoryException e)
          throws DirectoryException
      {
        if (!isServiceError(e.getResultCode()))
        {
          throw e;
        }
 
        // The connection has failed (e.g. idle timeout), so repeat the
        // request on a new connection.
        connection.close();
        try
        {
          connection = factory.getConnection();
        }
        catch (final DirectoryException e2)
        {
          // Give up - the server is unreachable.
          connectionIsClosed = true;
          connection = null;
          availableConnections.release();
          throw e2;
        }
      }
    }
 
 
 
    // Guarded by PolicyImpl.lock.
    private boolean poolIsClosed = false;
 
    private final ConnectionFactory factory;
    private final int poolSize = Runtime.getRuntime().availableProcessors() * 2;
    private final Semaphore availableConnections = new Semaphore(poolSize);
    private final Queue<Connection> connectionPool =
      new ConcurrentLinkedQueue<Connection>();
 
 
 
    /**
     * Creates a new connection pool for the provided factory.
     *
     * @param factory
     *          The underlying connection factory whose connections are to be
     *          pooled.
     */
    ConnectionPool(final ConnectionFactory factory)
    {
      this.factory = factory;
    }
 
 
 
    /**
     * Release all connections: do we want to block?
     */
    @Override
    public void close()
    {
      // No need for synchronization as this can only be called with the
      // policy's exclusive lock.
      poolIsClosed = true;
 
      Connection connection;
      while ((connection = connectionPool.poll()) != null)
      {
        connection.close();
      }
 
      factory.close();
 
      // Since we have the exclusive lock, there should be no more connections
      // in use.
      if (availableConnections.availablePermits() != poolSize)
      {
        throw new IllegalStateException(
            "Pool has remaining connections open after close");
      }
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public Connection getConnection() throws DirectoryException
    {
      // This should only be called with the policy's shared lock.
      if (poolIsClosed)
      {
        throw new IllegalStateException("pool is closed");
      }
 
      availableConnections.acquireUninterruptibly();
 
      // There is either a pooled connection or we are allowed to create
      // one.
      Connection connection = connectionPool.poll();
      if (connection == null)
      {
        try
        {
          connection = factory.getConnection();
        }
        catch (final DirectoryException e)
        {
          availableConnections.release();
          throw e;
        }
      }
 
      return new PooledConnection(connection);
    }
  }
 
 
 
  /**
   * A simplistic two-way fail-over connection factory implementation.
   * <p>
   * Package private for testing.
   */
  static final class FailoverLoadBalancer extends AbstractLoadBalancer
  {
 
    /**
     * Creates a new fail-over connection factory which will always try the
     * primary connection factory first, before trying the second.
     *
     * @param primary
     *          The primary connection factory.
     * @param secondary
     *          The secondary connection factory.
     * @param scheduler
     *          The monitoring scheduler.
     */
    FailoverLoadBalancer(final ConnectionFactory primary,
        final ConnectionFactory secondary,
        final ScheduledExecutorService scheduler)
    {
      super(new ConnectionFactory[] { primary, secondary }, scheduler);
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    int getStartIndex()
    {
      // Always start with the primaries.
      return 0;
    }
 
  }
 
 
 
  /**
   * The PTA design guarantees that connections are only used by a single thread
   * at a time, so we do not need to perform any synchronization.
   * <p>
   * Package private for testing.
   */
  static final class LDAPConnectionFactory implements ConnectionFactory
  {
    /**
     * LDAP connection implementation.
     */
    private final class LDAPConnection implements Connection
    {
      private final Socket plainSocket;
      private final Socket ldapSocket;
      private final LDAPWriter writer;
      private final LDAPReader reader;
      private int nextMessageID = 1;
      private boolean isClosed = false;
 
 
 
      private LDAPConnection(final Socket plainSocket, final Socket ldapSocket,
          final LDAPReader reader, final LDAPWriter writer)
      {
        this.plainSocket = plainSocket;
        this.ldapSocket = ldapSocket;
        this.reader = reader;
        this.writer = writer;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void close()
      {
        /*
         * This method is intentionally a bit "belt and braces" because we have
         * seen far too many subtle resource leaks due to bugs within JDK,
         * especially when used in conjunction with SSL (e.g.
         * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7025227).
         */
        if (isClosed)
        {
          return;
        }
        isClosed = true;
 
        // Send an unbind request.
        final LDAPMessage message = new LDAPMessage(nextMessageID++,
            new UnbindRequestProtocolOp());
        try
        {
          writer.writeMessage(message);
        }
        catch (final IOException e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
        }
 
        // Close all IO resources.
        writer.close();
        reader.close();
 
        try
        {
          ldapSocket.close();
        }
        catch (final IOException e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
        }
 
        try
        {
          plainSocket.close();
        }
        catch (final IOException e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public ByteString search(final DN baseDN, final SearchScope scope,
          final SearchFilter filter) throws DirectoryException
      {
        // Create the search request and send it to the server.
        final SearchRequestProtocolOp searchRequest =
          new SearchRequestProtocolOp(
            ByteString.valueOf(baseDN.toString()), scope,
            DereferencePolicy.DEREF_ALWAYS, 1 /* size limit */,
            (timeoutMS / 1000), true /* types only */,
            RawFilter.create(filter), NO_ATTRIBUTES);
        sendRequest(searchRequest);
 
        // Read the responses from the server. We cannot fail-fast since this
        // could leave unread search response messages.
        byte opType;
        ByteString username = null;
        int resultCount = 0;
 
        do
        {
          final LDAPMessage responseMessage = readResponse();
          opType = responseMessage.getProtocolOpType();
 
          switch (opType)
          {
          case OP_TYPE_SEARCH_RESULT_ENTRY:
            final SearchResultEntryProtocolOp searchEntry = responseMessage
                .getSearchResultEntryProtocolOp();
            if (username == null)
            {
              username = ByteString.valueOf(searchEntry.getDN().toString());
            }
            resultCount++;
            break;
 
          case OP_TYPE_SEARCH_RESULT_REFERENCE:
            // The reference does not necessarily mean that there would have
            // been any matching results, so lets ignore it.
            break;
 
          case OP_TYPE_SEARCH_RESULT_DONE:
            final SearchResultDoneProtocolOp searchResult = responseMessage
                .getSearchResultDoneProtocolOp();
 
            final ResultCode resultCode = ResultCode.valueOf(searchResult
                .getResultCode());
            switch (resultCode)
            {
            case SUCCESS:
              // The search succeeded. Drop out of the loop and check that we
              // got a matching entry.
              break;
 
            case SIZE_LIMIT_EXCEEDED:
              // Multiple matching candidates.
              throw new DirectoryException(
                  ResultCode.CLIENT_SIDE_MORE_RESULTS_TO_RETURN,
                  ERR_LDAP_PTA_CONNECTION_SEARCH_SIZE_LIMIT.get(host, port,
                      String.valueOf(cfg.dn()), String.valueOf(baseDN),
                      String.valueOf(filter)));
 
            default:
              // The search failed for some reason.
              throw new DirectoryException(resultCode,
                  ERR_LDAP_PTA_CONNECTION_SEARCH_FAILED.get(host, port,
                      String.valueOf(cfg.dn()), String.valueOf(baseDN),
                      String.valueOf(filter), resultCode.getIntValue(),
                      resultCode.getResultCodeName(),
                      searchResult.getErrorMessage()));
            }
 
            break;
 
          default:
            // Check for disconnect notifications.
            handleUnexpectedResponse(responseMessage);
            break;
          }
        }
        while (opType != OP_TYPE_SEARCH_RESULT_DONE);
 
        if (resultCount > 1)
        {
          // Multiple matching candidates.
          throw new DirectoryException(
              ResultCode.CLIENT_SIDE_MORE_RESULTS_TO_RETURN,
              ERR_LDAP_PTA_CONNECTION_SEARCH_SIZE_LIMIT.get(host, port,
                  String.valueOf(cfg.dn()), String.valueOf(baseDN),
                  String.valueOf(filter)));
        }
 
        if (username == null)
        {
          // No matching entries found.
          throw new DirectoryException(
              ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED,
              ERR_LDAP_PTA_CONNECTION_SEARCH_NO_MATCHES.get(host, port,
                  String.valueOf(cfg.dn()), String.valueOf(baseDN),
                  String.valueOf(filter)));
        }
 
        return username;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void simpleBind(final ByteString username,
          final ByteString password) throws DirectoryException
      {
        // Create the bind request and send it to the server.
        final BindRequestProtocolOp bindRequest = new BindRequestProtocolOp(
            username, 3, password);
        sendRequest(bindRequest);
 
        // Read the response from the server.
        final LDAPMessage responseMessage = readResponse();
        switch (responseMessage.getProtocolOpType())
        {
        case OP_TYPE_BIND_RESPONSE:
          final BindResponseProtocolOp bindResponse = responseMessage
              .getBindResponseProtocolOp();
 
          final ResultCode resultCode = ResultCode.valueOf(bindResponse
              .getResultCode());
          if (resultCode == ResultCode.SUCCESS)
          {
            // FIXME: need to look for things like password expiration
            // warning, reset notice, etc.
            return;
          }
          else
          {
            // The bind failed for some reason.
            throw new DirectoryException(resultCode,
                ERR_LDAP_PTA_CONNECTION_BIND_FAILED.get(host, port,
                    String.valueOf(cfg.dn()), String.valueOf(username),
                    resultCode.getIntValue(), resultCode.getResultCodeName(),
                    bindResponse.getErrorMessage()));
          }
 
        default:
          // Check for disconnect notifications.
          handleUnexpectedResponse(responseMessage);
          break;
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      protected void finalize()
      {
        close();
      }
 
 
 
      private void handleUnexpectedResponse(final LDAPMessage responseMessage)
          throws DirectoryException
      {
        if (responseMessage.getProtocolOpType() == OP_TYPE_EXTENDED_RESPONSE)
        {
          final ExtendedResponseProtocolOp extendedResponse = responseMessage
              .getExtendedResponseProtocolOp();
          final String responseOID = extendedResponse.getOID();
 
          if ((responseOID != null)
              && responseOID.equals(OID_NOTICE_OF_DISCONNECTION))
          {
            ResultCode resultCode = ResultCode.valueOf(extendedResponse
                .getResultCode());
 
            /*
             * Since the connection has been disconnected we want to ensure that
             * upper layers treat all disconnect notifications as fatal and
             * close the connection. Therefore we map the result code to a fatal
             * error code if needed. A good example of a non-fatal error code
             * being returned is INVALID_CREDENTIALS which is used to indicate
             * that the currently bound user has had their entry removed. We
             * definitely don't want to pass this straight back to the caller
             * since it will be misinterpreted as an authentication failure if
             * the operation being performed is a bind.
             */
            ResultCode mappedResultCode = isServiceError(resultCode) ?
                resultCode : ResultCode.UNAVAILABLE;
 
            throw new DirectoryException(mappedResultCode,
                ERR_LDAP_PTA_CONNECTION_DISCONNECTING.get(host, port,
                    String.valueOf(cfg.dn()), resultCode.getIntValue(),
                    resultCode.getResultCodeName(),
                    extendedResponse.getErrorMessage()));
          }
        }
 
        // Unexpected response type.
        throw new DirectoryException(ResultCode.CLIENT_SIDE_DECODING_ERROR,
            ERR_LDAP_PTA_CONNECTION_WRONG_RESPONSE.get(host, port,
                String.valueOf(cfg.dn()),
                String.valueOf(responseMessage.getProtocolOp())));
      }
 
 
 
      // Reads a response message and adapts errors to directory exceptions.
      private LDAPMessage readResponse() throws DirectoryException
      {
        final LDAPMessage responseMessage;
        try
        {
          responseMessage = reader.readMessage();
        }
        catch (final ASN1Exception e)
        {
          // ASN1 layer hides all underlying IO exceptions.
          if (e.getCause() instanceof SocketTimeoutException)
          {
            throw new DirectoryException(ResultCode.CLIENT_SIDE_TIMEOUT,
                ERR_LDAP_PTA_CONNECTION_TIMEOUT.get(host, port,
                    String.valueOf(cfg.dn())), e);
          }
          else if (e.getCause() instanceof IOException)
          {
            throw new DirectoryException(ResultCode.CLIENT_SIDE_SERVER_DOWN,
                ERR_LDAP_PTA_CONNECTION_OTHER_ERROR.get(host, port,
                    String.valueOf(cfg.dn()), e.getMessage()), e);
          }
          else
          {
            throw new DirectoryException(ResultCode.CLIENT_SIDE_DECODING_ERROR,
                ERR_LDAP_PTA_CONNECTION_DECODE_ERROR.get(host, port,
                    String.valueOf(cfg.dn()), e.getMessage()), e);
          }
        }
        catch (final LDAPException e)
        {
          throw new DirectoryException(ResultCode.CLIENT_SIDE_DECODING_ERROR,
              ERR_LDAP_PTA_CONNECTION_DECODE_ERROR.get(host, port,
                  String.valueOf(cfg.dn()), e.getMessage()), e);
        }
        catch (final SocketTimeoutException e)
        {
          throw new DirectoryException(ResultCode.CLIENT_SIDE_TIMEOUT,
              ERR_LDAP_PTA_CONNECTION_TIMEOUT.get(host, port,
                  String.valueOf(cfg.dn())), e);
        }
        catch (final IOException e)
        {
          throw new DirectoryException(ResultCode.CLIENT_SIDE_SERVER_DOWN,
              ERR_LDAP_PTA_CONNECTION_OTHER_ERROR.get(host, port,
                  String.valueOf(cfg.dn()), e.getMessage()), e);
        }
 
        if (responseMessage == null)
        {
          throw new DirectoryException(ResultCode.CLIENT_SIDE_SERVER_DOWN,
              ERR_LDAP_PTA_CONNECTION_CLOSED.get(host, port,
                  String.valueOf(cfg.dn())));
        }
        return responseMessage;
      }
 
 
 
      // Sends a request message and adapts errors to directory exceptions.
      private void sendRequest(final ProtocolOp request)
          throws DirectoryException
      {
        final LDAPMessage requestMessage = new LDAPMessage(nextMessageID++,
            request);
        try
        {
          writer.writeMessage(requestMessage);
        }
        catch (final IOException e)
        {
          throw new DirectoryException(ResultCode.CLIENT_SIDE_SERVER_DOWN,
              ERR_LDAP_PTA_CONNECTION_OTHER_ERROR.get(host, port,
                  String.valueOf(cfg.dn()), e.getMessage()), e);
        }
      }
    }
 
 
 
    private final String host;
    private final int port;
    private final LDAPPassThroughAuthenticationPolicyCfg cfg;
    private final int timeoutMS;
 
 
 
    /**
     * LDAP connection factory implementation is package private so that it can
     * be tested.
     *
     * @param host
     *          The server host name.
     * @param port
     *          The server port.
     * @param cfg
     *          The configuration (for SSL).
     */
    LDAPConnectionFactory(final String host, final int port,
        final LDAPPassThroughAuthenticationPolicyCfg cfg)
    {
      this.host = host;
      this.port = port;
      this.cfg = cfg;
 
      // Normalize the timeoutMS to an integer (admin framework ensures that the
      // value is non-negative).
      this.timeoutMS = (int) Math.min(cfg.getConnectionTimeout(),
          Integer.MAX_VALUE);
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public void close()
    {
      // Nothing to do.
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public Connection getConnection() throws DirectoryException
    {
      try
      {
        // Create the remote ldapSocket address.
        final InetAddress address = InetAddress.getByName(host);
        final InetSocketAddress socketAddress = new InetSocketAddress(address,
            port);
 
        // Create the ldapSocket and connect to the remote server.
        final Socket plainSocket = new Socket();
        Socket ldapSocket = null;
        LDAPReader reader = null;
        LDAPWriter writer = null;
        LDAPConnection ldapConnection = null;
 
        try
        {
          // Set ldapSocket cfg before connecting.
          plainSocket.setTcpNoDelay(cfg.isUseTCPNoDelay());
          plainSocket.setKeepAlive(cfg.isUseTCPKeepAlive());
          plainSocket.setSoTimeout(timeoutMS);
 
          // Connect the ldapSocket.
          plainSocket.connect(socketAddress, timeoutMS);
 
          if (cfg.isUseSSL())
          {
            // Obtain the optional configured trust manager which will be used
            // in order to determine the trust of the remote LDAP server.
            TrustManager[] tm = null;
            final DN trustManagerDN = cfg.getTrustManagerProviderDN();
            if (trustManagerDN != null)
            {
              final TrustManagerProvider<?> trustManagerProvider =
                DirectoryServer.getTrustManagerProvider(trustManagerDN);
              if (trustManagerProvider != null)
              {
                tm = trustManagerProvider.getTrustManagers();
              }
            }
 
            // Create the SSL context and initialize it.
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null /* key managers */, tm, null /* rng */);
 
            // Create the SSL socket.
            final SSLSocketFactory sslSocketFactory = sslContext
                .getSocketFactory();
            final SSLSocket sslSocket = (SSLSocket) sslSocketFactory
                .createSocket(plainSocket, host, port, true);
            ldapSocket = sslSocket;
 
            sslSocket.setUseClientMode(true);
            if (!cfg.getSSLProtocol().isEmpty())
            {
              sslSocket.setEnabledProtocols(cfg.getSSLProtocol().toArray(
                  new String[0]));
            }
            if (!cfg.getSSLCipherSuite().isEmpty())
            {
              sslSocket.setEnabledCipherSuites(cfg.getSSLCipherSuite().toArray(
                  new String[0]));
            }
 
            // Force TLS negotiation.
            sslSocket.startHandshake();
          }
          else
          {
            ldapSocket = plainSocket;
          }
 
          reader = new LDAPReader(ldapSocket);
          writer = new LDAPWriter(ldapSocket);
 
          ldapConnection = new LDAPConnection(plainSocket, ldapSocket, reader,
              writer);
 
          return ldapConnection;
        }
        finally
        {
          if (ldapConnection == null)
          {
            // Connection creation failed for some reason, so clean up IO
            // resources.
            if (reader != null)
            {
              reader.close();
            }
            if (writer != null)
            {
              writer.close();
            }
 
            if (ldapSocket != null)
            {
              try
              {
                ldapSocket.close();
              }
              catch (final IOException ignored)
              {
                // Ignore.
              }
            }
 
            if (ldapSocket != plainSocket)
            {
              try
              {
                plainSocket.close();
              }
              catch (final IOException ignored)
              {
                // Ignore.
              }
            }
          }
        }
      }
      catch (final UnknownHostException e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        throw new DirectoryException(ResultCode.CLIENT_SIDE_CONNECT_ERROR,
            ERR_LDAP_PTA_CONNECT_UNKNOWN_HOST.get(host, port,
                String.valueOf(cfg.dn()), host), e);
      }
      catch (final ConnectException e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        throw new DirectoryException(ResultCode.CLIENT_SIDE_CONNECT_ERROR,
            ERR_LDAP_PTA_CONNECT_ERROR.get(host, port,
                String.valueOf(cfg.dn()), port), e);
      }
      catch (final SocketTimeoutException e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        throw new DirectoryException(ResultCode.CLIENT_SIDE_TIMEOUT,
            ERR_LDAP_PTA_CONNECT_TIMEOUT.get(host, port,
                String.valueOf(cfg.dn())), e);
      }
      catch (final SSLException e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        throw new DirectoryException(ResultCode.CLIENT_SIDE_CONNECT_ERROR,
            ERR_LDAP_PTA_CONNECT_SSL_ERROR.get(host, port,
                String.valueOf(cfg.dn()), e.getMessage()), e);
      }
      catch (final Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        throw new DirectoryException(ResultCode.CLIENT_SIDE_CONNECT_ERROR,
            ERR_LDAP_PTA_CONNECT_OTHER_ERROR.get(host, port,
                String.valueOf(cfg.dn()), e.getMessage()), e);
      }
 
    }
  }
 
 
 
  /**
   * An interface for obtaining a connection factory for LDAP connections to a
   * named LDAP server and the monitoring scheduler.
   */
  static interface Provider
  {
    /**
     * Returns a connection factory which can be used for obtaining connections
     * to the specified LDAP server.
     *
     * @param host
     *          The LDAP server host name.
     * @param port
     *          The LDAP server port.
     * @param cfg
     *          The LDAP connection configuration.
     * @return A connection factory which can be used for obtaining connections
     *         to the specified LDAP server.
     */
    ConnectionFactory getLDAPConnectionFactory(String host, int port,
        LDAPPassThroughAuthenticationPolicyCfg cfg);
 
 
 
    /**
     * Returns the scheduler which should be used to periodically ping
     * connection factories to determine when they are online.
     *
     * @return The scheduler which should be used to periodically ping
     *         connection factories to determine when they are online.
     */
    ScheduledExecutorService getScheduledExecutorService();
 
 
 
    /**
     * Returns the current time in order to perform cached password expiration
     * checks. The returned string will be formatted as a a generalized time
     * string
     *
     * @return The current time.
     */
    String getCurrentTime();
 
 
 
    /**
     * Returns the current time in order to perform cached password expiration
     * checks.
     *
     * @return The current time in MS.
     */
    long getCurrentTimeMS();
  }
 
 
 
  /**
   * A simplistic load-balancer connection factory implementation using
   * approximately round-robin balancing.
   */
  static final class RoundRobinLoadBalancer extends AbstractLoadBalancer
  {
    private final AtomicInteger nextIndex = new AtomicInteger();
    private final int maxIndex;
 
 
 
    /**
     * Creates a new load-balancer which will distribute connection requests
     * across a set of underlying connection factories.
     *
     * @param factories
     *          The list of underlying connection factories.
     * @param scheduler
     *          The monitoring scheduler.
     */
    RoundRobinLoadBalancer(final ConnectionFactory[] factories,
        final ScheduledExecutorService scheduler)
    {
      super(factories, scheduler);
      this.maxIndex = factories.length;
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    int getStartIndex()
    {
      // A round robin pool of one connection factories is unlikely in
      // practice and requires special treatment.
      if (maxIndex == 1)
      {
        return 0;
      }
 
      // Determine the next factory to use: avoid blocking algorithm.
      int oldNextIndex;
      int newNextIndex;
      do
      {
        oldNextIndex = nextIndex.get();
        newNextIndex = oldNextIndex + 1;
        if (newNextIndex == maxIndex)
        {
          newNextIndex = 0;
        }
      }
      while (!nextIndex.compareAndSet(oldNextIndex, newNextIndex));
 
      // There's a potential, but benign, race condition here: other threads
      // could jump in and rotate through the list before we return the
      // connection factory.
      return oldNextIndex;
    }
 
  }
 
 
 
  /**
   * LDAP PTA policy implementation.
   */
  private final class PolicyImpl extends AuthenticationPolicy implements
      ConfigurationChangeListener<LDAPPassThroughAuthenticationPolicyCfg>
  {
 
    /**
     * LDAP PTA policy state implementation.
     */
    private final class StateImpl extends AuthenticationPolicyState
    {
 
      private final AttributeType cachedPasswordAttribute;
      private final AttributeType cachedPasswordTimeAttribute;
 
      private ByteString newCachedPassword = null;
 
 
 
 
      private StateImpl(final Entry userEntry)
      {
        super(userEntry);
 
        this.cachedPasswordAttribute = DirectoryServer.getAttributeType(
            OP_ATTR_PTAPOLICY_CACHED_PASSWORD, true);
        this.cachedPasswordTimeAttribute = DirectoryServer.getAttributeType(
            OP_ATTR_PTAPOLICY_CACHED_PASSWORD_TIME, true);
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public void finalizeStateAfterBind() throws DirectoryException
      {
        sharedLock.lock();
        try
        {
          if (cfg.isUsePasswordCaching() && newCachedPassword != null)
          {
            // Update the user's entry to contain the cached password and
            // time stamp.
            ByteString encodedPassword = pwdStorageScheme
                .encodePasswordWithScheme(newCachedPassword);
 
            List<RawModification> modifications =
              new ArrayList<RawModification>(2);
            modifications.add(RawModification.create(ModificationType.REPLACE,
                OP_ATTR_PTAPOLICY_CACHED_PASSWORD, encodedPassword));
            modifications.add(RawModification.create(ModificationType.REPLACE,
                OP_ATTR_PTAPOLICY_CACHED_PASSWORD_TIME,
                provider.getCurrentTime()));
 
            InternalClientConnection conn = InternalClientConnection
                .getRootConnection();
            ModifyOperation internalModify = conn.processModify(userEntry
                .getDN().toString(), modifications);
 
            ResultCode resultCode = internalModify.getResultCode();
            if (resultCode != ResultCode.SUCCESS)
            {
              // The modification failed for some reason. This should not
              // prevent the bind from succeeded since we are only updating
              // cache data. However, the performance of the server may be
              // impacted, so log a debug warning message.
              if (debugEnabled())
              {
                TRACER.debugWarning(
                    "An error occurred while trying to update the LDAP PTA "
                        + "cached password for user %s: %s", userEntry.getDN()
                        .toString(), String.valueOf(internalModify
                        .getErrorMessage()));
              }
            }
 
            newCachedPassword = null;
          }
        }
        finally
        {
          sharedLock.unlock();
        }
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public AuthenticationPolicy getAuthenticationPolicy()
      {
        return PolicyImpl.this;
      }
 
 
 
      /**
       * {@inheritDoc}
       */
      @Override
      public boolean passwordMatches(final ByteString password)
          throws DirectoryException
      {
        sharedLock.lock();
        try
        {
          // First check the cached password if enabled and available.
          if (passwordMatchesCachedPassword(password))
          {
            return true;
          }
 
          // The cache lookup failed, so perform full PTA.
          ByteString username = null;
 
          switch (cfg.getMappingPolicy())
          {
          case UNMAPPED:
            // The bind DN is the name of the user's entry.
            username = ByteString.valueOf(userEntry.getDN().toString());
            break;
          case MAPPED_BIND:
            // The bind DN is contained in an attribute in the user's entry.
            mapBind: for (final AttributeType at : cfg.getMappedAttribute())
            {
              final List<Attribute> attributes = userEntry.getAttribute(at);
              if (attributes != null && !attributes.isEmpty())
              {
                for (final Attribute attribute : attributes)
                {
                  if (!attribute.isEmpty())
                  {
                    username = attribute.iterator().next().getValue();
                    break mapBind;
                  }
                }
              }
            }
 
            if (username == null)
            {
              /*
               * The mapping attribute(s) is not present in the entry. This
               * could be a configuration error, but it could also be because
               * someone is attempting to authenticate using a bind DN which
               * references a non-user entry.
               */
              throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                  ERR_LDAP_PTA_MAPPING_ATTRIBUTE_NOT_FOUND.get(
                      String.valueOf(userEntry.getDN()),
                      String.valueOf(cfg.dn()),
                      mappedAttributesAsString(cfg.getMappedAttribute())));
            }
 
            break;
          case MAPPED_SEARCH:
            // A search against the remote directory is required in order to
            // determine the bind DN.
 
            // Construct the search filter.
            final LinkedList<SearchFilter> filterComponents =
              new LinkedList<SearchFilter>();
            for (final AttributeType at : cfg.getMappedAttribute())
            {
              final List<Attribute> attributes = userEntry.getAttribute(at);
              if (attributes != null && !attributes.isEmpty())
              {
                for (final Attribute attribute : attributes)
                {
                  for (final AttributeValue value : attribute)
                  {
                    filterComponents.add(SearchFilter.createEqualityFilter(at,
                        value));
                  }
                }
              }
            }
 
            if (filterComponents.isEmpty())
            {
              /*
               * The mapping attribute(s) is not present in the entry. This
               * could be a configuration error, but it could also be because
               * someone is attempting to authenticate using a bind DN which
               * references a non-user entry.
               */
              throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                  ERR_LDAP_PTA_MAPPING_ATTRIBUTE_NOT_FOUND.get(
                      String.valueOf(userEntry.getDN()),
                      String.valueOf(cfg.dn()),
                      mappedAttributesAsString(cfg.getMappedAttribute())));
            }
 
            final SearchFilter filter;
            if (filterComponents.size() == 1)
            {
              filter = filterComponents.getFirst();
            }
            else
            {
              filter = SearchFilter.createORFilter(filterComponents);
            }
 
            // Now search the configured base DNs, stopping at the first
            // success.
            for (final DN baseDN : cfg.getMappedSearchBaseDN())
            {
              Connection connection = null;
              try
              {
                connection = searchFactory.getConnection();
                username = connection.search(baseDN, SearchScope.WHOLE_SUBTREE,
                    filter);
              }
              catch (final DirectoryException e)
              {
                switch (e.getResultCode())
                {
                case NO_SUCH_OBJECT:
                case CLIENT_SIDE_NO_RESULTS_RETURNED:
                  // Ignore and try next base DN.
                  break;
                case CLIENT_SIDE_MORE_RESULTS_TO_RETURN:
                  // More than one matching entry was returned.
                  throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                      ERR_LDAP_PTA_MAPPED_SEARCH_TOO_MANY_CANDIDATES.get(
                          String.valueOf(userEntry.getDN()),
                          String.valueOf(cfg.dn()), String.valueOf(baseDN),
                          String.valueOf(filter)));
                default:
                  // We don't want to propagate this internal error to the
                  // client. We should log it and map it to a more appropriate
                  // error.
                  throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                      ERR_LDAP_PTA_MAPPED_SEARCH_FAILED.get(
                          String.valueOf(userEntry.getDN()),
                          String.valueOf(cfg.dn()), e.getMessageObject()), e);
                }
              }
              finally
              {
                if (connection != null)
                {
                  connection.close();
                }
              }
            }
 
            if (username == null)
            {
              /*
               * No matching entries were found in the remote directory.
               */
              throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                  ERR_LDAP_PTA_MAPPED_SEARCH_NO_CANDIDATES.get(
                      String.valueOf(userEntry.getDN()),
                      String.valueOf(cfg.dn()), String.valueOf(filter)));
            }
 
            break;
          }
 
          // Now perform the bind.
          Connection connection = null;
          try
          {
            connection = bindFactory.getConnection();
            connection.simpleBind(username, password);
 
            // The password matched, so cache it, it will be stored in the
            // user's entry when the state is finalized and only if caching is
            // enabled.
            newCachedPassword = password;
            return true;
          }
          catch (final DirectoryException e)
          {
            switch (e.getResultCode())
            {
            case NO_SUCH_OBJECT:
            case INVALID_CREDENTIALS:
              return false;
            default:
              // We don't want to propagate this internal error to the
              // client. We should log it and map it to a more appropriate
              // error.
              throw new DirectoryException(ResultCode.INVALID_CREDENTIALS,
                  ERR_LDAP_PTA_MAPPED_BIND_FAILED.get(
                      String.valueOf(userEntry.getDN()),
                      String.valueOf(cfg.dn()), e.getMessageObject()), e);
            }
          }
          finally
          {
            if (connection != null)
            {
              connection.close();
            }
          }
        }
        finally
        {
          sharedLock.unlock();
        }
      }
 
 
 
      private boolean passwordMatchesCachedPassword(ByteString password)
      {
        if (!cfg.isUsePasswordCaching())
        {
          return false;
        }
 
        // First determine if the cached password time is present and valid.
        boolean foundValidCachedPasswordTime = false;
 
        List<Attribute> cptlist = userEntry
            .getAttribute(cachedPasswordTimeAttribute);
        if (cptlist != null && !cptlist.isEmpty())
        {
          foundCachedPasswordTime:
          {
            for (Attribute attribute : cptlist)
            {
              // Ignore any attributes with options.
              if (!attribute.hasOptions())
              {
                for (AttributeValue value : attribute)
                {
                  try
                  {
                    long cachedPasswordTime = GeneralizedTimeSyntax
                        .decodeGeneralizedTimeValue(value.getNormalizedValue());
                    long currentTime = provider.getCurrentTimeMS();
                    long expiryTime = cachedPasswordTime
                        + (cfg.getCachedPasswordTTL() * 1000);
                    foundValidCachedPasswordTime = (expiryTime > currentTime);
                  }
                  catch (DirectoryException e)
                  {
                    // Fall-through and give up immediately.
                    if (debugEnabled())
                    {
                      TRACER.debugCaught(DebugLogLevel.ERROR, e);
                    }
                  }
 
                  break foundCachedPasswordTime;
                }
              }
            }
          }
        }
 
        if (!foundValidCachedPasswordTime)
        {
          // The cached password time was not found or it has expired, so give
          // up immediately.
          return false;
        }
 
        // Next determine if there is a cached password.
        ByteString cachedPassword = null;
 
        List<Attribute> cplist = userEntry
            .getAttribute(cachedPasswordAttribute);
        if (cplist != null && !cplist.isEmpty())
        {
          foundCachedPassword:
          {
            for (Attribute attribute : cplist)
            {
              // Ignore any attributes with options.
              if (!attribute.hasOptions())
              {
                for (AttributeValue value : attribute)
                {
                  cachedPassword = value.getValue();
                  break foundCachedPassword;
                }
              }
            }
          }
        }
 
        if (cachedPassword == null)
        {
          // The cached password was not found, so give up immediately.
          return false;
        }
 
        // Decode the password and match it according to its storage scheme.
        try
        {
          String[] userPwComponents = UserPasswordSyntax
              .decodeUserPassword(cachedPassword.toString());
          PasswordStorageScheme<?> scheme = DirectoryServer
              .getPasswordStorageScheme(userPwComponents[0]);
          if (scheme != null)
          {
            return scheme.passwordMatches(password,
                ByteString.valueOf(userPwComponents[1]));
          }
        }
        catch (DirectoryException e)
        {
          // Unable to decode the cached password, so give up.
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
        }
 
        return false;
      }
    }
 
 
 
    // Guards against configuration changes.
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReadLock sharedLock = lock.readLock();
    private final WriteLock exclusiveLock = lock.writeLock();
 
    // Current configuration.
    private LDAPPassThroughAuthenticationPolicyCfg cfg;
 
    private ConnectionFactory searchFactory = null;
    private ConnectionFactory bindFactory = null;
 
    private PasswordStorageScheme<?> pwdStorageScheme = null;
 
 
 
    private PolicyImpl(
        final LDAPPassThroughAuthenticationPolicyCfg configuration)
    {
      initializeConfiguration(configuration);
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public ConfigChangeResult applyConfigurationChange(
        final LDAPPassThroughAuthenticationPolicyCfg cfg)
    {
      exclusiveLock.lock();
      try
      {
        closeConnections();
        initializeConfiguration(cfg);
      }
      finally
      {
        exclusiveLock.unlock();
      }
      return new ConfigChangeResult(ResultCode.SUCCESS, false);
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public AuthenticationPolicyState createAuthenticationPolicyState(
        final Entry userEntry, final long time) throws DirectoryException
    {
      // The current time is not needed for LDAP PTA.
      return new StateImpl(userEntry);
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public void finalizeAuthenticationPolicy()
    {
      exclusiveLock.lock();
      try
      {
        cfg.removeLDAPPassThroughChangeListener(this);
        closeConnections();
      }
      finally
      {
        exclusiveLock.unlock();
      }
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public DN getDN()
    {
      return cfg.dn();
    }
 
 
 
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isConfigurationChangeAcceptable(
        final LDAPPassThroughAuthenticationPolicyCfg cfg,
        final List<Message> unacceptableReasons)
    {
      return LDAPPassThroughAuthenticationPolicyFactory.this
          .isConfigurationAcceptable(cfg, unacceptableReasons);
    }
 
 
 
    private void closeConnections()
    {
      exclusiveLock.lock();
      try
      {
        if (searchFactory != null)
        {
          searchFactory.close();
          searchFactory = null;
        }
 
        if (bindFactory != null)
        {
          bindFactory.close();
          bindFactory = null;
        }
 
      }
      finally
      {
        exclusiveLock.unlock();
      }
    }
 
 
 
    private void initializeConfiguration(
        final LDAPPassThroughAuthenticationPolicyCfg cfg)
    {
      this.cfg = cfg;
 
      // First obtain the mapped search password if needed, ignoring any errors
      // since these should have already been detected during configuration
      // validation.
      final String mappedSearchPassword;
      if (cfg.getMappingPolicy() == MappingPolicy.MAPPED_SEARCH
          && cfg.getMappedSearchBindDN() != null
          && !cfg.getMappedSearchBindDN().isNullDN())
      {
        mappedSearchPassword = getMappedSearchBindPassword(cfg,
            new LinkedList<Message>());
      }
      else
      {
        mappedSearchPassword = null;
      }
 
      // Use two pools per server: one for authentication (bind) and one for
      // searches. Even if the searches are performed anonymously we cannot use
      // the same pool, otherwise they will be performed as the most recently
      // authenticated user.
 
      // Create load-balancers for primary servers.
      final RoundRobinLoadBalancer primarySearchLoadBalancer;
      final RoundRobinLoadBalancer primaryBindLoadBalancer;
      final ScheduledExecutorService scheduler = provider
          .getScheduledExecutorService();
 
      Set<String> servers = cfg.getPrimaryRemoteLDAPServer();
      ConnectionPool[] searchPool = new ConnectionPool[servers.size()];
      ConnectionPool[] bindPool = new ConnectionPool[servers.size()];
      int index = 0;
      for (final String hostPort : servers)
      {
        final ConnectionFactory factory = newLDAPConnectionFactory(hostPort);
        searchPool[index] = new ConnectionPool(
            new AuthenticatedConnectionFactory(factory,
                cfg.getMappedSearchBindDN(),
                mappedSearchPassword));
        bindPool[index++] = new ConnectionPool(factory);
      }
      primarySearchLoadBalancer = new RoundRobinLoadBalancer(searchPool,
          scheduler);
      primaryBindLoadBalancer = new RoundRobinLoadBalancer(bindPool, scheduler);
 
      // Create load-balancers for secondary servers.
      servers = cfg.getSecondaryRemoteLDAPServer();
      if (servers.isEmpty())
      {
        searchFactory = primarySearchLoadBalancer;
        bindFactory = primaryBindLoadBalancer;
      }
      else
      {
        searchPool = new ConnectionPool[servers.size()];
        bindPool = new ConnectionPool[servers.size()];
        index = 0;
        for (final String hostPort : servers)
        {
          final ConnectionFactory factory = newLDAPConnectionFactory(hostPort);
          searchPool[index] = new ConnectionPool(
              new AuthenticatedConnectionFactory(factory,
                  cfg.getMappedSearchBindDN(),
                  mappedSearchPassword));
          bindPool[index++] = new ConnectionPool(factory);
        }
        final RoundRobinLoadBalancer secondarySearchLoadBalancer =
          new RoundRobinLoadBalancer(searchPool, scheduler);
        final RoundRobinLoadBalancer secondaryBindLoadBalancer =
          new RoundRobinLoadBalancer(bindPool, scheduler);
        searchFactory = new FailoverLoadBalancer(primarySearchLoadBalancer,
            secondarySearchLoadBalancer, scheduler);
        bindFactory = new FailoverLoadBalancer(primaryBindLoadBalancer,
            secondaryBindLoadBalancer, scheduler);
      }
 
      if (cfg.isUsePasswordCaching())
      {
        pwdStorageScheme = DirectoryServer.getPasswordStorageScheme(cfg
            .getCachedPasswordStorageSchemeDN());
      }
    }
 
 
 
    private ConnectionFactory newLDAPConnectionFactory(final String hostPort)
    {
      // Validation already performed by admin framework.
      final HostPort hp = HostPort.valueOf(hostPort);
      return provider.getLDAPConnectionFactory(hp.getHost(), hp.getPort(), cfg);
    }
 
  }
 
 
 
  // Debug tracer for this class.
  private static final DebugTracer TRACER = DebugLogger.getTracer();
 
  /**
   * Attribute list for searches requesting no attributes.
   */
  static final LinkedHashSet<String> NO_ATTRIBUTES = new LinkedHashSet<String>(
      1);
  static
  {
    NO_ATTRIBUTES.add(SchemaConstants.NO_ATTRIBUTES);
  }
 
  // The provider which should be used by policies to create LDAP connections.
  private final Provider provider;
 
  /**
   * The default LDAP connection factory provider.
   */
  private static final Provider DEFAULT_PROVIDER = new Provider()
  {
 
    // Global scheduler used for periodically monitoring connection factories in
    // order to detect when they are online.
    private final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(2, new ThreadFactory()
        {
 
          @Override
          public Thread newThread(final Runnable r)
          {
            final Thread t = new DirectoryThread(r,
                "LDAP PTA connection monitor thread");
            t.setDaemon(true);
            return t;
          }
        });
 
 
 
    @Override
    public ConnectionFactory getLDAPConnectionFactory(final String host,
        final int port, final LDAPPassThroughAuthenticationPolicyCfg cfg)
    {
      return new LDAPConnectionFactory(host, port, cfg);
    }
 
 
 
    @Override
    public ScheduledExecutorService getScheduledExecutorService()
    {
      return scheduler;
    }
 
    @Override
    public String getCurrentTime()
    {
      return TimeThread.getGMTTime();
    }
 
    @Override
    public long getCurrentTimeMS()
    {
      return TimeThread.getTime();
    }
 
  };
 
 
 
  /**
   * Determines whether or no a result code is expected to trigger the
   * associated connection to be closed immediately.
   *
   * @param resultCode
   *          The result code.
   * @return {@code true} if the result code is expected to trigger the
   *         associated connection to be closed immediately.
   */
  static boolean isServiceError(final ResultCode resultCode)
  {
    switch (resultCode)
    {
    case OPERATIONS_ERROR:
    case PROTOCOL_ERROR:
    case TIME_LIMIT_EXCEEDED:
    case ADMIN_LIMIT_EXCEEDED:
    case UNAVAILABLE_CRITICAL_EXTENSION:
    case BUSY:
    case UNAVAILABLE:
    case UNWILLING_TO_PERFORM:
    case LOOP_DETECT:
    case OTHER:
    case CLIENT_SIDE_CONNECT_ERROR:
    case CLIENT_SIDE_DECODING_ERROR:
    case CLIENT_SIDE_ENCODING_ERROR:
    case CLIENT_SIDE_LOCAL_ERROR:
    case CLIENT_SIDE_SERVER_DOWN:
    case CLIENT_SIDE_TIMEOUT:
      return true;
    default:
      return false;
    }
  }
 
 
 
//Get the search bind password performing mapped searches.
  //
  // We will offer several places to look for the password, and we will
  // do so in the following order:
  //
  // - In a specified Java property
  // - In a specified environment variable
  // - In a specified file on the server filesystem.
  // - As the value of a configuration attribute.
  //
  // In any case, the password must be in the clear.
  private static String getMappedSearchBindPassword(
      final LDAPPassThroughAuthenticationPolicyCfg cfg,
      final List<Message> unacceptableReasons)
  {
    String password = null;
 
    if (cfg.getMappedSearchBindPasswordProperty() != null)
    {
      String propertyName = cfg.getMappedSearchBindPasswordProperty();
      password = System.getProperty(propertyName);
      if (password == null)
      {
        unacceptableReasons.add(ERR_LDAP_PTA_PWD_PROPERTY_NOT_SET.get(
            String.valueOf(cfg.dn()), String.valueOf(propertyName)));
      }
    }
    else if (cfg.getMappedSearchBindPasswordEnvironmentVariable() != null)
    {
      String envVarName = cfg.getMappedSearchBindPasswordEnvironmentVariable();
      password = System.getenv(envVarName);
      if (password == null)
      {
        unacceptableReasons.add(ERR_LDAP_PTA_PWD_ENVAR_NOT_SET.get(
            String.valueOf(cfg.dn()), String.valueOf(envVarName)));
      }
    }
    else if (cfg.getMappedSearchBindPasswordFile() != null)
    {
      String fileName = cfg.getMappedSearchBindPasswordFile();
      File passwordFile = getFileForPath(fileName);
      if (!passwordFile.exists())
      {
        unacceptableReasons.add(ERR_LDAP_PTA_PWD_NO_SUCH_FILE.get(
            String.valueOf(cfg.dn()), String.valueOf(fileName)));
      }
      else
      {
        BufferedReader br = null;
        try
        {
          br = new BufferedReader(new FileReader(passwordFile));
          password = br.readLine();
          if (password == null)
          {
            unacceptableReasons.add(ERR_LDAP_PTA_PWD_FILE_EMPTY.get(
                String.valueOf(cfg.dn()), String.valueOf(fileName)));
          }
        }
        catch (IOException e)
        {
          unacceptableReasons.add(ERR_LDAP_PTA_PWD_FILE_CANNOT_READ.get(
              String.valueOf(cfg.dn()), String.valueOf(fileName),
              getExceptionMessage(e)));
        }
        finally
        {
          try
          {
            br.close();
          }
          catch (Exception e)
          {
            // Ignored.
          }
        }
      }
    }
    else if (cfg.getMappedSearchBindPassword() != null)
    {
      password = cfg.getMappedSearchBindPassword();
    }
    else
    {
      // Password wasn't defined anywhere.
      unacceptableReasons
          .add(ERR_LDAP_PTA_NO_PWD.get(String.valueOf(cfg.dn())));
    }
 
    return password;
  }
 
 
 
  private static boolean isServerAddressValid(
      final LDAPPassThroughAuthenticationPolicyCfg configuration,
      final List<Message> unacceptableReasons, final String hostPort)
  {
    try
    {
      // validate provided string
      HostPort.valueOf(hostPort);
      return true;
    }
    catch (RuntimeException e)
    {
      if (unacceptableReasons != null)
      {
        final Message msg = ERR_LDAP_PTA_INVALID_PORT_NUMBER.get(
            String.valueOf(configuration.dn()), hostPort);
        unacceptableReasons.add(msg);
      }
      return false;
    }
  }
 
 
 
  private static String mappedAttributesAsString(
      final Collection<AttributeType> attributes)
  {
    switch (attributes.size())
    {
    case 0:
      return "";
    case 1:
      return attributes.iterator().next().getNameOrOID();
    default:
      final StringBuilder builder = new StringBuilder();
      final Iterator<AttributeType> i = attributes.iterator();
      builder.append(i.next().getNameOrOID());
      while (i.hasNext())
      {
        builder.append(", ");
        builder.append(i.next().getNameOrOID());
      }
      return builder.toString();
    }
  }
 
 
 
  /**
   * Public default constructor used by the admin framework. This will use the
   * default LDAP connection factory provider.
   */
  public LDAPPassThroughAuthenticationPolicyFactory()
  {
    this(DEFAULT_PROVIDER);
  }
 
 
 
  /**
   * Package private constructor allowing unit tests to provide mock connection
   * implementations.
   *
   * @param provider
   *          The LDAP connection factory provider implementation which LDAP PTA
   *          authentication policies will use.
   */
  LDAPPassThroughAuthenticationPolicyFactory(final Provider provider)
  {
    this.provider = provider;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override
  public AuthenticationPolicy createAuthenticationPolicy(
      final LDAPPassThroughAuthenticationPolicyCfg configuration)
      throws ConfigException, InitializationException
  {
    final PolicyImpl policy = new PolicyImpl(configuration);
    configuration.addLDAPPassThroughChangeListener(policy);
    return policy;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isConfigurationAcceptable(
      final LDAPPassThroughAuthenticationPolicyCfg cfg,
      final List<Message> unacceptableReasons)
  {
    // Check that the port numbers are valid. We won't actually try and connect
    // to the server since they may not be available (hence we have fail-over
    // capabilities).
    boolean configurationIsAcceptable = true;
 
    for (final String hostPort : cfg.getPrimaryRemoteLDAPServer())
    {
      configurationIsAcceptable &= isServerAddressValid(cfg,
          unacceptableReasons, hostPort);
    }
 
    for (final String hostPort : cfg.getSecondaryRemoteLDAPServer())
    {
      configurationIsAcceptable &= isServerAddressValid(cfg,
          unacceptableReasons, hostPort);
    }
 
    // Ensure that the search bind password is defined somewhere.
    if (cfg.getMappingPolicy() == MappingPolicy.MAPPED_SEARCH
        && cfg.getMappedSearchBindDN() != null
        && !cfg.getMappedSearchBindDN().isNullDN())
    {
      if (getMappedSearchBindPassword(cfg, unacceptableReasons) == null)
      {
        configurationIsAcceptable = false;
      }
    }
 
    return configurationIsAcceptable;
  }
}