Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*	$NetBSD: chain.c,v 1.3 2021/08/14 16:14:59 christos Exp $	*/

/* chain.c - chain LDAP operations */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 2003-2021 The OpenLDAP Foundation.
 * Portions Copyright 2003 Howard Chu.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* ACKNOWLEDGEMENTS:
 * This work was initially developed by the Howard Chu for inclusion
 * in OpenLDAP Software.
 * This work was subsequently modified by Pierangelo Masarati.
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: chain.c,v 1.3 2021/08/14 16:14:59 christos Exp $");

#include "portable.h"

#include <stdio.h>

#include <ac/string.h>
#include <ac/socket.h>

#include "lutil.h"
#include "slap.h"
#include "back-ldap.h"
#include "slap-config.h"

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
#define SLAP_CHAINING_DEFAULT				LDAP_CHAINING_PREFERRED
#define SLAP_CH_RESOLVE_SHIFT				SLAP_CONTROL_SHIFT
#define SLAP_CH_RESOLVE_MASK				(0x3 << SLAP_CH_RESOLVE_SHIFT)
#define SLAP_CH_RESOLVE_CHAINING_PREFERRED		(LDAP_CHAINING_PREFERRED << SLAP_CH_RESOLVE_SHIFT)
#define SLAP_CH_RESOLVE_CHAINING_REQUIRED		(LDAP_CHAINING_REQUIRED << SLAP_CH_RESOLVE_SHIFT)
#define SLAP_CH_RESOLVE_REFERRALS_PREFERRED		(LDAP_REFERRALS_PREFERRED << SLAP_CH_RESOLVE_SHIFT)
#define SLAP_CH_RESOLVE_REFERRALS_REQUIRED		(LDAP_REFERRALS_REQUIRED << SLAP_CH_RESOLVE_SHIFT)
#define SLAP_CH_RESOLVE_DEFAULT				(SLAP_CHAINING_DEFAULT << SLAP_CH_RESOLVE_SHIFT)
#define	SLAP_CH_CONTINUATION_SHIFT			(SLAP_CH_RESOLVE_SHIFT + 2)
#define SLAP_CH_CONTINUATION_MASK			(0x3 << SLAP_CH_CONTINUATION_SHIFT)
#define SLAP_CH_CONTINUATION_CHAINING_PREFERRED		(LDAP_CHAINING_PREFERRED << SLAP_CH_CONTINUATION_SHIFT)
#define SLAP_CH_CONTINUATION_CHAINING_REQUIRED		(LDAP_CHAINING_REQUIRED << SLAP_CH_CONTINUATION_SHIFT)
#define SLAP_CH_CONTINUATION_REFERRALS_PREFERRED	(LDAP_REFERRALS_PREFERRED << SLAP_CH_CONTINUATION_SHIFT)
#define SLAP_CH_CONTINUATION_REFERRALS_REQUIRED		(LDAP_REFERRALS_REQUIRED << SLAP_CH_CONTINUATION_SHIFT)
#define SLAP_CH_CONTINUATION_DEFAULT			(SLAP_CHAINING_DEFAULT << SLAP_CH_CONTINUATION_SHIFT)

#define o_chaining			o_ctrlflag[sc_chainingBehavior]
#define get_chaining(op)		((op)->o_chaining & SLAP_CONTROL_MASK)
#define get_chainingBehavior(op)	((op)->o_chaining & (SLAP_CH_RESOLVE_MASK|SLAP_CH_CONTINUATION_MASK))
#define get_resolveBehavior(op)		((op)->o_chaining & SLAP_CH_RESOLVE_MASK)
#define get_continuationBehavior(op)	((op)->o_chaining & SLAP_CH_CONTINUATION_MASK)

static int		sc_chainingBehavior;
#endif /*  LDAP_CONTROL_X_CHAINING_BEHAVIOR */

typedef enum {
	LDAP_CH_NONE = 0,
	LDAP_CH_RES,
	LDAP_CH_ERR
} ldap_chain_status_t;

static BackendInfo	*lback;

typedef struct ldap_chain_t {
	/*
	 * A "template" ldapinfo_t gets all common configuration items;
	 * then, for each configured URI, an entry is created in the tree;
	 * all the specific configuration items get in the current URI 
	 * structure.
	 *
 	 * Then, for each referral, extract the URI and lookup the
	 * related structure.  If configured to do so, allow URIs
	 * not found in the structure to create a temporary one
	 * that chains anonymously; maybe it can also be added to 
	 * the tree?  Should be all configurable.
	 */

	/* "common" configuration info (anything occurring before an "uri") */
	ldapinfo_t		*lc_common_li;

	/* current configuration info */
	ldapinfo_t		*lc_cfg_li;

	/* tree of configured[/generated?] "uri" info */
	ldap_avl_info_t		lc_lai;

	/* max depth in nested referrals chaining */
	int			lc_max_depth;

	unsigned		lc_flags;
#define LDAP_CHAIN_F_NONE		(0x00U)
#define	LDAP_CHAIN_F_CHAINING		(0x01U)
#define	LDAP_CHAIN_F_CACHE_URI		(0x02U)
#define	LDAP_CHAIN_F_RETURN_ERR		(0x04U)

#define LDAP_CHAIN_ISSET(lc, f)		( ( (lc)->lc_flags & (f) ) == (f) )
#define	LDAP_CHAIN_CHAINING( lc )	LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_CHAINING )
#define	LDAP_CHAIN_CACHE_URI( lc )	LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_CACHE_URI )
#define	LDAP_CHAIN_RETURN_ERR( lc )	LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_RETURN_ERR )

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	LDAPControl		lc_chaining_ctrl;
	char			lc_chaining_ctrlflag;
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
} ldap_chain_t;

static int ldap_chain_db_init_common( BackendDB	*be );
static int ldap_chain_db_init_one( BackendDB *be );
static int ldap_chain_db_open_one( BackendDB *be );
#define	ldap_chain_db_close_one(be)	(0)
#define	ldap_chain_db_destroy_one(be, rs)	(lback)->bi_db_destroy( (be), (rs) )

typedef struct ldap_chain_cb_t {
	ldap_chain_status_t	lb_status;
	ldap_chain_t		*lb_lc;
	slap_operation_t	lb_op_type;
	char			*lb_text;
	int			lb_depth;
} ldap_chain_cb_t;

static int
ldap_chain_op(
	Operation	*op,
	SlapReply	*rs,
	slap_operation_t op_type,
	BerVarray	ref,
	int		depth );

static int
ldap_chain_search(
	Operation	*op,
	SlapReply	*rs,
	BerVarray	ref,
	int		depth );

static slap_overinst ldapchain;

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
static int
chaining_control_add(
		ldap_chain_t	*lc,
		Operation 	*op, 
		LDAPControl	***oldctrlsp )
{
	LDAPControl	**ctrls = NULL;
	int		c = 0;

	*oldctrlsp = op->o_ctrls;

	/* default chaining control not defined */
	if ( !LDAP_CHAIN_CHAINING( lc ) ) {
		return 0;
	}

	/* already present */
	if ( get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
		return 0;
	}

	/* FIXME: check other incompatibilities */

	/* add to other controls */
	if ( op->o_ctrls ) {
		for ( c = 0; op->o_ctrls[ c ]; c++ )
			/* count them */ ;
	}

	ctrls = ch_calloc( sizeof( LDAPControl *), c + 2 );
	ctrls[ 0 ] = &lc->lc_chaining_ctrl;
	if ( op->o_ctrls ) {
		for ( c = 0; op->o_ctrls[ c ]; c++ ) {
			ctrls[ c + 1 ] = op->o_ctrls[ c ];
		}
	}
	ctrls[ c + 1 ] = NULL;

	op->o_ctrls = ctrls;

	op->o_chaining = lc->lc_chaining_ctrlflag;

	return 0;
}

static int
chaining_control_remove(
		Operation 	*op, 
		LDAPControl	***oldctrlsp )
{
	LDAPControl	**oldctrls = *oldctrlsp;

	/* we assume that the first control is the chaining control
	 * added by the chain overlay, so it's the only one we explicitly 
	 * free */
	if ( op->o_ctrls != oldctrls ) {
		if ( op->o_ctrls != NULL ) {
			assert( op->o_ctrls[ 0 ] != NULL );

			free( op->o_ctrls );

			op->o_chaining = 0;
		}
		op->o_ctrls = oldctrls;
	} 

	*oldctrlsp = NULL;

	return 0;
}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

static int
ldap_chain_uri_cmp( const void *c1, const void *c2 )
{
	const ldapinfo_t	*li1 = (const ldapinfo_t *)c1;
	const ldapinfo_t	*li2 = (const ldapinfo_t *)c2;

	assert( li1->li_bvuri != NULL );
	assert( !BER_BVISNULL( &li1->li_bvuri[ 0 ] ) );
	assert( BER_BVISNULL( &li1->li_bvuri[ 1 ] ) );

	assert( li2->li_bvuri != NULL );
	assert( !BER_BVISNULL( &li2->li_bvuri[ 0 ] ) );
	assert( BER_BVISNULL( &li2->li_bvuri[ 1 ] ) );

	return ber_bvcmp( &li1->li_bvuri[ 0 ], &li2->li_bvuri[ 0 ] );
}

static int
ldap_chain_uri_dup( void *c1, void *c2 )
{
	ldapinfo_t	*li1 = (ldapinfo_t *)c1;
	ldapinfo_t	*li2 = (ldapinfo_t *)c2;

	assert( li1->li_bvuri != NULL );
	assert( !BER_BVISNULL( &li1->li_bvuri[ 0 ] ) );
	assert( BER_BVISNULL( &li1->li_bvuri[ 1 ] ) );

	assert( li2->li_bvuri != NULL );
	assert( !BER_BVISNULL( &li2->li_bvuri[ 0 ] ) );
	assert( BER_BVISNULL( &li2->li_bvuri[ 1 ] ) );

	if ( ber_bvcmp( &li1->li_bvuri[ 0 ], &li2->li_bvuri[ 0 ] ) == 0 ) {
		return -1;
	}

	return 0;
}

/*
 * Search specific response that strips entryDN from entries
 */
static int
ldap_chain_cb_search_response( Operation *op, SlapReply *rs )
{
	ldap_chain_cb_t	*lb = (ldap_chain_cb_t *)op->o_callback->sc_private;

	assert( op->o_tag == LDAP_REQ_SEARCH );

	/* if in error, don't proceed any further */
	if ( lb->lb_status == LDAP_CH_ERR ) {
		return 0;
	}

	if ( rs->sr_type == REP_SEARCH ) {
		Attribute	**ap = &rs->sr_entry->e_attrs;

		for ( ; *ap != NULL; ap = &(*ap)->a_next ) {
			/* will be generated later by frontend
			 * (a cleaner solution would be that
			 * the frontend checks if it already exists */
			if ( ad_cmp( (*ap)->a_desc, slap_schema.si_ad_entryDN ) == 0 )
			{
				Attribute *a = *ap;

				*ap = (*ap)->a_next;
				attr_free( a );

				/* there SHOULD be one only! */
				break;
			}
		}

		/* tell the frontend not to add generated
		 * operational attributes */
		rs->sr_flags |= REP_NO_OPERATIONALS;
		
		return SLAP_CB_CONTINUE;

	} else if ( rs->sr_type == REP_SEARCHREF ) {
		/* if we get it here, it means the library was unable
		 * to chase the referral... */
		if ( lb->lb_depth < lb->lb_lc->lc_max_depth && rs->sr_ref != NULL ) {
			rs->sr_err = ldap_chain_search( op, rs, rs->sr_ref, lb->lb_depth );
		}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
		if ( rs->sr_err == LDAP_REFERRAL && get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
			switch ( get_continuationBehavior( op ) ) {
			case SLAP_CH_RESOLVE_CHAINING_REQUIRED:
				lb->lb_status = LDAP_CH_ERR;
				return rs->sr_err = LDAP_X_CANNOT_CHAIN;

			default:
				break;
			}
		}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
		return SLAP_CB_CONTINUE;

	} else if ( rs->sr_type == REP_RESULT ) {
		if ( rs->sr_err == LDAP_REFERRAL
			&& lb->lb_depth < lb->lb_lc->lc_max_depth
			&& rs->sr_ref != NULL )
		{
			rs->sr_err = ldap_chain_op( op, rs, lb->lb_op_type,
				rs->sr_ref, lb->lb_depth );
		}

		/* back-ldap tried to send result */
		lb->lb_status = LDAP_CH_RES;
		/* don't let other callbacks run, this isn't
		 * the real result for this op.
		 */
		op->o_callback->sc_next = NULL;
	}

	return 0;
}

/*
 * Dummy response that simply traces if back-ldap tried to send 
 * anything to the client
 */
static int
ldap_chain_cb_response( Operation *op, SlapReply *rs )
{
	ldap_chain_cb_t	*lb = (ldap_chain_cb_t *)op->o_callback->sc_private;

	/* if in error, don't proceed any further */
	if ( lb->lb_status == LDAP_CH_ERR ) {
		return 0;
	}

	if ( rs->sr_type == REP_RESULT ) {
retry:;
		switch ( rs->sr_err ) {
		case LDAP_COMPARE_TRUE:
		case LDAP_COMPARE_FALSE:
			if ( op->o_tag != LDAP_REQ_COMPARE ) {
				return rs->sr_err;
			}
			/* fallthru */

		case LDAP_SUCCESS:
			lb->lb_status = LDAP_CH_RES;
			break;

		case LDAP_REFERRAL:
			if ( lb->lb_depth < lb->lb_lc->lc_max_depth && rs->sr_ref != NULL ) {
				rs->sr_err = ldap_chain_op( op, rs, lb->lb_op_type,
					rs->sr_ref, lb->lb_depth );
				goto retry;
			}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
			if ( get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
				switch ( get_continuationBehavior( op ) ) {
				case SLAP_CH_RESOLVE_CHAINING_REQUIRED:
					lb->lb_status = LDAP_CH_ERR;
					return rs->sr_err = LDAP_X_CANNOT_CHAIN;

				default:
					break;
				}
			}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
			break;

		default:
			/* remember the text before it's freed in ldap_back_op_result */
			if ( lb->lb_text ) {
				ber_memfree_x( lb->lb_text, op->o_tmpmemctx );
			}
			lb->lb_text = ber_strdup_x( rs->sr_text, op->o_tmpmemctx );
			return rs->sr_err;
		}

	} else if ( op->o_tag == LDAP_REQ_SEARCH && rs->sr_type == REP_SEARCH )
	{
		/* strip the entryDN attribute, but keep returning results */
		(void)ldap_chain_cb_search_response( op, rs );
	}

	return SLAP_CB_CONTINUE;
}

static int
ldap_chain_op(
	Operation	*op,
	SlapReply	*rs,
	slap_operation_t op_type,
	BerVarray	ref,
	int		depth )
{
	slap_overinst	*on = (slap_overinst *) op->o_bd->bd_info;
	ldap_chain_cb_t	*lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	struct berval	odn = op->o_req_dn,
			ondn = op->o_req_ndn;
	ldapinfo_t	li = { 0 }, *lip = NULL;
	struct berval	bvuri[ 2 ] = { { 0 } };

	/* NOTE: returned if ref is empty... */
	int		rc = LDAP_OTHER,
			first_rc;

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	LDAPControl	**ctrls = NULL;
	
	(void)chaining_control_add( lc, op, &ctrls );
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	li.li_bvuri = bvuri;
	first_rc = -1;
	for ( ; !BER_BVISNULL( ref ); ref++ ) {
		SlapReply	rs2 = { 0 };
		LDAPURLDesc	*srv = NULL;
		req_search_s	save_oq_search = op->oq_search,
				tmp_oq_search = { 0 };
		struct berval	dn = BER_BVNULL,
				pdn = odn,
				ndn = ondn;
		char		*filter = NULL;
		int		temporary = 0;
		int		free_dn = 0;
			
		/* We're setting the URI of the first referral;
		 * what if there are more?

Document: RFC 4511

4.1.10. Referral 
   ...
   If the client wishes to progress the operation, it MUST follow the 
   referral by contacting one of the supported services. If multiple 
   URIs are present, the client assumes that any supported URI may be 
   used to progress the operation. 

		 * so we actually need to follow exactly one,
		 * and we can assume any is fine.
		 */
	
		/* parse reference and use 
		 * proto://[host][:port]/ only */
		rc = ldap_url_parse_ext( ref->bv_val, &srv, LDAP_PVT_URL_PARSE_NONE );
		if ( rc != LDAP_URL_SUCCESS ) {
			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: unable to parse ref=\"%s\"\n",
				op->o_log_prefix, ref->bv_val );

			/* try next */
			rc = LDAP_OTHER;
			continue;
		}

		if ( op->o_tag == LDAP_REQ_SEARCH ) {
			if ( srv->lud_scope != LDAP_SCOPE_DEFAULT ) {
				/* RFC 4511: if scope is present, use it */
				tmp_oq_search.rs_scope = srv->lud_scope;

			} else {
				/* RFC 4511: if scope is absent, use original */
				tmp_oq_search.rs_scope = op->ors_scope;
			}
		}

		rc = LDAP_SUCCESS;
		srv->lud_scope = LDAP_SCOPE_DEFAULT;
		dn.bv_val = srv->lud_dn;
		filter = srv->lud_filter;

		/* normalize DN */
		if ( srv->lud_dn == NULL || srv->lud_dn[0] == '\0' ) {
			if ( srv->lud_dn == NULL ) {
				srv->lud_dn = "";
			}

		} else {
			ber_str2bv( srv->lud_dn, 0, 0, &dn );
			rc = dnPrettyNormal( NULL, &dn, &pdn, &ndn, op->o_tmpmemctx );
			if ( rc == LDAP_SUCCESS ) {
				/* remove DN essentially because later on 
				 * ldap_initialize() will parse the URL 
				 * as a comma-separated URL list */
				srv->lud_dn = "";
				free_dn = 1;
			}
		}

		/* prepare filter */
		if ( rc == LDAP_SUCCESS && op->o_tag == LDAP_REQ_SEARCH ) {
			/* filter */
			if ( srv->lud_filter != NULL
				&& srv->lud_filter[0] != '\0'
				&& strcasecmp( srv->lud_filter, "(objectClass=*)" ) != 0 )
			{
				/* RFC 4511: if filter is present, use it;
				 * otherwise, use original */
				tmp_oq_search.rs_filter = str2filter_x( op, srv->lud_filter );
				if ( tmp_oq_search.rs_filter != NULL ) {
					filter2bv_x( op, tmp_oq_search.rs_filter, &tmp_oq_search.rs_filterstr );

				} else {
					Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\": unable to parse filter=\"%s\"\n",
						op->o_log_prefix, ref->bv_val, srv->lud_filter );
					rc = LDAP_OTHER;
				}
			}
		}
		srv->lud_filter = NULL;

		if ( rc == LDAP_SUCCESS ) {
			li.li_uri = ldap_url_desc2str( srv );
		}

		srv->lud_dn = dn.bv_val;
		srv->lud_filter = filter;
		ldap_free_urldesc( srv );

		if ( rc != LDAP_SUCCESS ) {
			/* try next */
			rc = LDAP_OTHER;
			continue;
		}

		if ( li.li_uri == NULL ) {
			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\" unable to reconstruct URI\n",
				op->o_log_prefix, ref->bv_val );

			/* try next */
			rc = LDAP_OTHER;
			goto further_cleanup;
		}

		Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\" -> \"%s\"\n",
			op->o_log_prefix, ref->bv_val, li.li_uri );

		op->o_req_dn = pdn;
		op->o_req_ndn = ndn;

		if ( op->o_tag == LDAP_REQ_SEARCH ) {
			op->ors_scope = tmp_oq_search.rs_scope;
			if ( tmp_oq_search.rs_filter != NULL ) {
				op->ors_filter = tmp_oq_search.rs_filter;
				op->ors_filterstr = tmp_oq_search.rs_filterstr;
			}
		}

		ber_str2bv( li.li_uri, 0, 0, &li.li_bvuri[ 0 ] );

		/* Searches for a ldapinfo in the avl tree */
		ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
		lip = (ldapinfo_t *)ldap_tavl_find( lc->lc_lai.lai_tree,
			(caddr_t)&li, ldap_chain_uri_cmp );
		ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );

		if ( lip != NULL ) {
			op->o_bd->be_private = (void *)lip;

			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\": URI=\"%s\" found in cache\n",
				op->o_log_prefix, ref->bv_val, li.li_uri );

		} else {
			rc = ldap_chain_db_init_one( op->o_bd );
			if ( rc != 0 ) {
				Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\" unable to init back-ldap for URI=\"%s\"\n",
					op->o_log_prefix, ref->bv_val, li.li_uri );
				goto cleanup;
			}
			lip = (ldapinfo_t *)op->o_bd->be_private;
			lip->li_uri = li.li_uri;
			lip->li_bvuri = bvuri;
			rc = ldap_chain_db_open_one( op->o_bd );
			if ( rc != 0 ) {
				Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\" unable to open back-ldap for URI=\"%s\"\n",
					op->o_log_prefix, ref->bv_val, li.li_uri );
				lip->li_uri = NULL;
				lip->li_bvuri = NULL;
				(void)ldap_chain_db_destroy_one( op->o_bd, NULL);
				goto cleanup;
			}

			if ( LDAP_CHAIN_CACHE_URI( lc ) ) {
				ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
				if ( ldap_tavl_insert( &lc->lc_lai.lai_tree,
					(caddr_t)lip, ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
				{
					/* someone just inserted another;
					 * don't bother, use this and then
					 * just free it */
					temporary = 1;
				}
				ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );

			} else {
				temporary = 1;
			}

			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_op: ref=\"%s\" %s\n",
				op->o_log_prefix, ref->bv_val, temporary ? "temporary" : "caching" );
		}

		lb->lb_op_type = op_type;
		lb->lb_depth = depth + 1;

		rc = (&lback->bi_op_bind)[ op_type ]( op, &rs2 );

		/* note the first error */
		if ( first_rc == -1 ) {
			first_rc = rc;
		}

cleanup:;
		ldap_memfree( li.li_uri );
		li.li_uri = NULL;

		if ( temporary ) {
			lip->li_uri = NULL;
			lip->li_bvuri = NULL;
			(void)ldap_chain_db_close_one( op->o_bd );
			(void)ldap_chain_db_destroy_one( op->o_bd, NULL );
		}

further_cleanup:;
		if ( op->o_req_dn.bv_val == pdn.bv_val ) {
			op->o_req_dn = odn;
			op->o_req_ndn = ondn;
		}

		if ( free_dn ) {
			op->o_tmpfree( pdn.bv_val, op->o_tmpmemctx );
			op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
		}
	
		if ( op->o_tag == LDAP_REQ_SEARCH ) {	
			if ( tmp_oq_search.rs_filter != NULL ) {
				filter_free_x( op, tmp_oq_search.rs_filter, 1 );
			}

			if ( !BER_BVISNULL( &tmp_oq_search.rs_filterstr ) ) {
				slap_sl_free( tmp_oq_search.rs_filterstr.bv_val, op->o_tmpmemctx );
			}

			op->oq_search = save_oq_search;
		}

		if ( rc == LDAP_SUCCESS && rs2.sr_err == LDAP_SUCCESS ) {
			*rs = rs2;
			break;
		}

		rc = rs2.sr_err;
	}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	(void)chaining_control_remove( op, &ctrls );
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	if ( rc != LDAP_SUCCESS && first_rc > 0 ) {
		rc = first_rc;
	}

	return rc;
}

static int
ldap_chain_search(
	Operation	*op,
	SlapReply	*rs,
	BerVarray	ref,
	int		depth )

{
	slap_overinst	*on = (slap_overinst *) op->o_bd->bd_info;
	ldap_chain_cb_t	*lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	ldapinfo_t	li = { 0 }, *lip = NULL;
	struct berval	bvuri[ 2 ] = { { 0 } };

	struct berval	odn = op->o_req_dn,
			ondn = op->o_req_ndn;
	Entry		*save_entry = rs->sr_entry;
	slap_mask_t	save_flags = rs->sr_flags;

	int		rc = LDAP_OTHER,
			first_rc = -1;

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	LDAPControl	**ctrls = NULL;
	
	(void)chaining_control_add( lc, op, &ctrls );
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	assert( rs->sr_type == REP_SEARCHREF );

	rs->sr_type = REP_SEARCH;

	/* if we parse the URI then by no means 
	 * we can cache stuff or reuse connections, 
	 * because in back-ldap there's no caching
	 * based on the URI value, which is supposed
	 * to be set once for all (correct?) */
	li.li_bvuri = bvuri;
	for ( ; !BER_BVISNULL( &ref[0] ); ref++ ) {
		SlapReply	rs2 = { REP_RESULT };
		LDAPURLDesc	*srv;
		req_search_s	save_oq_search = op->oq_search,
				tmp_oq_search = { 0 };
		struct berval	dn,
				pdn = op->o_req_dn,
				ndn = op->o_req_ndn;
		char		*filter = NULL;
		int		temporary = 0;
		int		free_dn = 0;

		/* parse reference and use
		 * proto://[host][:port]/ only */
		rc = ldap_url_parse_ext( ref[0].bv_val, &srv, LDAP_PVT_URL_PARSE_NONE );
		if ( rc != LDAP_URL_SUCCESS ) {
			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: unable to parse ref=\"%s\"\n",
				op->o_log_prefix, ref->bv_val );

			/* try next */
			rs->sr_err = LDAP_OTHER;
			continue;
		}

		if ( srv->lud_scope != LDAP_SCOPE_DEFAULT ) {
			/* RFC 4511: if scope is present, use it */
			tmp_oq_search.rs_scope = srv->lud_scope;

		} else {
			/* RFC 4511: if scope is absent, use original */
			/* Section 4.5.3: if scope is onelevel, use base */
			if ( op->ors_scope == LDAP_SCOPE_ONELEVEL )
				tmp_oq_search.rs_scope = LDAP_SCOPE_BASE;
			else
				tmp_oq_search.rs_scope = op->ors_scope;
		}

		rc = LDAP_SUCCESS;
		srv->lud_scope = LDAP_SCOPE_DEFAULT;
		dn.bv_val = srv->lud_dn;
		filter = srv->lud_filter;

		/* normalize DN */
		if ( srv->lud_dn == NULL || srv->lud_dn[0] == '\0' ) {
			if ( srv->lud_dn == NULL ) {
				srv->lud_dn = "";
			}

			if ( save_entry != NULL ) {
				/* use the "right" DN, if available */
				pdn = save_entry->e_name;
				ndn = save_entry->e_nname;
			} /* else leave the original req DN in place, if any RFC 4511 */
			
		} else {
			/* RFC 4511: if DN is present, use it */
			ber_str2bv( srv->lud_dn, 0, 0, &dn );
			rc = dnPrettyNormal( NULL, &dn, &pdn, &ndn, op->o_tmpmemctx );
			if ( rc == LDAP_SUCCESS ) {
				/* remove DN essentially because later on 
				 * ldap_initialize() will parse the URL 
				 * as a comma-separated URL list */
				srv->lud_dn = "";
				free_dn = 1;
			}
		}

		/* prepare filter */
		if ( rc == LDAP_SUCCESS ) {
			/* filter */
			if ( srv->lud_filter != NULL
				&& srv->lud_filter[0] != '\0'
				&& strcasecmp( srv->lud_filter, "(objectClass=*)" ) != 0 )
			{
				/* RFC 4511: if filter is present, use it;
				 * otherwise, use original */
				tmp_oq_search.rs_filter = str2filter_x( op, srv->lud_filter );
				if ( tmp_oq_search.rs_filter != NULL ) {
					filter2bv_x( op, tmp_oq_search.rs_filter, &tmp_oq_search.rs_filterstr );

				} else {
					Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\": unable to parse filter=\"%s\"\n",
						op->o_log_prefix, ref->bv_val, srv->lud_filter );
					rc = LDAP_OTHER;
				}
			}
		}
		srv->lud_filter = NULL;

		if ( rc == LDAP_SUCCESS ) {
			li.li_uri = ldap_url_desc2str( srv );
		}

		srv->lud_dn = dn.bv_val;
		srv->lud_filter = filter;
		ldap_free_urldesc( srv );

		if ( rc != LDAP_SUCCESS || li.li_uri == NULL ) {
			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\" unable to reconstruct URI\n",
				op->o_log_prefix, ref->bv_val );

			/* try next */
			rc = LDAP_OTHER;
			goto further_cleanup;
		}

		Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\" -> \"%s\"\n",
			op->o_log_prefix, ref->bv_val, li.li_uri );

		op->o_req_dn = pdn;
		op->o_req_ndn = ndn;
		op->ors_scope = tmp_oq_search.rs_scope;
		if ( tmp_oq_search.rs_filter != NULL ) {
			op->ors_filter = tmp_oq_search.rs_filter;
			op->ors_filterstr = tmp_oq_search.rs_filterstr;
		}

		ber_str2bv( li.li_uri, 0, 0, &li.li_bvuri[ 0 ] );

		/* Searches for a ldapinfo in the avl tree */
		ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
		lip = (ldapinfo_t *)ldap_tavl_find( lc->lc_lai.lai_tree,
			(caddr_t)&li, ldap_chain_uri_cmp );
		ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );

		if ( lip != NULL ) {
			op->o_bd->be_private = (void *)lip;

			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\": URI=\"%s\" found in cache\n",
				op->o_log_prefix, ref->bv_val, li.li_uri );

		} else {
			/* if none is found, create a temporary... */
			rc = ldap_chain_db_init_one( op->o_bd );
			if ( rc != 0 ) {
				Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\" unable to init back-ldap for URI=\"%s\"\n",
					op->o_log_prefix, ref->bv_val, li.li_uri );
				goto cleanup;
			}
			lip = (ldapinfo_t *)op->o_bd->be_private;
			lip->li_uri = li.li_uri;
			lip->li_bvuri = bvuri;
			rc = ldap_chain_db_open_one( op->o_bd );
			if ( rc != 0 ) {
				Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\" unable to open back-ldap for URI=\"%s\"\n",
					op->o_log_prefix, ref->bv_val, li.li_uri );
				lip->li_uri = NULL;
				lip->li_bvuri = NULL;
				(void)ldap_chain_db_destroy_one( op->o_bd, NULL );
				goto cleanup;
			}

			if ( LDAP_CHAIN_CACHE_URI( lc ) ) {
				ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
				if ( ldap_tavl_insert( &lc->lc_lai.lai_tree,
					(caddr_t)lip, ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
				{
					/* someone just inserted another;
					 * don't bother, use this and then
					 * just free it */
					temporary = 1;
				}
				ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );

			} else {
				temporary = 1;
			}

			Debug( LDAP_DEBUG_TRACE, "%s ldap_chain_search: ref=\"%s\" %s\n",
				op->o_log_prefix, ref->bv_val, temporary ? "temporary" : "caching" );
		}

		lb->lb_op_type = op_search;
		lb->lb_depth = depth + 1;

		/* FIXME: should we also copy filter and scope?
		 * according to RFC3296, no */
		rc = lback->bi_op_search( op, &rs2 );
		if ( first_rc == -1 ) {
			first_rc = rc;
		}

cleanup:;
		ldap_memfree( li.li_uri );
		li.li_uri = NULL;

		if ( temporary ) {
			lip->li_uri = NULL;
			lip->li_bvuri = NULL;
			(void)ldap_chain_db_close_one( op->o_bd );
			(void)ldap_chain_db_destroy_one( op->o_bd, NULL );
		}
		
further_cleanup:;
		if ( op->o_req_dn.bv_val == pdn.bv_val ) {
			op->o_req_dn = odn;
			op->o_req_ndn = ondn;
		}

		if ( free_dn ) {
			op->o_tmpfree( pdn.bv_val, op->o_tmpmemctx );
			op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
		}

		if ( tmp_oq_search.rs_filter != NULL ) {
			filter_free_x( op, tmp_oq_search.rs_filter, 1 );
		}

		if ( !BER_BVISNULL( &tmp_oq_search.rs_filterstr ) ) {
			slap_sl_free( tmp_oq_search.rs_filterstr.bv_val, op->o_tmpmemctx );
		}

		op->oq_search = save_oq_search;
		
		if ( rc == LDAP_SUCCESS && rs2.sr_err == LDAP_SUCCESS ) {
			*rs = rs2;
			break;
		}

		rc = rs2.sr_err;
	}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	(void)chaining_control_remove( op, &ctrls );
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	rs->sr_type = REP_SEARCHREF;
	rs->sr_entry = save_entry;
	rs->sr_flags = save_flags;

	if ( rc != LDAP_SUCCESS ) {
		/* couldn't chase any of the referrals */
		if ( first_rc != -1 ) {
			rc = first_rc;

		} else {
			rc = SLAP_CB_CONTINUE;
		}
	}

	return rc;
}

static int
ldap_chain_response( Operation *op, SlapReply *rs )
{
	slap_overinst	*on = (slap_overinst *)op->o_bd->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	BackendDB	db, *bd = op->o_bd;
	ldap_chain_cb_t	lb = { 0 };
	slap_callback	*sc = op->o_callback,
			sc2 = { 0 };
	int		rc = 0;
	const char	*text = NULL;
	const char	*matched;
	BerVarray	ref;
	slap_mask_t	flags = 0;
	struct berval	ndn = op->o_ndn;

	int		sr_err = rs->sr_err;
	slap_reply_t	sr_type = rs->sr_type;
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	slap_mask_t	chain_mask = 0;
	ber_len_t	chain_shift = 0;
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	if ( rs->sr_err != LDAP_REFERRAL && rs->sr_type != REP_SEARCHREF ) {
		return SLAP_CB_CONTINUE;
	}
	if ( !rs->sr_ref ) {
		return SLAP_CB_CONTINUE;
	}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	if ( rs->sr_err == LDAP_REFERRAL && get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
		switch ( get_resolveBehavior( op ) ) {
		case SLAP_CH_RESOLVE_REFERRALS_PREFERRED:
		case SLAP_CH_RESOLVE_REFERRALS_REQUIRED:
			return SLAP_CB_CONTINUE;

		default:
			chain_mask = SLAP_CH_RESOLVE_MASK;
			chain_shift = SLAP_CH_RESOLVE_SHIFT;
			break;
		}

	} else if ( rs->sr_type == REP_SEARCHREF && get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
		switch ( get_continuationBehavior( op ) ) {
		case SLAP_CH_CONTINUATION_REFERRALS_PREFERRED:
		case SLAP_CH_CONTINUATION_REFERRALS_REQUIRED:
			return SLAP_CB_CONTINUE;

		default:
			chain_mask = SLAP_CH_CONTINUATION_MASK;
			chain_shift = SLAP_CH_CONTINUATION_SHIFT;
			break;
		}
	}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	/*
	 * TODO: add checks on who/when chain operations; e.g.:
	 *   a) what identities are authorized
	 *   b) what request DN (e.g. only chain requests rooted at <DN>)
	 *   c) what referral URIs
	 *   d) what protocol scheme (e.g. only ldaps://)
	 *   e) what ssf
	 */

	db = *op->o_bd;
	SLAP_DBFLAGS( &db ) &= ~SLAP_DBFLAG_MONITORING;
	op->o_bd = &db;

	text = rs->sr_text;
	rs->sr_text = NULL;
	matched = rs->sr_matched;
	rs->sr_matched = NULL;
	ref = rs->sr_ref;
	rs->sr_ref = NULL;

	flags = rs->sr_flags & (REP_MATCHED_MUSTBEFREED | REP_REF_MUSTBEFREED);
	rs->sr_flags &= ~flags;

	/* we need this to know if back-ldap returned any result */
	lb.lb_lc = lc;
	sc2.sc_next = sc->sc_next;
	sc2.sc_private = &lb;
	sc2.sc_response = ldap_chain_cb_response;
	op->o_callback = &sc2;

	/* Chaining can be performed by a privileged user on behalf
	 * of normal users, using the ProxyAuthz control, by exploiting
	 * the identity assertion feature of back-ldap; see idassert-*
	 * directives in slapd-ldap(5).
	 *
	 * FIXME: the idassert-authcDN is one, will it be fine regardless
	 * of the URI we obtain from the referral?
	 */

	switch ( op->o_tag ) {
	case LDAP_REQ_BIND: {
		struct berval	rndn = op->o_req_ndn;
		Connection	*conn = op->o_conn;

		/* FIXME: can we really get a referral for binds? */
		op->o_req_ndn = slap_empty_bv;
		op->o_conn = NULL;
		rc = ldap_chain_op( op, rs, op_bind, ref, 0 );
		op->o_req_ndn = rndn;
		op->o_conn = conn;
		}
		break;

	case LDAP_REQ_ADD:
		rc = ldap_chain_op( op, rs, op_add, ref, 0 );
		break;

	case LDAP_REQ_DELETE:
		rc = ldap_chain_op( op, rs, op_delete, ref, 0 );
		break;

	case LDAP_REQ_MODRDN:
		rc = ldap_chain_op( op, rs, op_modrdn, ref, 0 );
	    	break;

	case LDAP_REQ_MODIFY:
		rc = ldap_chain_op( op, rs, op_modify, ref, 0 );
		break;

	case LDAP_REQ_COMPARE:
		rc = ldap_chain_op( op, rs, op_compare, ref, 0 );
		if ( rs->sr_err == LDAP_COMPARE_TRUE || rs->sr_err == LDAP_COMPARE_FALSE ) {
			rc = LDAP_SUCCESS;
		}
		break;

	case LDAP_REQ_SEARCH:
		if ( rs->sr_type == REP_SEARCHREF ) {
			sc2.sc_response = ldap_chain_cb_search_response;
			rc = ldap_chain_search( op, rs, ref, 0 );
			
		} else {
			/* we might get here before any database actually 
			 * performed a search; in those cases, we need
			 * to check limits, to make sure safe defaults
			 * are in place */
			if ( op->ors_limit != NULL || limits_check( op, rs ) == 0 ) {
				rc = ldap_chain_op( op, rs, op_search, ref, 0 );
			} else {
				rc = SLAP_CB_CONTINUE;
			}
		}
	    	break;

	case LDAP_REQ_EXTENDED:
		rc = ldap_chain_op( op, rs, op_extended, ref, 0 );
		/* FIXME: ldap_back_extended() by design 
		 * doesn't send result; frontend is expected
		 * to send it... */
		/* FIXME: what about chaining? */
		if ( rc != SLAPD_ABANDON ) {
			rs->sr_err = rc;
			send_ldap_extended( op, rs );
			rc = LDAP_SUCCESS;
		}
		lb.lb_status = LDAP_CH_RES;
		break;

	default:
		rc = SLAP_CB_CONTINUE;
		break;
	}

	switch ( rc ) {
	case SLAPD_ABANDON:
		goto dont_chain;

	case LDAP_SUCCESS:
	case LDAP_REFERRAL:
		sr_err = rs->sr_err;
		/* slapd-ldap sent response */
		if ( !op->o_abandon && lb.lb_status != LDAP_CH_RES ) {
			/* FIXME: should we send response? */
			Debug( LDAP_DEBUG_ANY,
				"%s: ldap_chain_response: "
				"overlay should have sent result.\n",
				op->o_log_prefix );
		}
		break;

	default:
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
		if ( lb.lb_status == LDAP_CH_ERR && rs->sr_err == LDAP_X_CANNOT_CHAIN ) {
			goto cannot_chain;
		}

		switch ( ( get_chainingBehavior( op ) & chain_mask ) >> chain_shift ) {
		case LDAP_CHAINING_REQUIRED:
cannot_chain:;
			op->o_callback = NULL;
			send_ldap_error( op, rs, LDAP_X_CANNOT_CHAIN,
				"operation cannot be completed without chaining" );
			goto dont_chain;

		default:
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
			if ( LDAP_CHAIN_RETURN_ERR( lc ) ) {
				sr_err = rs->sr_err = rc;
				rs->sr_text = lb.lb_text;
				rs->sr_type = sr_type;

			} else {
				rc = SLAP_CB_CONTINUE;
				rs->sr_err = sr_err;
				rs->sr_type = sr_type;
				rs->sr_text = text;
				rs->sr_matched = matched;
				rs->sr_ref = ref;
				rs->sr_flags |= flags;
			}
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
			break;
		}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
	}

	if ( lb.lb_status == LDAP_CH_NONE && rc != SLAPD_ABANDON ) {
		/* give the remaining callbacks a chance */
		op->o_callback = sc->sc_next;
		rc = rs->sr_err = slap_map_api2result( rs );
		send_ldap_result( op, rs );
	}

dont_chain:;
	rs->sr_err = sr_err;
	rs->sr_type = sr_type;
	rs->sr_text = text;
	rs->sr_matched = matched;
	rs->sr_ref = ref;
	rs->sr_flags |= flags;

	op->o_bd = bd;
	op->o_callback = sc;
	op->o_ndn = ndn;

	if ( rs->sr_text == lb.lb_text ) {
		rs->sr_text = NULL;
	}
	if ( lb.lb_text ) {
		ber_memfree_x( lb.lb_text, op->o_tmpmemctx );
	}

	return rc;
}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
static int
ldap_chain_parse_ctrl(
	Operation	*op,
	SlapReply	*rs,
	LDAPControl	*ctrl );

static int
str2chain( const char *s )
{
	if ( strcasecmp( s, "chainingPreferred" ) == 0 ) {
		return LDAP_CHAINING_PREFERRED;
		
	} else if ( strcasecmp( s, "chainingRequired" ) == 0 ) {
		return LDAP_CHAINING_REQUIRED;

	} else if ( strcasecmp( s, "referralsPreferred" ) == 0 ) {
		return LDAP_REFERRALS_PREFERRED;
		
	} else if ( strcasecmp( s, "referralsRequired" ) == 0 ) {
		return LDAP_REFERRALS_REQUIRED;
	}

	return -1;
}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

/*
 * configuration...
 */

enum {
	CH_CHAINING = 1,
	CH_CACHE_URI,
	CH_MAX_DEPTH,
	CH_RETURN_ERR,

	CH_LAST
};

static ConfigDriver chain_cf_gen;
static ConfigCfAdd chain_cfadd;
static ConfigLDAPadd chain_ldadd;
#ifdef SLAP_CONFIG_DELETE
static ConfigLDAPdel chain_lddel;
#endif

static ConfigTable chaincfg[] = {
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	{ "chain-chaining", "args",
		2, 4, 0, ARG_MAGIC|ARG_BERVAL|CH_CHAINING, chain_cf_gen,
		"( OLcfgOvAt:3.1 NAME 'olcChainingBehavior' "
			"DESC 'Chaining behavior control parameters (draft-sermersheim-ldap-chaining)' "
			"EQUALITY caseIgnoreMatch "
			"SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
	{ "chain-cache-uri", "TRUE/FALSE",
		2, 2, 0, ARG_MAGIC|ARG_ON_OFF|CH_CACHE_URI, chain_cf_gen,
		"( OLcfgOvAt:3.2 NAME 'olcChainCacheURI' "
			"DESC 'Enables caching of URIs not present in configuration' "
			"EQUALITY booleanMatch "
			"SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
	{ "chain-max-depth", "args",
		2, 2, 0, ARG_MAGIC|ARG_INT|CH_MAX_DEPTH, chain_cf_gen,
		"( OLcfgOvAt:3.3 NAME 'olcChainMaxReferralDepth' "
			"DESC 'max referral depth' "
			"SYNTAX OMsInteger "
			"EQUALITY integerMatch "
			"SINGLE-VALUE )", NULL, NULL },
	{ "chain-return-error", "TRUE/FALSE",
		2, 2, 0, ARG_MAGIC|ARG_ON_OFF|CH_RETURN_ERR, chain_cf_gen,
		"( OLcfgOvAt:3.4 NAME 'olcChainReturnError' "
			"DESC 'Errors are returned instead of the original referral' "
			"EQUALITY booleanMatch "
			"SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
	{ NULL, NULL, 0, 0, 0, ARG_IGNORED }
};

static ConfigOCs chainocs[] = {
	{ "( OLcfgOvOc:3.1 "
		"NAME 'olcChainConfig' "
		"DESC 'Chain configuration' "
		"SUP olcOverlayConfig "
		"MAY ( "
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
			"olcChainingBehavior $ "
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
			"olcChainCacheURI $ "
			"olcChainMaxReferralDepth $ "
			"olcChainReturnError "
			") )",
		Cft_Overlay, chaincfg, NULL, chain_cfadd },
	{ "( OLcfgOvOc:3.2 "
		"NAME 'olcChainDatabase' "
		"DESC 'Chain remote server configuration' "
		"AUXILIARY )",
		Cft_Misc, NULL, chain_ldadd
#ifdef SLAP_CONFIG_DELETE
		, NULL, chain_lddel
#endif
	},
	{ NULL, 0, NULL }
};

static int
chain_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
{
	slap_overinst		*on;
	ldap_chain_t		*lc;

	ldapinfo_t		*li;

	AttributeDescription	*ad = NULL;
	Attribute		*at;
	const char		*text;

	int			rc;

	if ( p->ce_type != Cft_Overlay
		|| !p->ce_bi
		|| p->ce_bi->bi_cf_ocs != chainocs )
	{
		return LDAP_CONSTRAINT_VIOLATION;
	}

	on = (slap_overinst *)p->ce_bi;
	lc = (ldap_chain_t *)on->on_bi.bi_private;

	assert( ca->be == NULL );
	ca->be = (BackendDB *)ch_calloc( 1, sizeof( BackendDB ) );

	ca->be->bd_info = (BackendInfo *)on;

	rc = slap_str2ad( "olcDbURI", &ad, &text );
	assert( rc == LDAP_SUCCESS );

	at = attr_find( e->e_attrs, ad );
#if 0
	if ( lc->lc_common_li == NULL && at != NULL ) {
		/* FIXME: we should generate an empty default entry
		 * if none is supplied */
		Debug( LDAP_DEBUG_ANY, "slapd-chain: "
			"first underlying database \"%s\" "
			"cannot contain attribute \"%s\".\n",
			e->e_name.bv_val, ad->ad_cname.bv_val );
		rc = LDAP_CONSTRAINT_VIOLATION;
		goto done;

	} else
#endif
	if ( lc->lc_common_li != NULL && lc->lc_common_li != lc->lc_cfg_li && at == NULL ) {
		/* FIXME: we should generate an empty default entry
		 * if none is supplied */
		Debug( LDAP_DEBUG_ANY, "slapd-chain: "
			"subsequent underlying database \"%s\" "
			"must contain attribute \"%s\".\n",
			e->e_name.bv_val, ad->ad_cname.bv_val );
		rc = LDAP_CONSTRAINT_VIOLATION;
		goto done;
	}

	if ( lc->lc_common_li == NULL ) {
		rc = ldap_chain_db_init_common( ca->be );
		if ( rc != 0 )
			goto fail;
		li = ca->be->be_private;
		lc->lc_common_li = lc->lc_cfg_li = li;

	}
	rc = ldap_chain_db_init_one( ca->be );
	lc->lc_cfg_li = NULL;

	if ( rc != 0 ) {
fail:
		Debug( LDAP_DEBUG_ANY, "slapd-chain: "
			"unable to init %sunderlying database \"%s\".\n",
			lc->lc_common_li == NULL ? "common " : "", e->e_name.bv_val );
		return LDAP_CONSTRAINT_VIOLATION;
	}

	li = ca->be->be_private;

	if ( at ) {
		char **urls;

		urls = ldap_str2charray( at->a_vals[ 0 ].bv_val, ", \t" );
		if ( !urls || !urls[0] || urls[1] ) {
			ldap_charray_free( urls );
			Debug( LDAP_DEBUG_ANY, "slapd-chain: "
				"olcDbURI must contain exactly one url, got %s\n",
				at->a_vals[ 0 ].bv_val );
			rc = LDAP_CONSTRAINT_VIOLATION;
			goto done;
		}
		ldap_charray_free( urls );

		li->li_uri = ch_strdup( at->a_vals[ 0 ].bv_val );
		value_add_one( &li->li_bvuri, &at->a_vals[ 0 ] );
		if ( ldap_tavl_insert( &lc->lc_lai.lai_tree, (caddr_t)li,
			ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
		{
			Debug( LDAP_DEBUG_ANY, "slapd-chain: "
				"database \"%s\" insert failed.\n",
				e->e_name.bv_val );
			rc = LDAP_CONSTRAINT_VIOLATION;
			goto done;
		}
	}

	ca->ca_private = on;

done:;
	if ( rc != LDAP_SUCCESS ) {
		(void)ldap_chain_db_destroy_one( ca->be, NULL );
		ch_free( ca->be );
		ca->be = NULL;
	}

	return rc;
}

static void
ldap_chain_cfadd_apply(
	ldapinfo_t *li,
	Operation *op,
	SlapReply *rs,
	Entry *p,
	ConfigArgs *ca,
	int count )
{
	struct berval			bv;

	/* FIXME: should not hardcode "olcDatabase" here */
	bv.bv_len = snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
		"olcDatabase={%d}%s", count, lback->bi_type );
	bv.bv_val = ca->cr_msg;

	ca->be->be_private = (void *)li;
	config_build_entry( op, rs, p->e_private, ca,
		&bv, lback->bi_cf_ocs, &chainocs[1] );

	return;
}

static int
chain_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
{
	CfEntryInfo	*pe = p->e_private;
	slap_overinst	*on = (slap_overinst *)pe->ce_bi;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	void		*priv = (void *)ca->be->be_private;
	TAvlnode	*edge;
	int		count = 0;

	if ( lback->bi_cf_ocs ) {

		ldap_chain_cfadd_apply( lc->lc_common_li, op, rs, p, ca, count++ );

		edge = ldap_tavl_end( lc->lc_lai.lai_tree, TAVL_DIR_LEFT );
		while ( edge ) {
			TAvlnode *next = ldap_tavl_next( edge, TAVL_DIR_RIGHT );
			ldapinfo_t *li = (ldapinfo_t *)edge->avl_data;
			ldap_chain_cfadd_apply( li, op, rs, p, ca, count++ );
			edge = next;
		}

		ca->be->be_private = priv;
	}

	lc->lc_cfg_li = NULL;

	return 0;
}

#ifdef SLAP_CONFIG_DELETE
static int
chain_lddel( CfEntryInfo *ce, Operation *op )
{
	CfEntryInfo	*pe = ce->ce_parent;
	slap_overinst	*on = (slap_overinst *)pe->ce_bi;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	ldapinfo_t	*li = (ldapinfo_t *) ce->ce_be->be_private;

	if ( li != lc->lc_common_li ) {
		if (! ldap_tavl_delete( &lc->lc_lai.lai_tree, li, ldap_chain_uri_cmp ) ) {
			Debug( LDAP_DEBUG_ANY, "slapd-chain: ldap_avl_delete failed. "
				"\"%s\" not found.\n", li->li_uri );
			return -1;
		}
	} else if ( lc->lc_lai.lai_tree ) {
		Debug( LDAP_DEBUG_ANY, "slapd-chain: cannot delete first underlying "
			"LDAP database when other databases are still present.\n" );
		return -1;
	} else {
		lc->lc_common_li = NULL;
	}

	ce->ce_be->bd_info = lback;

	if ( ce->ce_be->bd_info->bi_db_close ) {
		ce->ce_be->bd_info->bi_db_close( ce->ce_be, NULL );
	}
	if ( ce->ce_be->bd_info->bi_db_destroy ) {
		ce->ce_be->bd_info->bi_db_destroy( ce->ce_be, NULL );
	}

	ch_free(ce->ce_be);
	ce->ce_be = NULL;

	return LDAP_SUCCESS;
}
#endif /* SLAP_CONFIG_DELETE */

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
static slap_verbmasks chaining_mode[] = {
	{ BER_BVC("referralsRequired"),		LDAP_REFERRALS_REQUIRED },
	{ BER_BVC("referralsPreferred"),	LDAP_REFERRALS_PREFERRED },
	{ BER_BVC("chainingRequired"),		LDAP_CHAINING_REQUIRED },
	{ BER_BVC("chainingPreferred"),		LDAP_CHAINING_PREFERRED },
	{ BER_BVNULL,				0 }
};
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

static int
chain_cf_gen( ConfigArgs *c )
{
	slap_overinst	*on = (slap_overinst *)c->bi;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;

	int		rc = 0;

	if ( c->op == SLAP_CONFIG_EMIT ) {
		switch( c->type ) {
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
		case CH_CHAINING: {
			struct berval	resolve = BER_BVNULL,
					continuation = BER_BVNULL;

			if ( !LDAP_CHAIN_CHAINING( lc ) ) {
				return 1;
			}

			enum_to_verb( chaining_mode, ( ( lc->lc_chaining_ctrlflag & SLAP_CH_RESOLVE_MASK ) >> SLAP_CH_RESOLVE_SHIFT ), &resolve );
			enum_to_verb( chaining_mode, ( ( lc->lc_chaining_ctrlflag & SLAP_CH_CONTINUATION_MASK ) >> SLAP_CH_CONTINUATION_SHIFT ), &continuation );

			c->value_bv.bv_len = STRLENOF( "resolve=" ) + resolve.bv_len
				+ STRLENOF( " " )
				+ STRLENOF( "continuation=" ) + continuation.bv_len;
			c->value_bv.bv_val = ch_malloc( c->value_bv.bv_len + 1 );
			snprintf( c->value_bv.bv_val, c->value_bv.bv_len + 1,
				"resolve=%s continuation=%s",
				resolve.bv_val, continuation.bv_val );

			if ( lc->lc_chaining_ctrl.ldctl_iscritical ) {
				c->value_bv.bv_val = ch_realloc( c->value_bv.bv_val,
					c->value_bv.bv_len + STRLENOF( " critical" ) + 1 );
				AC_MEMCPY( &c->value_bv.bv_val[ c->value_bv.bv_len ],
					" critical", STRLENOF( " critical" ) + 1 );
				c->value_bv.bv_len += STRLENOF( " critical" );
			}

			break;
		}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

		case CH_CACHE_URI:
			c->value_int = LDAP_CHAIN_CACHE_URI( lc );
			break;

		case CH_MAX_DEPTH:
			c->value_int = lc->lc_max_depth;
			break;

		case CH_RETURN_ERR:
			c->value_int = LDAP_CHAIN_RETURN_ERR( lc );
			break;

		default:
			assert( 0 );
			rc = 1;
		}
		return rc;

	} else if ( c->op == LDAP_MOD_DELETE ) {
		switch( c->type ) {
		case CH_CHAINING:
			return 1;

		case CH_CACHE_URI:
			lc->lc_flags &= ~LDAP_CHAIN_F_CACHE_URI;
			break;

		case CH_MAX_DEPTH:
			c->value_int = 0;
			break;

		case CH_RETURN_ERR:
			lc->lc_flags &= ~LDAP_CHAIN_F_RETURN_ERR;
			break;

		default:
			return 1;
		}
		return rc;
	}

	switch( c->type ) {
	case CH_CHAINING: {
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
		char			**argv = c->argv;
		int			argc = c->argc;
		BerElementBuffer	berbuf;
		BerElement		*ber = (BerElement *)&berbuf;
		int			resolve = -1,
					continuation = -1,
					iscritical = 0;
		Operation		op = { 0 };
		SlapReply		rs = { 0 };

		lc->lc_chaining_ctrlflag = 0;

		for ( argc--, argv++; argc > 0; argc--, argv++ ) {
			if ( strncasecmp( argv[ 0 ], "resolve=", STRLENOF( "resolve=" ) ) == 0 ) {
				resolve = str2chain( argv[ 0 ] + STRLENOF( "resolve=" ) );
				if ( resolve == -1 ) {
					Debug( LDAP_DEBUG_ANY, "%s: "
						"illegal <resolve> value %s "
						"in \"chain-chaining>\".\n",
						c->log, argv[ 0 ] );
					return 1;
				}

			} else if ( strncasecmp( argv[ 0 ], "continuation=", STRLENOF( "continuation=" ) ) == 0 ) {
				continuation = str2chain( argv[ 0 ] + STRLENOF( "continuation=" ) );
				if ( continuation == -1 ) {
					Debug( LDAP_DEBUG_ANY, "%s: "
						"illegal <continuation> value %s "
						"in \"chain-chaining\".\n",
						c->log, argv[ 0 ] );
					return 1;
				}

			} else if ( strcasecmp( argv[ 0 ], "critical" ) == 0 ) {
				iscritical = 1;

			} else {
				Debug( LDAP_DEBUG_ANY, "%s: "
					"unknown option in \"chain-chaining\".\n",
					c->log );
				return 1;
			}
		}

		if ( resolve != -1 || continuation != -1 ) {
			int	err;

			if ( resolve == -1 ) {
				/* default */
				resolve = SLAP_CHAINING_DEFAULT;
			}

			ber_init2( ber, NULL, LBER_USE_DER );

			err = ber_printf( ber, "{e" /* } */, resolve );
	    		if ( err == -1 ) {
				ber_free( ber, 1 );
				Debug( LDAP_DEBUG_ANY, "%s: "
					"chaining behavior control encoding error!\n",
					c->log );
				return 1;
			}

			if ( continuation > -1 ) {
				err = ber_printf( ber, "e", continuation );
	    			if ( err == -1 ) {
					ber_free( ber, 1 );
					Debug( LDAP_DEBUG_ANY, "%s: "
						"chaining behavior control encoding error!\n",
						c->log );
					return 1;
				}
			}

			err = ber_printf( ber, /* { */ "N}" );
	    		if ( err == -1 ) {
				ber_free( ber, 1 );
				Debug( LDAP_DEBUG_ANY, "%s: "
					"chaining behavior control encoding error!\n",
					c->log );
				return 1;
			}

			if ( ber_flatten2( ber, &lc->lc_chaining_ctrl.ldctl_value, 0 ) == -1 ) {
				exit( EXIT_FAILURE );
			}

		} else {
			BER_BVZERO( &lc->lc_chaining_ctrl.ldctl_value );
		}

		lc->lc_chaining_ctrl.ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
		lc->lc_chaining_ctrl.ldctl_iscritical = iscritical;

		if ( ldap_chain_parse_ctrl( &op, &rs, &lc->lc_chaining_ctrl ) != LDAP_SUCCESS )
		{
			Debug( LDAP_DEBUG_ANY, "%s: "
				"unable to parse chaining control%s%s.\n",
				c->log, rs.sr_text ? ": " : "",
				rs.sr_text ? rs.sr_text : "" );
			return 1;
		}

		lc->lc_chaining_ctrlflag = op.o_chaining;

		lc->lc_flags |= LDAP_CHAIN_F_CHAINING;

		rc = 0;
#else /* ! LDAP_CONTROL_X_CHAINING_BEHAVIOR */
		Debug( LDAP_DEBUG_ANY, "%s: "
			"\"chaining\" control unsupported (ignored).\n",
			c->log );
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
		} break;

	case CH_CACHE_URI:
		if ( c->value_int ) {
			lc->lc_flags |= LDAP_CHAIN_F_CACHE_URI;
		} else {
			lc->lc_flags &= ~LDAP_CHAIN_F_CACHE_URI;
		}
		break;

	case CH_MAX_DEPTH:
		if ( c->value_int < 0 ) {
			snprintf( c->cr_msg, sizeof( c->cr_msg ),
				"<%s> invalid max referral depth %d",
				c->argv[0], c->value_int );
			Debug( LDAP_DEBUG_ANY, "%s: %s.\n",
				c->log, c->cr_msg );
			rc = 1;
			break;
		}
		lc->lc_max_depth = c->value_int;

	case CH_RETURN_ERR:
		if ( c->value_int ) {
			lc->lc_flags |= LDAP_CHAIN_F_RETURN_ERR;
		} else {
			lc->lc_flags &= ~LDAP_CHAIN_F_RETURN_ERR;
		}
		break;

	default:
		assert( 0 );
		return 1;
	}
	return rc;
}

static int
ldap_chain_db_init(
	BackendDB *be,
	ConfigReply *cr )
{
	slap_overinst	*on = (slap_overinst *)be->bd_info;
	ldap_chain_t	*lc = NULL;

	if ( lback == NULL ) {
		lback = backend_info( "ldap" );

		if ( lback == NULL ) {
			return 1;
		}
	}

	lc = ch_malloc( sizeof( ldap_chain_t ) );
	if ( lc == NULL ) {
		return 1;
	}
	memset( lc, 0, sizeof( ldap_chain_t ) );
	lc->lc_max_depth = 1;
	ldap_pvt_thread_mutex_init( &lc->lc_lai.lai_mutex );

	on->on_bi.bi_private = (void *)lc;

	return 0;
}

static int
ldap_chain_db_config(
	BackendDB	*be,
	const char	*fname,
	int		lineno,
	int		argc,
	char		**argv )
{
	slap_overinst	*on = (slap_overinst *)be->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;

	int		rc = SLAP_CONF_UNKNOWN;

	if ( lc->lc_common_li == NULL ) {
		BackendDB db = *be;
		ldap_chain_db_init_common( &db );
		lc->lc_common_li = lc->lc_cfg_li = (ldapinfo_t *)db.be_private;
	}

	/* Something for the chain database? */
	if ( strncasecmp( argv[ 0 ], "chain-", STRLENOF( "chain-" ) ) == 0 ) {
		char		*save_argv0 = argv[ 0 ];
		BackendDB	db = *be;
		static char	*allowed_argv[] = {
			/* special: put URI here, so in the meanwhile
			 * it detects whether a new URI is being provided */
			"uri",
			"nretries",
			"timeout",
			/* flags */
			"tls",
			/* FIXME: maybe rebind-as-user should be allowed
			 * only within known URIs... */
			"rebind-as-user",
			"chase-referrals",
			"t-f-support",
			"proxy-whoami",
			NULL
		};
		int		which_argv = -1;

		argv[ 0 ] += STRLENOF( "chain-" );

		for ( which_argv = 0; allowed_argv[ which_argv ]; which_argv++ ) {
			if ( strcasecmp( argv[ 0 ], allowed_argv[ which_argv ] ) == 0 ) {
				break;
			}
		}

		if ( allowed_argv[ which_argv ] == NULL ) {
			which_argv = -1;

			if ( lc->lc_cfg_li == lc->lc_common_li ) {
				Debug( LDAP_DEBUG_ANY, "%s: line %d: "
					"\"%s\" only allowed within a URI directive.\n.",
					fname, lineno, argv[ 0 ] );
				return 1;
			}
		}

		if ( which_argv == 0 ) {
			rc = ldap_chain_db_init_one( &db );
			if ( rc != 0 ) {
				Debug( LDAP_DEBUG_ANY, "%s: line %d: "
					"underlying slapd-ldap initialization failed.\n.",
					fname, lineno );
				return 1;
			}
			lc->lc_cfg_li = db.be_private;
		}

		/* TODO: add checks on what other slapd-ldap(5) args
		 * should be put in the template; this is not quite
		 * harmful, because attributes that shouldn't don't
		 * get actually used, but the user should at least
		 * be warned.
		 */

		db.bd_info = lback;
		db.be_private = (void *)lc->lc_cfg_li;
		db.be_cf_ocs = lback->bi_cf_ocs;

		rc = config_generic_wrapper( &db, fname, lineno, argc, argv );

		argv[ 0 ] = save_argv0;

		if ( which_argv == 0 ) {
private_destroy:;
			if ( rc != 0 ) {
				db.bd_info = lback;
				db.be_private = (void *)lc->lc_cfg_li;
				ldap_chain_db_destroy_one( &db, NULL );
				lc->lc_cfg_li = NULL;
			} else {
				if ( lc->lc_cfg_li->li_bvuri == NULL
					|| BER_BVISNULL( &lc->lc_cfg_li->li_bvuri[ 0 ] )
					|| !BER_BVISNULL( &lc->lc_cfg_li->li_bvuri[ 1 ] ) )
				{
					Debug( LDAP_DEBUG_ANY, "%s: line %d: "
						"no URI list allowed in slapo-chain.\n",
						fname, lineno );
					rc = 1;
					goto private_destroy;
				}

				if ( ldap_tavl_insert( &lc->lc_lai.lai_tree,
					(caddr_t)lc->lc_cfg_li,
					ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
				{
					Debug( LDAP_DEBUG_ANY, "%s: line %d: "
						"duplicate URI in slapo-chain.\n",
						fname, lineno );
					rc = 1;
					goto private_destroy;
				}
			}
		}
	}

	return rc;
}

enum db_which {
	db_open = 0,
	db_close,
	db_destroy,

	db_last
};

static int
ldap_chain_db_func(
	BackendDB *be,
	enum db_which which
)
{
	slap_overinst	*on = (slap_overinst *)be->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;

	int		rc = 0;

	if ( lc ) {
		BI_db_func	*func = (&lback->bi_db_open)[ which ];

		if ( func != NULL && lc->lc_common_li != NULL ) {
			BackendDB		db = *be;

			db.bd_info = lback;
			db.be_private = lc->lc_common_li;

			rc = func( &db, NULL );

			if ( rc != 0 ) {
				return rc;
			}

			if ( lc->lc_lai.lai_tree != NULL ) {
				TAvlnode *edge = ldap_tavl_end( lc->lc_lai.lai_tree, TAVL_DIR_LEFT );
				while ( edge ) {
					TAvlnode *next = ldap_tavl_next( edge, TAVL_DIR_RIGHT );
					ldapinfo_t *li = (ldapinfo_t *)edge->avl_data;
					db.be_private = (void *)li;
					rc = func( &db, NULL );
					if ( rc == 1 ) {
						break;
					}
					edge = next;
				}
			}
		}
	}

	return rc;
}

static int
ldap_chain_db_open(
	BackendDB	*be,
	ConfigReply	*cr )
{
	slap_overinst	*on = (slap_overinst *) be->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;
	slap_mask_t	monitoring;
	int		rc = 0;

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	rc = overlay_register_control( be, LDAP_CONTROL_X_CHAINING_BEHAVIOR );
	if ( rc != 0 ) {
		return rc;
	}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	if ( lc->lc_common_li == NULL ) {
		void	*be_private = be->be_private;
		ldap_chain_db_init_common( be );
		lc->lc_common_li = lc->lc_cfg_li = (ldapinfo_t *)be->be_private;
		be->be_private = be_private;
	}

	/* filter out and restore monitoring */
	monitoring = ( SLAP_DBFLAGS( be ) & SLAP_DBFLAG_MONITORING );
	SLAP_DBFLAGS( be ) &= ~SLAP_DBFLAG_MONITORING;
	rc = ldap_chain_db_func( be, db_open );
	SLAP_DBFLAGS( be ) |= monitoring;

	return rc;
}

static int
ldap_chain_db_close(
	BackendDB	*be,
	ConfigReply	*cr )
{
#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
#ifdef SLAP_CONFIG_DELETE
	overlay_unregister_control( be, LDAP_CONTROL_X_CHAINING_BEHAVIOR );
#endif /* SLAP_CONFIG_DELETE */
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
	return ldap_chain_db_func( be, db_close );
}

static int
ldap_chain_db_destroy(
	BackendDB	*be,
	ConfigReply	*cr )
{
	slap_overinst	*on = (slap_overinst *) be->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;

	int		rc;

	rc = ldap_chain_db_func( be, db_destroy );

	if ( lc ) {
		ldap_tavl_free( lc->lc_lai.lai_tree, NULL );
		ldap_pvt_thread_mutex_destroy( &lc->lc_lai.lai_mutex );
		ch_free( lc );
	}

	return rc;
}

/*
 * inits one instance of the slapd-ldap backend, and stores
 * the private info in be_private of the arg
 */
static int
ldap_chain_db_init_common(
	BackendDB	*be )
{
	BackendInfo	*bi = be->bd_info;
	ldapinfo_t	*li;
	int		rc;

	be->bd_info = lback;
	be->be_private = NULL;
	rc = lback->bi_db_init( be, NULL );
	if ( rc != 0 ) {
		return rc;
	}
	li = (ldapinfo_t *)be->be_private;
	li->li_urllist_f = NULL;
	li->li_urllist_p = NULL;

	be->bd_info = bi;

	return 0;
}

/*
 * inits one instance of the slapd-ldap backend, stores
 * the private info in be_private of the arg and fills
 * selected fields with data from the template.
 *
 * NOTE: add checks about the other fields of the template,
 * which are ignored and SHOULD NOT be configured by the user.
 */
static int
ldap_chain_db_init_one(
	BackendDB	*be )
{
	slap_overinst	*on = (slap_overinst *)be->bd_info;
	ldap_chain_t	*lc = (ldap_chain_t *)on->on_bi.bi_private;

	BackendInfo	*bi = be->bd_info;
	ldapinfo_t	*li;

	slap_op_t	t;

	be->bd_info = lback;
	be->be_private = NULL;
	t = lback->bi_db_init( be, NULL );
	if ( t != 0 ) {
		return t;
	}
	li = (ldapinfo_t *)be->be_private;
	li->li_urllist_f = NULL;
	li->li_urllist_p = NULL;

	/* copy common data */
	li->li_nretries = lc->lc_common_li->li_nretries;
	li->li_flags = lc->lc_common_li->li_flags;
	li->li_version = lc->lc_common_li->li_version;
	for ( t = 0; t < SLAP_OP_LAST; t++ ) {
		li->li_timeout[ t ] = lc->lc_common_li->li_timeout[ t ];
	}
	be->bd_info = bi;

	return 0;
}

static int
ldap_chain_db_open_one(
	BackendDB	*be )
{
	if ( SLAP_DBMONITORING( be ) ) {
		ldapinfo_t	*li = (ldapinfo_t *)be->be_private;

		if ( li->li_uri == NULL ) {
			ber_str2bv( "cn=Common Connections", 0, 1,
				&li->li_monitor_info.lmi_conn_rdn );
			ber_str2bv( "cn=Operations on Common Connections", 0, 1,
				&li->li_monitor_info.lmi_conn_rdn );

		} else {
			char		*ptr;

			li->li_monitor_info.lmi_conn_rdn.bv_len
				= STRLENOF( "cn=" ) + strlen( li->li_uri );
			ptr = li->li_monitor_info.lmi_conn_rdn.bv_val
				= ch_malloc( li->li_monitor_info.lmi_conn_rdn.bv_len + 1 );
			ptr = lutil_strcopy( ptr, "cn=" );
			ptr = lutil_strcopy( ptr, li->li_uri );
			ptr[ 0 ] = '\0';

			li->li_monitor_info.lmi_ops_rdn.bv_len
				= STRLENOF( "cn=Operations on " ) + strlen( li->li_uri );
			ptr = li->li_monitor_info.lmi_ops_rdn.bv_val
				= ch_malloc( li->li_monitor_info.lmi_ops_rdn.bv_len + 1 );
			ptr = lutil_strcopy( ptr, "cn=Operations on " );
			ptr = lutil_strcopy( ptr, li->li_uri );
			ptr[ 0 ] = '\0';
		}
	}

	return lback->bi_db_open( be, NULL );
}

static int
ldap_chain_connection_destroy(
	BackendDB *be,
	Connection *conn
)
{
	slap_overinst		*on = (slap_overinst *) be->bd_info;
	ldap_chain_t		*lc = (ldap_chain_t *)on->on_bi.bi_private;
	void			*private = be->be_private;
	TAvlnode		*edge;
	int			rc;

	be->be_private = NULL;
	ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
	edge = ldap_tavl_end( lc->lc_lai.lai_tree, TAVL_DIR_LEFT );
	while ( edge ) {
		TAvlnode *next = ldap_tavl_next( edge, TAVL_DIR_RIGHT );
		ldapinfo_t *li = (ldapinfo_t *)edge->avl_data;
		be->be_private = (void *)li;
		rc = lback->bi_connection_destroy( be, conn );
		if ( rc == 1 ) {
			break;
		}
		edge = next;
	}


	ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );
	be->be_private = private;

	return rc;
}

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
static int
ldap_chain_parse_ctrl(
	Operation	*op,
	SlapReply	*rs,
	LDAPControl	*ctrl )
{
	ber_tag_t	tag;
	BerElement	*ber;
	ber_int_t	mode,
			behavior;

	if ( get_chaining( op ) != SLAP_CONTROL_NONE ) {
		rs->sr_text = "Chaining behavior control specified multiple times";
		return LDAP_PROTOCOL_ERROR;
	}

	if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
		rs->sr_text = "Chaining behavior control specified with pagedResults control";
		return LDAP_PROTOCOL_ERROR;
	}

	if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
		mode = (SLAP_CH_RESOLVE_DEFAULT|SLAP_CH_CONTINUATION_DEFAULT);

	} else {
		ber_len_t	len;

		/* Parse the control value
		 *      ChainingBehavior ::= SEQUENCE { 
		 *           resolveBehavior         Behavior OPTIONAL, 
		 *           continuationBehavior    Behavior OPTIONAL } 
		 *                             
		 *      Behavior :: = ENUMERATED { 
		 *           chainingPreferred       (0), 
		 *           chainingRequired        (1), 
		 *           referralsPreferred      (2), 
		 *           referralsRequired       (3) } 
		 */

		ber = ber_init( &ctrl->ldctl_value );
		if( ber == NULL ) {
			rs->sr_text = "internal error";
			return LDAP_OTHER;
		}

		tag = ber_scanf( ber, "{e" /* } */, &behavior );
		/* FIXME: since the whole SEQUENCE is optional,
		 * should we accept no enumerations at all? */
		if ( tag != LBER_ENUMERATED ) {
			rs->sr_text = "Chaining behavior control: resolveBehavior decoding error";
			return LDAP_PROTOCOL_ERROR;
		}

		switch ( behavior ) {
		case LDAP_CHAINING_PREFERRED:
			mode = SLAP_CH_RESOLVE_CHAINING_PREFERRED;
			break;

		case LDAP_CHAINING_REQUIRED:
			mode = SLAP_CH_RESOLVE_CHAINING_REQUIRED;
			break;

		case LDAP_REFERRALS_PREFERRED:
			mode = SLAP_CH_RESOLVE_REFERRALS_PREFERRED;
			break;

		case LDAP_REFERRALS_REQUIRED:
			mode = SLAP_CH_RESOLVE_REFERRALS_REQUIRED;
			break;

		default:
			rs->sr_text = "Chaining behavior control: unknown resolveBehavior";
			return LDAP_PROTOCOL_ERROR;
		}

		tag = ber_peek_tag( ber, &len );
		if ( tag == LBER_ENUMERATED ) {
			tag = ber_scanf( ber, "e", &behavior );
			if ( tag == LBER_ERROR ) {
				rs->sr_text = "Chaining behavior control: continuationBehavior decoding error";
				return LDAP_PROTOCOL_ERROR;
			}
		}

		if ( tag == LBER_DEFAULT ) {
			mode |= SLAP_CH_CONTINUATION_DEFAULT;

		} else {
			switch ( behavior ) {
			case LDAP_CHAINING_PREFERRED:
				mode |= SLAP_CH_CONTINUATION_CHAINING_PREFERRED;
				break;

			case LDAP_CHAINING_REQUIRED:
				mode |= SLAP_CH_CONTINUATION_CHAINING_REQUIRED;
				break;

			case LDAP_REFERRALS_PREFERRED:
				mode |= SLAP_CH_CONTINUATION_REFERRALS_PREFERRED;
				break;

			case LDAP_REFERRALS_REQUIRED:
				mode |= SLAP_CH_CONTINUATION_REFERRALS_REQUIRED;
				break;

			default:
				rs->sr_text = "Chaining behavior control: unknown continuationBehavior";
				return LDAP_PROTOCOL_ERROR;
			}
		}

		if ( ( ber_scanf( ber, /* { */ "}") ) == LBER_ERROR ) {
			rs->sr_text = "Chaining behavior control: decoding error";
			return LDAP_PROTOCOL_ERROR;
		}

		(void) ber_free( ber, 1 );
	}

	op->o_chaining = mode | ( ctrl->ldctl_iscritical
			? SLAP_CONTROL_CRITICAL
			: SLAP_CONTROL_NONCRITICAL );

	return LDAP_SUCCESS;
}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

int
chain_initialize( void )
{
	int rc;

	/* Make sure we don't exceed the bits reserved for userland */
	config_check_userland( CH_LAST );

	/* olcDatabaseDummy is defined in slapd, and Windows
	   will not let us initialize a struct element with a data pointer
	   from another library, so we have to initialize this element
	   "by hand".  */
	chainocs[1].co_table = olcDatabaseDummy;

#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
	rc = register_supported_control( LDAP_CONTROL_X_CHAINING_BEHAVIOR,
			/* SLAP_CTRL_GLOBAL| */ SLAP_CTRL_ACCESS|SLAP_CTRL_HIDE, NULL,
			ldap_chain_parse_ctrl, &sc_chainingBehavior );
	if ( rc != LDAP_SUCCESS ) {
		Debug( LDAP_DEBUG_ANY, "slapd-chain: "
			"unable to register chaining behavior control: %d.\n",
			rc );
		return rc;
	}
#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */

	ldapchain.on_bi.bi_type = "chain";
	ldapchain.on_bi.bi_db_init = ldap_chain_db_init;
	ldapchain.on_bi.bi_db_config = ldap_chain_db_config;
	ldapchain.on_bi.bi_db_open = ldap_chain_db_open;
	ldapchain.on_bi.bi_db_close = ldap_chain_db_close;
	ldapchain.on_bi.bi_db_destroy = ldap_chain_db_destroy;

	ldapchain.on_bi.bi_connection_destroy = ldap_chain_connection_destroy;

	ldapchain.on_response = ldap_chain_response;

	ldapchain.on_bi.bi_cf_ocs = chainocs;

	rc = config_register_schema( chaincfg, chainocs );
	if ( rc ) {
		return rc;
	}

	return overlay_register( &ldapchain );
}