summaryrefslogtreecommitdiffstats
path: root/pykolab/auth/ldap/__init__.py
blob: 54e231db3fd8770cd29fe73bb0f18ce03f453f62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 or, at your option, any later version
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

import datetime
import _ldap
import ldap
import ldap.async
import ldap.controls
import logging
import time

import pykolab
import pykolab.base

from pykolab import utils
from pykolab.constants import *
from pykolab.errors import *
from pykolab.translate import _

log = pykolab.getLogger('pykolab.auth')
conf = pykolab.getConf()

import cache

# Catch python-ldap-2.4 changes
from distutils import version

if version.StrictVersion('2.4.0') <= version.StrictVersion(ldap.__version__):
    LDAP_CONTROL_PAGED_RESULTS = ldap.CONTROL_PAGEDRESULTS
else:
    LDAP_CONTROL_PAGED_RESULTS = ldap.LDAP_CONTROL_PAGE_OID

try:
    from ldap.controls import psearch
except:
    log.warning(_("Python LDAP library does not support persistent search"))

class SimplePagedResultsControl(ldap.controls.SimplePagedResultsControl):
    """

        Python LDAP 2.4 and later breaks the API. This is an abstraction class
        so that we can handle either.
    """

    def __init__(self, page_size=0, cookie=''):
        if version.StrictVersion(
                '2.4.0'
            ) <= version.StrictVersion(
                    ldap.__version__
                ):

            ldap.controls.SimplePagedResultsControl.__init__(
                    self,
                    size=page_size,
                    cookie=cookie
                )
        else:
            ldap.controls.SimplePagedResultsControl.__init__(
                    self,
                    LDAP_CONTROL_PAGED_RESULTS,
                    True,
                    (page_size, '')
                )

    def cookie(self):
        if version.StrictVersion(
                '2.4.0'
            ) <= version.StrictVersion(
                    ldap.__version__
                ):

            return self.cookie
        else:
            return self.controlValue[1]

    def size(self):
        if version.StrictVersion(
                '2.4.0'
            ) <= version.StrictVersion(
                    ldap.__version__
                ):

            return self.size
        else:
            return self.controlValue[0]

class LDAP(pykolab.base.Base):
    """
        Abstraction layer for the LDAP authentication / authorization backend,
        for use with Kolab.
    """

    def __init__(self, domain=None):
        """
            Initialize the LDAP object for domain. If no domain is specified,
            domain name space configured as 'kolab'.'primary_domain' is used.
        """
        pykolab.base.Base.__init__(self)

        self.ldap = None
        self.bind = False
        if domain == None:
            self.domain = conf.get('kolab', 'primary_domain')
        else:
            self.domain = domain

    def authenticate(self, login, realm):
        """
            Find the entry corresponding to login, and attempt a bind.

            login is a tuple with 4 values. In order of appearance;

            [0] - the login username.

            [1] - the password

            [2] - the service (optional)

            [3] - the realm

            Called from pykolab.auth.Auth, the realm parameter is derived, while
            login[3] preserves the originally specified realm.
        """

        try:
            log.debug(
                    _("Attempting to authenticate user %s in realm %s") % (
                            login[0],
                            realm
                        ),
                    level=8
                )
        except:
            pass

        self.connect()
        self._bind()

        user_filter = self.config_get('user_filter')

        _filter = '(&(|'

        auth_attrs = self.config_get_list('auth_attributes')

        for attr in auth_attrs:
            _filter += "(%s=%s)" % (attr, login[0])
            _filter += "(%s=%s@%s)" % (attr, login[0], realm)

        _filter += ')%s)' % (user_filter)

        _search = self.ldap.search_ext(
                self.config_get('base_dn'),
                ldap.SCOPE_SUBTREE,
                _filter,
                ['entrydn']
            )

        (
                _result_type,
                _result_data,
                _result_msgid,
                _result_controls
            ) = self.ldap.result3(_search)

        if len(_result_data) >= 1:
            (entry_dn, entry_attrs) = _result_data[0]

        try:
            log.debug(_("Binding with user_dn %s and password %s")
                % (entry_dn, login[1]))

            # Needs to be synchronous or succeeds and continues setting retval
            # to True!!
            self.ldap.simple_bind_s(entry_dn, login[1])
            retval = True
        except:
            try:
                log.debug(
                        _("Failed to authenticate as user %s") % (login[0]),
                        level=8
                    )
            except:
                pass

            retval = False

        return retval

    def connect(self):
        """
            Connect to the LDAP server through the uri configured.
        """
        if not self.ldap == None:
            return

        log.debug(_("Connecting to LDAP..."), level=8)

        uri = self.config_get('ldap_uri')

        log.debug(_("Attempting to use LDAP URI %s") % (uri), level=8)

        trace_level = 0

        if conf.debuglevel > 8:
            trace_level = 1

        self.ldap = ldap.ldapobject.ReconnectLDAPObject(
                uri,
                trace_level=trace_level,
                retry_max=200,
                retry_delay=3.0
            )

        self.ldap.protocol_version = 3
        self.ldap.supported_controls = []

    def entry_dn(self, entry_id):
        """
            Get a entry's distinguished name for an entry ID.

            The entry ID may be any of:

            - an entry's value for the configured unique_attribute,
            - a (syntactically valid) Distinguished Name,
            - a dictionary such as previously returned as (part of) the result
              of a search.
        """
        entry_dn = None

        if self._entry_dn(entry_id):
            return entry_id

        if self._entry_dict(entry_id):
            return entry_id['dn']

        unique_attribute = self.config_get('unique_attribute')
        base_dn = self.config_get('base_dn')

        _search = self.ldap.search_ext(
                base_dn,
                ldap.SCOPE_SUBTREE,
                '(%s=%s)' % (unique_attribute, entry_id),
                ['entrydn']
            )

        (
                _result_type,
                _result_data,
                _result_msgid,
                _result_controls
            ) = self.ldap.result3(_search)

        if len(_result_data) >= 1:
            (entry_dn, entry_attrs) = _result_data[0]

        return entry_dn

    def get_entry_attribute(self, entry_id, attribute):
        """
            Get an attribute for an entry.

            Return the attribute value if successful, or None if not.
        """

        entry_attrs = self.get_entry_attributes(entry_id, [attribute])

        if entry_attrs.has_key(attribute):
            return entry_attrs[attribute]
        elif entry_attrs.has_key(attribute.lower()):
            return entry_attrs[attribute.lower()]
        else:
            return None

    def get_entry_attributes(self, entry_id, attributes):
        """
            Get multiple attributes for an entry.
        """

        self._bind()

        #print entry_id
        entry_dn = self.entry_dn(entry_id)
        #print entry_dn

        _search = self.ldap.search_ext(
                entry_dn,
                ldap.SCOPE_BASE,
                filterstr='(objectclass=*)',
                attrlist=[ 'dn' ] + attributes
            )

        (
                _result_type,
                _result_data,
                _result_msgid,
                _result_controls
            ) = self.ldap.result3(_search)

        if len(_result_data) >= 1:
            (_entry_dn, _entry_attrs) = _result_data[0]
        else:
            return None

        return utils.normalize(_entry_attrs)

    def find_recipient(self, address="*", exclude_entry_id=None):
        """
            Given an address string or list of addresses, find one or more valid
            recipients.

            Use this function only to detect whether an address is already in
            use by any entry in the tree.

            Specify an additional entry_id to exclude to exclude matches against
            the current entry.
        """

        self._bind()

        if not exclude_entry_id == None:
            __filter_prefix = "(&"
            __filter_suffix = "(!(%s=%s)))" % (
                    self.config_get('unique_attribute'),
                    exclude_entry_id
                )

        else:
            __filter_prefix = ""
            __filter_suffix = ""

        kolab_filter = self._kolab_filter()
        recipient_address_attrs = self.config_get_list("mail_attributes")
        result_attributes = recipient_address_attrs
        result_attributes.append(self.config_get('unique_attribute'))

        _filter = "(|"

        for recipient_address_attr in recipient_address_attrs:
            if isinstance(address, basestring):
                _filter += "(%s=%s)" % (recipient_address_attr, address)
            else:
                for _address in address:
                    _filter += "(%s=%s)" % (recipient_address_attr, _address)

        _filter += ")"

        _filter = "%s%s%s" % (__filter_prefix,_filter,__filter_suffix)


        log.debug(_("Finding recipient with filter %r") % (_filter), level=8)

        if len(_filter) <= 6:
            return None

        _results = self.ldap.search_s(
                self.config_get('base_dn'),
                scope=ldap.SCOPE_SUBTREE,
                filterstr=_filter,
                attrlist=result_attributes,
                attrsonly=True
            )

        _entry_dns = []

        for _result in _results:
            (_entry_id, _entry_attrs) = _result
            _entry_dns.append(_entry_id)

        return _entry_dns

    def find_resource(self, address="*", exclude_entry_id=None):
        """
            Given an address string or list of addresses, find one or more valid
            resources.

            Specify an additional entry_id to exclude to exclude matches.
        """

        self._bind()

        if not exclude_entry_id == None:
            __filter_prefix = "(&"
            __filter_suffix = "(!(%s=%s)))" % (
                    self.config_get('unique_attribute'),
                    exclude_entry_id
                )

        else:
            __filter_prefix = ""
            __filter_suffix = ""

        resource_filter = self.config_get('resource_filter')
        if not resource_filter == None:
            __filter_prefix = "(&%s" % resource_filter
            __filter_suffix = ")"

        resource_base_dn = self.config_get('resource_base_dn')

        recipient_address_attrs = self.config_get_list("mail_attributes")

        result_attributes = recipient_address_attrs
        result_attributes.append(self.config_get('unique_attribute'))

        _filter = "(|"

        for recipient_address_attr in recipient_address_attrs:
            if isinstance(address, basestring):
                _filter += "(%s=%s)" % (recipient_address_attr, address)
            else:
                for _address in address:
                    _filter += "(%s=%s)" % (recipient_address_attr, _address)

        _filter += ")"

        _filter = "%s%s%s" % (__filter_prefix,_filter,__filter_suffix)

        log.debug(_("Finding resource with filter %r") % (_filter), level=8)

        if len(_filter) <= 6:
            return None

        _results = self.ldap.search_s(
                resource_base_dn,
                scope=ldap.SCOPE_SUBTREE,
                filterstr=_filter,
                attrlist=result_attributes,
                attrsonly=True
            )

        _entry_dns = []

        for _result in _results:
            (_entry_id, _entry_attrs) = _result
            _entry_dns.append(_entry_id)

        return _entry_dns

    def get_latest_sync_timestamp(self):
        timestamp = cache.last_modify_timestamp(self.domain)
        log.debug(_("Using timestamp %r") % (timestamp), level=9)
        return timestamp

    def list_secondary_domains(self):
        """
            List alias domain name spaces for the current domain name space.
        """
        return [s for s, p in self.secondary_domains.iteritems() if p == self.domain]

    def recipient_policy(self, entry):
        """
            Apply a recipient policy, if configured.

            Given an entry, returns the entry's attribute values to be set.
        """
        entry_dn = self.entry_dn(entry)
        entry_modifications = {}
        entry_type = self._entry_type(entry)
        mail_attributes = self.config_get_list('mail_attributes')
        primary_mail = None
        primary_mail_attribute = None
        secondary_mail = None
        secondary_mail_attribute = None

        if len(mail_attributes) >= 1:
            primary_mail_attribute = mail_attributes[0]

        if len(mail_attributes) >= 2:
            secondary_mail_attribute = mail_attributes[1]

        want_attrs = []

        log.debug(_("Applying recipient policy to %r") % (entry_dn), level=8)

        # See which mail attributes we would want to control.
        #
        # 'mail' is considered for primary_mail,
        # 'alias' and 'mailalternateaddress' are considered for secondary mail.
        #
        primary_mail = self.config_get_raw('%s_primary_mail' % (entry_type))
        if primary_mail == None and entry_type == 'user':
            primary_mail = self.config_get_raw('primary_mail')

        if not secondary_mail_attribute == None:
            secondary_mail = self.config_get_raw('%s_secondary_mail' % (entry_type))
            if secondary_mail == None and entry_type == 'user':
                secondary_mail = self.config_get_raw('secondary_mail')

        log.debug(
                _("Using mail attributes: %r, with primary %r and " + \
                        "secondary %r") % (
                                mail_attributes,
                                primary_mail_attribute,
                                secondary_mail_attribute
                            ),
                level=8
            )

        for _mail_attr in mail_attributes:
            if not entry.has_key(_mail_attr):
                log.debug(_("key %r not in entry") % (_mail_attr), level=8)
                if _mail_attr == primary_mail_attribute:
                    log.debug(_("key %r is the prim. mail attr.") % (_mail_attr), level=8)
                    if not primary_mail == None:
                        log.debug(_("prim. mail pol. is not empty"), level=8)
                        want_attrs.append(_mail_attr)
                elif _mail_attr == secondary_mail_attribute:
                    log.debug(_("key %r is the sec. mail attr.") % (_mail_attr), level=8)
                    if not secondary_mail == None:
                        log.debug(_("sec. mail pol. is not empty"), level=8)
                        want_attrs.append(_mail_attr)

        if len(want_attrs) > 0:
            log.debug(_("Attributes %r are not yet available for entry %r") % (
                        want_attrs,
                        entry_dn
                    ),
                    level=8
                )

        # Also append the preferredlanguage or 'native tongue' configured
        # for the entry.
        if not entry.has_key('preferredlanguage'):
            want_attrs.append('preferredlanguage')

        # If we wanted anything, now is the time to get it.
        if len(want_attrs) > 0:
            log.debug(_("Attributes %r are not yet available for entry %r") % (
                        want_attrs,
                        entry_dn
                    ),
                    level=8
                )
            attributes = self.get_entry_attributes(entry_dn, want_attrs)

            for attribute in attributes.keys():
                entry[attribute] = attributes[attribute]

        if not entry.has_key('preferredlanguage'):
            entry['preferredlanguage'] = conf.get('kolab', 'default_locale')

        # Primary mail address
        if not primary_mail == None:
            primary_mail_address = conf.plugins.exec_hook(
                    "set_primary_mail",
                    kw={
                            'primary_mail': primary_mail,
                            'entry': entry,
                            'primary_domain': self.domain
                        }
                )

            i = 1
            _primary_mail = primary_mail_address

            done = False
            while not done:
                results = self.find_recipient(_primary_mail, entry['id'])

                # Length of results should be 0 (no entry found)
                # or 1 (which should be the entry we're looking at here)
                if len(results) == 0:
                    log.debug(
                            _("No results for mail address %s found") % (
                                    _primary_mail
                                ),
                            level=8
                        )

                    done = True
                    continue

                if len(results) == 1:
                    log.debug(
                            _("1 result for address %s found, verifying") % (
                                    _primary_mail
                                ),
                            level=8
                        )

                    almost_done = True
                    for result in results:
                        if not result == entry_dn:
                            log.debug(
                                    _("Too bad, primary email address %s " + \
                                    "already in use for %s (we are %s)") % (
                                            _primary_mail,
                                            result,
                                            entry_dn
                                        ),
                                    level=8
                                )

                            almost_done = False
                        else:
                            log.debug(_("Address assigned to us"), level=8)

                    if almost_done:
                        done = True
                        continue

                i += 1
                _primary_mail = "%s%d@%s" % (
                        primary_mail_address.split('@')[0],
                        i,
                        primary_mail_address.split('@')[1]
                    )

            primary_mail_address = _primary_mail

            ###
            ### FIXME
            ###
            if not primary_mail_address == None:
                if not entry.has_key(primary_mail_attribute):
                    self.set_entry_attribute(entry, primary_mail_attribute, primary_mail_address)
                    entry_modifications[primary_mail_attribute] = primary_mail_address
                else:
                    if not primary_mail_address == entry[primary_mail_attribute]:
                        self.set_entry_attribute(entry, primary_mail_attribute, primary_mail_address)

                        entry_modifications[primary_mail_attribute] = primary_mail_address

        if not secondary_mail == None:
            # Execute the plugin hook
            suggested_secondary_mail = conf.plugins.exec_hook(
                    "set_secondary_mail",
                    kw={
                            'secondary_mail': secondary_mail,
                            'entry': entry,
                            'domain': self.domain,
                            'primary_domain': self.domain,
                            'secondary_domains': self.list_secondary_domains()
                        }
                ) # end of conf.plugins.exec_hook() call

            secondary_mail_addresses = []

            for _secondary_mail in suggested_secondary_mail:
                i = 1
                __secondary_mail = _secondary_mail

                done = False
                while not done:
                    results = self.find_recipient(__secondary_mail, entry['id'])

                    # Length of results should be 0 (no entry found)
                    # or 1 (which should be the entry we're looking at here)
                    if len(results) == 0:
                        log.debug(
                                _("No results for address %s found") % (
                                        __secondary_mail
                                    ),
                                level=8
                            )

                        done = True
                        continue

                    if len(results) == 1:
                        log.debug(
                                _("1 result for address %s found, " + \
                                "verifying...") % (
                                        __secondary_mail
                                    ),
                                level=8
                            )

                        almost_done = True
                        for result in results:
                            if not result == entry_dn:
                                log.debug(
                                        _("Too bad, secondary email " + \
                                        "address %s already in use for " + \
                                        "%s (we are %s)") % (
                                                __secondary_mail,
                                                result,
                                                entry_dn
                                            ),
                                        level=8
                                    )

                                almost_done = False
                            else:
                                log.debug(_("Address assigned to us"), level=8)

                        if almost_done:
                            done = True
                            continue

                    i += 1
                    __secondary_mail = "%s%d@%s" % (
                            _secondary_mail.split('@')[0],
                            i,
                            _secondary_mail.split('@')[1]
                        )

                secondary_mail_addresses.append(__secondary_mail)

            log.debug(_("Recipient policy composed the following set of secondary " + \
                    "email addresses: %r") % (secondary_mail_addresses), level=8)

            if entry.has_key(secondary_mail_attribute):
                if isinstance(entry[secondary_mail_attribute], list):
                    secondary_mail_addresses.extend(entry[secondary_mail_attribute])
                else:
                    secondary_mail_addresses.append(entry[secondary_mail_attribute])

            if not secondary_mail_addresses == None:
                log.debug(
                        _("Secondary mail addresses that we want is not None: %r") % (
                                secondary_mail_addresses
                            ),
                        level=9
                    )

                secondary_mail_addresses = list(set(secondary_mail_addresses))

                # Avoid duplicates
                while primary_mail_address in secondary_mail_addresses:
                    log.debug(
                            _("Avoiding the duplication of the primary mail " + \
                                    "address %r in the list of secondary mail " + \
                                    "addresses") % (primary_mail_address),
                            level=9
                        )

                    secondary_mail_addresses.pop(
                            secondary_mail_addresses.index(primary_mail_address)
                        )

                log.debug(
                        _("Entry is getting secondary mail addresses: %r") % (
                                secondary_mail_addresses
                            ),
                        level=9
                    )

                if not entry.has_key(secondary_mail_attribute):
                    log.debug(
                            _("Entry did not have any secondary mail " + \
                                    "addresses in %r") % (secondary_mail_attribute),
                            level=9
                        )

                    if not len(secondary_mail_addresses) == 0:
                        self.set_entry_attribute(
                                entry,
                                secondary_mail_attribute,
                                secondary_mail_addresses
                            )

                        entry_modifications[secondary_mail_attribute] = secondary_mail_addresses
                else:
                    if isinstance(entry[secondary_mail_attribute], basestring):
                        entry[secondary_mail_attribute] = [entry[secondary_mail_attribute]]

                    log.debug(_("secondary_mail_addresses: %r") % (secondary_mail_addresses), level=8)
                    log.debug(_("entry[%s]: %r") % (secondary_mail_attribute,entry[secondary_mail_attribute]), level=8)

                    secondary_mail_addresses.sort()
                    entry[secondary_mail_attribute].sort()

                    log.debug(_("secondary_mail_addresses: %r") % (secondary_mail_addresses), level=8)
                    log.debug(_("entry[%s]: %r") % (secondary_mail_attribute,entry[secondary_mail_attribute]), level=8)

                    if not list(set(secondary_mail_addresses)) == list(set(entry[secondary_mail_attribute])):
                        self.set_entry_attribute(
                                entry,
                                secondary_mail_attribute,
                                list(set(secondary_mail_addresses))
                            )

                        entry_modifications[secondary_mail_attribute] = list(set(secondary_mail_addresses))

        log.debug(_("Entry modifications list: %r") % (entry_modifications), level=8)

        return entry_modifications

    def search_entry_by_attribute(self, attr, value, **kw):
        self._bind()

        _filter = "(%s=%s)" % (attr, value)

        return self._search(
                self.config_get('base_dn'),
                filterstr=_filter,
                attrlist=[
                        '*',
                    ],
                override_search='_regular_search'
            )


    def set_entry_attribute(self, entry_id, attribute, value):
        log.debug(_("Setting entry attribute %r to %r for %r") % (attribute, value, entry_id), level=9)
        self.set_entry_attributes(entry_id, { attribute: value })

    def set_entry_attributes(self, entry_id, attributes):
        self._bind()

        entry_dn = self.entry_dn(entry_id)

        entry = self.get_entry_attributes(entry_dn, ['*'])

        attrs = {}

        for attribute in attributes.keys():
            attrs[attribute.lower()] = attributes[attribute]

        modlist = []

        for attribute in attrs.keys():
            if not entry.has_key(attribute):
                entry[attribute] = self.get_entry_attribute(entry_id, attribute)

        for attribute in attrs.keys():
            if entry.has_key(attribute) and entry[attribute] == None:
                modlist.append((ldap.MOD_ADD, attribute, attrs[attribute]))
            elif entry.has_key(attribute) and not entry[attribute] == None:
                if attrs[attribute] == None:
                    modlist.append((ldap.MOD_DELETE, attribute, entry[attribute]))
                else:
                    modlist.append((ldap.MOD_REPLACE, attribute, attrs[attribute]))

        dn = entry_dn

        if len(modlist) > 0:
            try:
                self.ldap.modify_s(dn, modlist)
            except:
                log.error(_("Could not update dn %r:\n%r") % (dn, modlist))

    def synchronize(self, mode=0):
        """
            Synchronize with LDAP
        """
        self._bind()

        _filter = self._kolab_filter()

        modified_after = self.get_latest_sync_timestamp()
        _filter = "(&%s(modifytimestamp>=%s))" % (_filter,modified_after)

        log.debug(_("Using filter %r") % (_filter), level=8)

        if not mode == 0:
            override_search = mode
        else:
            override_search = False

        self._search(
                self.config_get('base_dn'),
                filterstr=_filter,
                attrlist=[
                        '*',
                        self.config_get('unique_attribute'),
                        conf.get('cyrus-sasl', 'result_attribute'),
                        'modifytimestamp'
                    ],
                override_search=override_search,
                callback=self._synchronize_callback,
            )

    def user_quota(self, entry_id, folder):
        default_quota = self.config_get('default_quota')
        quota_attribute = self.config_get('quota_attribute')

        if quota_attribute == None:
            return

        if default_quota == None:
            return

        self._bind()

        entry_dn = self.entry_dn(entry_id)

        current_ldap_quota = self.get_entry_attribute(entry_dn, quota_attribute)
        _imap_quota = self.imap.get_quota(folder)

        if _imap_quota == None:
            used = None
            current_imap_quota = None
        else:
            (used, current_imap_quota) = _imap_quota

        log.debug(
                _("About to consider the user quota for %r (used: %r, " + \
                    "imap: %r, ldap: %r, default: %r") % (
                        entry_dn,
                        used,
                        current_imap_quota,
                        current_ldap_quota,
                        default_quota
                    ),
                level=9
            )

        new_quota = conf.plugins.exec_hook("set_user_folder_quota", kw={
                    'used': used,
                    'imap_quota': current_imap_quota,
                    'ldap_quota': current_ldap_quota,
                    'default_quota': default_quota
                }
            )

        if not current_ldap_quota == None:
            if not new_quota == (int)(current_ldap_quota):
                self.set_entry_attribute(
                        entry_dn,
                        quota_attribute,
                        "%s" % (new_quota)
                    )
        else:
            if not new_quota == None:
                self.set_entry_attribute(
                        entry_dn,
                        quota_attribute,
                        "%s" % (new_quota)
                    )

        if not current_imap_quota == None:
            if not new_quota == current_imap_quota:
                self.imap.set_quota(folder, new_quota)

        else:
            if not new_quota == None:
                self.imap.set_quota(folder, new_quota)

    ###
    ### API depth level increasing!
    ###

    def _bind(self):
        if self.ldap == None:
            self.connect()

        if not self.bind:
            bind_dn = self.config_get('bind_dn')
            bind_pw = self.config_get('bind_pw')

            # TODO: Binding errors control
            try:
                self.ldap.simple_bind_s(bind_dn, bind_pw)
                self.bind = True
            except ldap.SERVER_DOWN:
                # Can't contact LDAP server
                #
                # - Service not started
                # - Service faulty
                # - Firewall
                pass
            except ldap.INVALID_CREDENTIALS:
                log.error(_("Invalid DN, username and/or password."))

    def _change_add_group(self, entry, change):
        """
            An entry of type group was added.

            The Kolab daemon has little to do for this type of action on this
            type of entry.
        """
        pass

    def _change_add_None(self, entry, change):
        """
            Redirect to _change_add_unknown
        """
        self._change_add_unknown(entry, change)

    def _change_add_resource(self, entry, change):
        """
            An entry of type resource was added.

            The Kolab daemon has little to do for this type of action on this
            type of entry.
        """
        pass

    def _change_add_role(self, entry, change):
        """
            An entry of type role was added.

            The Kolab daemon has little to do for this type of action on this
            type of entry.
        """
        pass

    def _change_add_sharedfolder(self, entry, change):
        """
            An entry of type sharedfolder was added.
        """
        self.imap.connect(domain=self.domain)

        server = None

        # Get some configuration values
        mailserver_attribute = self.config_get('mailserver_attribute')
        if entry.has_key(mailserver_attribute):
            server = entry[mailserver_attribute]

        foldertype_attribute = self.config_get('sharedfolder_type_attribute')
        if not foldertype_attribute == None:
            if not entry.has_key(foldertype_attribute):
                entry[foldertype_attribute] = self.get_user_attribute(
                        entry['id'],
                        foldertype_attribute
                    )

            if not entry[foldertype_attribute] == None:
                entry['kolabfoldertype'] = entry[foldertype_attribute]

        if not entry.has_key('kolabfoldertype'):
            entry['kolabfoldertype'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabfoldertype'
                )

        # A delivery address is postuser+targetfolder
        delivery_address_attribute = self.config_get('sharedfolder_delivery_address_attribute')
        if not delivery_address_attribute == None:
            if not entry.has_key(delivery_address_attribute):
                entry[delivery_address_attribute] = self.get_entry_attribute(
                        entry['id'],
                        delivery_address_attribute
                    )

            if not entry[delivery_address_attribute] == None:
                if len(entry[delivery_address_attribute].split('+')) > 1:
                    entry['kolabtargetfolder'] = entry[delivery_address_attribute].split('+')[1]

        if not entry.has_key('kolabtargetfolder'):
            entry['kolabtargetfolder'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabtargetfolder'
                )

        if entry.has_key('kolabtargetfolder') and \
                not entry['kolabtargetfolder'] == None:

            folder_path = entry['kolabtargetfolder']
        else:
            # TODO: What is *the* way to see if we need to create an @domain
            # shared mailbox?
            # TODO^2: self.domain, really? Presumes any mail attribute is
            # set to the primary domain name space...
            # TODO^3: Test if the cn is already something@domain
            result_attribute = conf.get('cyrus-sasl', 'result_attribute')
            if result_attribute in ['mail']:
                folder_path = "%s@%s" % (entry['cn'], self.domain)
            else:
                folder_path = entry['cn']

        folderacl_entry_attribute = self.config_get('sharedfolder_acl_entry_attribute')

        if not folderacl_entry_attribute == None:
            if not entry.has_key(folderacl_entry_attribute):
                entry[folderacl_entry_attribute] = self.get_entry_attribute(
                        entry['id'],
                        folderacl_entry_attribute
                    )

            if not entry[folderacl_entry_attribute] == None:
                # Parse it before assigning it
                entry['kolabmailfolderaclentry'] = []
                if not isinstance(entry[folderacl_entry_attribute], list):
                    entry[folderacl_entry_attribute] = [ entry[folderacl_entry_attribute] ]

                for acl_entry in entry[folderacl_entry_attribute]:
                    acl_access = acl_entry.split()[-1]
                    aci_subject = ' '.join(acl_entry.split()[:-1])

                    log.debug(_("Found a subject %r with access %r") % (aci_subject, acl_access), level=8)

                    access_lookup_dict = {
                            'read': 'lrs',
                            'post': 'p',
                            'append': 'wip',
                            'write': 'lrswite',
                            'all': 'lrsedntxakcpiw'
                        }

                    if access_lookup_dict.has_key(acl_access):
                        acl_access = access_lookup_dict[acl_access]

                    log.debug(_("Found a subject %r with access %r") % (aci_subject, acl_access), level=8)

                    entry['kolabmailfolderaclentry'].append("(%r, %r, %r)" % (folder_path, aci_subject, acl_access))

        if not entry.has_key('kolabmailfolderaclentry'):
            entry['kolabmailfolderaclentry'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabmailfolderaclentry'
                )

        if not self.imap.shared_folder_exists(folder_path):
            self.imap.shared_folder_create(folder_path, server)

        if entry.has_key('kolabfoldertype') and \
                not entry['kolabfoldertype'] == None:

            self.imap.shared_folder_set_type(
                    folder_path,
                    entry['kolabfoldertype']
                )

        if entry.has_key(delivery_address_attribute) and \
                not entry[delivery_address_attribute] == None:
            self.imap.set_acl(folder_path, 'anyone', 'p')

        if entry.has_key('kolabmailfolderaclentry') and \
                not entry['kolabmailfolderaclentry'] == None:

            self.imap._set_kolab_mailfolder_acls(
                    entry['kolabmailfolderaclentry']
                )

        #if server == None:
            #self.entry_set_attribute(mailserver_attribute, server)

    def _change_add_unknown(self, entry, change):
        """
            An entry has been add, and we do not know of what object type
            the entry was - user, group, role or sharedfolder.
        """
        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        if not entry.has_key(result_attribute):
            return None

        if entry[result_attribute] == None:
            return None

        for _type in ['user','group','role','sharedfolder']:
            try:
                eval("self._change_add_%s(entry, change)" % (_type))
                success = True
            except:
                success = False

            if success:
                break

    def _change_add_user(self, entry, change):
        """
            An entry of type user was added.
        """
        mailserver_attribute = self.config_get('mailserver_attribute')
        if mailserver_attribute == None:
            mailserver_attribute = 'mailhost'

        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        if not entry.has_key(mailserver_attribute):
            entry[mailserver_attribute] = \
                self.get_entry_attribute(entry, mailserver_attribute)

        rcpt_addrs = self.recipient_policy(entry)
        for key in rcpt_addrs:
            entry[key] = rcpt_addrs[key]

        if not entry.has_key(result_attribute):
            return

        if entry[result_attribute] == None:
            return

        cache.get_entry(self.domain, entry)

        self.imap.connect(domain=self.domain)

        if not self.imap.user_mailbox_exists(entry[result_attribute]):
            folder = self.imap.user_mailbox_create(
                    entry[result_attribute],
                    entry[mailserver_attribute]
                )

        else:
            folder = "user%s%s" % (self.imap.separator,entry[result_attribute])

        server = self.imap.user_mailbox_server(folder)

        if not entry[mailserver_attribute] == server:
            self.set_entry_attribute(entry, mailserver_attribute, server)

        self.user_quota(entry, folder)

    def _change_delete_group(self, entry, change):
        """
            An entry of type group was deleted.
        """

        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        if not entry.has_key(result_attribute):
            return None

        if entry[result_attribute] == None:
            return None

        self.imap.cleanup_acls(entry[result_attribute])


    def _change_delete_None(self, entry, change):
        """
            Redirect to _change_delete_unknown
        """
        self._change_delete_unknown(entry, change)

    def _change_delete_sharedfolder(self, entry, change):
        pass

    def _change_delete_unknown(self, entry, change):
        """
            An entry has been deleted, and we do not know of what object type
            the entry was - user, group, role or sharedfolder.
        """
        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        if not entry.has_key(result_attribute):
            return None

        if entry[result_attribute] == None:
            return None

        success = True
        for _type in ['user','group','role','sharedfolder']:
            try:
                eval("self._change_delete_%s(entry, change)" % (_type))
            except:
                success = False

            if success:
                break

    def _change_delete_user(self, entry, change):
        """
            An entry of type user was deleted.
        """
        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        if not entry.has_key(result_attribute):
            return None

        if entry[result_attribute] == None:
            return None

        cache.delete_entry(self.domain, entry)

        self.imap.user_mailbox_delete(entry[result_attribute])
        self.imap.cleanup_acls(entry[result_attribute])

    def _change_moddn_group(self, entry, change):
        # TODO: If the rdn attribute is the same as the result attribute...
        pass

    def _change_moddn_role(self, entry, change):
        pass

    def _change_moddn_user(self, entry, change):
        old_dn = change['previous_dn']
        new_dn = change['dn']

        import ldap.dn
        old_rdn = ldap.dn.explode_dn(old_dn)[0].split('=')[0]
        new_rdn = ldap.dn.explode_dn(new_dn)[0].split('=')[0]

        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        old_canon_attr = None

        cache_entry = cache.get_entry(self.domain, entry)
        if not cache_entry == None:
            old_canon_attr = cache_entry.result_attribute

        # See if we have to trigger the recipient policy. Only really applies to
        # situations in which the result_attribute is used in the old or in the
        # new DN.
        trigger_recipient_policy = False

        if old_rdn == result_attribute:
            if new_rdn == result_attribute:
                if new_rdn == old_rdn:
                    trigger_recipient_policy = True
            else:
                if not new_rdn == old_rdn:
                    trigger_recipient_policy = True
        else:
            if new_rdn == result_attribute:
                if not new_rdn == old_rdn:
                    trigger_recipient_policy = True

        if trigger_recipient_policy:
            entry_changes = self.recipient_policy(entry)

            for key in entry_changes.keys():
                entry[key] = entry_changes[key]

            # Now look at entry_changes and old_canon_attr, and see if they're
            # the same value.
            if entry_changes.has_key(result_attribute):
                if not old_canon_attr == None:
                    self.imap.user_mailbox_create(
                            entry_changes[result_attribute]
                        )

                elif not entry_changes[result_attribute] == old_canon_attr:
                    self.imap.user_mailbox_rename(
                            old_canon_attr,
                            entry_changes[result_attribute]
                        )

        cache.get_entry(self.domain, entry)

    def _change_moddn_sharedfolder(self, entry, change):
        pass

    def _change_modify_group(self, entry, change):
        pass

    def _change_modify_role(self, entry, change):
        pass

    def _change_modify_sharedfolder(self, entry, change):
        """
            A shared folder was modified.
        """
        self.imap.connect(domain=self.domain)

        server = None

        # Get some configuration values
        mailserver_attribute = self.config_get('mailserver_attribute')
        if entry.has_key(mailserver_attribute):
            server = entry[mailserver_attribute]

        foldertype_attribute = self.config_get('sharedfolder_type_attribute')
        if not foldertype_attribute == None:
            if not entry.has_key(foldertype_attribute):
                entry[foldertype_attribute] = self.get_user_attribute(
                        entry['id'],
                        foldertype_attribute
                    )

            if not entry[foldertype_attribute] == None:
                entry['kolabfoldertype'] = entry[foldertype_attribute]

        if not entry.has_key('kolabfoldertype'):
            entry['kolabfoldertype'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabfoldertype'
                )

        # A delivery address is postuser+targetfolder
        delivery_address_attribute = self.config_get('sharedfolder_delivery_address_attribute')
        if not delivery_address_attribute == None:
            if not entry.has_key(delivery_address_attribute):
                entry[delivery_address_attribute] = self.get_entry_attribute(
                        entry['id'],
                        delivery_address_attribute
                    )

            if not entry[delivery_address_attribute] == None:
                if len(entry[delivery_address_attribute].split('+')) > 1:
                    entry['kolabtargetfolder'] = entry[delivery_address_attribute].split('+')[1]

        if not entry.has_key('kolabtargetfolder'):
            entry['kolabtargetfolder'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabtargetfolder'
                )

        if entry.has_key('kolabtargetfolder') and \
                not entry['kolabtargetfolder'] == None:

            folder_path = entry['kolabtargetfolder']
        else:
            # TODO: What is *the* way to see if we need to create an @domain
            # shared mailbox?
            # TODO^2: self.domain, really? Presumes any mail attribute is
            # set to the primary domain name space...
            # TODO^3: Test if the cn is already something@domain
            result_attribute = conf.get('cyrus-sasl', 'result_attribute')
            if result_attribute in ['mail']:
                folder_path = "%s@%s" % (entry['cn'], self.domain)
            else:
                folder_path = entry['cn']

        folderacl_entry_attribute = self.config_get('sharedfolder_acl_entry_attribute')

        if not folderacl_entry_attribute == None:
            if not entry.has_key(folderacl_entry_attribute):
                entry[folderacl_entry_attribute] = self.get_entry_attribute(
                        entry['id'],
                        folderacl_entry_attribute
                    )

            if not entry[folderacl_entry_attribute] == None:
                # Parse it before assigning it
                entry['kolabmailfolderaclentry'] = []
                if not isinstance(entry[folderacl_entry_attribute], list):
                    entry[folderacl_entry_attribute] = [ entry[folderacl_entry_attribute] ]

                for acl_entry in entry[folderacl_entry_attribute]:
                    acl_access = acl_entry.split()[-1]
                    aci_subject = ' '.join(acl_entry.split()[:-1])

                    log.debug(_("Found a subject %r with access %r") % (aci_subject, acl_access), level=8)

                    access_lookup_dict = {
                            'read': 'lrs',
                            'post': 'p',
                            'append': 'wip',
                            'write': 'lrswite',
                            'all': 'lrsedntxakcpiw'
                        }

                    if access_lookup_dict.has_key(acl_access):
                        acl_access = access_lookup_dict[acl_access]

                    log.debug(_("Found a subject %r with access %r") % (aci_subject, acl_access), level=8)

                    entry['kolabmailfolderaclentry'].append("(%r, %r, %r)" % (folder_path, aci_subject, acl_access))

        if not entry.has_key('kolabmailfolderaclentry'):
            entry['kolabmailfolderaclentry'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabmailfolderaclentry'
                )

        if not self.imap.shared_folder_exists(folder_path):
            self.imap.shared_folder_create(folder_path, server)

        if entry.has_key('kolabfoldertype') and \
                not entry['kolabfoldertype'] == None:

            self.imap.shared_folder_set_type(
                    folder_path,
                    entry['kolabfoldertype']
                )

        if entry.has_key(delivery_address_attribute) and \
                not entry[delivery_address_attribute] == None:
            self.imap.set_acl(folder_path, 'anyone', 'p')

        if entry.has_key('kolabmailfolderaclentry') and \
                not entry['kolabmailfolderaclentry'] == None:

            self.imap._set_kolab_mailfolder_acls(
                    entry['kolabmailfolderaclentry']
                )

        #if server == None:
            #self.entry_set_attribute(mailserver_attribute, server)

    def _change_modify_user(self, entry, change):
        """
            Handle the changes for an object of type user.

            Expects the new entry.
        """

        # Initialize old_canon_attr (#1701)
        old_canon_attr = None

        result_attribute = conf.get('cyrus-sasl','result_attribute')

        _entry = cache.get_entry(self.domain, entry, update=False)

        # We do not necessarily have a synchronisation cache entry (#1701)
        if not _entry == None:
            if _entry.__dict__.has_key('result_attribute') and not _entry.result_attribute == '':
                old_canon_attr = _entry.result_attribute

        entry_changes = self.recipient_policy(entry)

        log.debug(
                _("Result from recipient policy: %r") % (entry_changes),
                level=8
            )

        if entry_changes.has_key(result_attribute):
            if not entry_changes[result_attribute] == old_canon_attr:
                self.imap.user_mailbox_rename(
                        old_canon_attr,
                        entry_changes[result_attribute]
                    )

                entry[result_attribute] = entry_changes[result_attribute]
                cache.get_entry(self.domain, entry)
        elif entry.has_key(result_attribute):
            if not entry[result_attribute] == old_canon_attr:
                self.imap.user_mailbox_rename(
                        old_canon_attr,
                        entry[result_attribute]
                    )

                cache.get_entry(self.domain, entry)

        self.user_quota(entry, "user%s%s" % (self.imap.get_separator(),entry[result_attribute]))

        if conf.has_option(self.domain, 'sieve_mgmt'):
            sieve_mgmt_enabled = conf.get(self.domain, 'sieve_mgmt')
            if utils.true_or_false(sieve_mgmt_enabled):
                conf.plugins.exec_hook(
                        'sieve_mgmt_refresh',
                        kw={
                                'user': entry[result_attribute]
                            }
                    )

    def _change_none_group(self, entry, change):
        """
            A group entry as part of the initial search result set.

            The Kolab daemon has little to do for this type of action on this
            type of entry.
        """
        pass

    def _change_none_None(self, entry, change):
        pass

    def _change_none_role(self, entry, change):
        """
            A role entry as part of the initial search result set.

            The Kolab daemon has little to do for this type of action on this
            type of entry.
        """
        pass

    def _change_none_sharedfolder(self, entry, change):
        """
            A sharedfolder entry as part of the initial search result set.
        """
        self.imap.connect(domain=self.domain)

        server = None
        mailserver_attribute = self.config_get('mailserver_attribute')

        if entry.has_key(mailserver_attribute):
            server = entry['mailserver_attribute']

        if not entry.has_key('kolabtargetfolder'):
            entry['kolabtargetfolder'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabtargetfolder'
                )

        if not entry.has_key('kolabfoldertype'):
            entry['kolabfoldertype'] = self.get_entry_attribute(
                    entry['id'],
                    'kolabfoldertype'
                )

        #if not entry.has_key('kolabmailfolderaclentry'):
            #entry['kolabmailfolderaclentry'] = self.get_entry_attribute(
                    #entry['id'],
                    #'kolabmailfolderaclentry'
                #)

        if entry.has_key('kolabtargetfolder') and \
                not entry['kolabtargetfolder'] == None:

            folder_path = entry['kolabtargetfolder']
        else:
            # TODO: What is *the* way to see if we need to create an @domain
            # shared mailbox?
            # TODO^2: self.domain, really? Presumes any mail attribute is
            # set to the primary domain name space...
            # TODO^3: Test if the cn is already something@domain
            result_attribute = conf.get('cyrus-sasl', 'result_attribute')
            if result_attribute in ['mail']:
                folder_path = "%s@%s" % (entry['cn'], self.domain)
            else:
                folder_path = entry['cn']

        if not self.imap.shared_folder_exists(folder_path):
            self.imap.shared_folder_create(folder_path, server)

        if entry.has_key('kolabfoldertype') and \
                not entry['kolabfoldertype'] == None:

            self.imap.shared_folder_set_type(
                    folder_path,
                    entry['kolabfoldertype']
                )

        #if entry.has_key('kolabmailfolderaclentry') and \
                #not entry['kolabmailfolderaclentry'] == None:

            #self.imap._set_kolab_mailfolder_acls(
                    #entry['kolabmailfolderaclentry']
                #)

        #if server == None:
            #self.entry_set_attribute(mailserver_attribute, server)

    def _change_none_user(self, entry, change):
        """
            A user entry as part of the initial search result set.
        """
        result_attribute = conf.get('cyrus-sasl', 'result_attribute')

        old_canon_attr = None

        _entry = cache.get_entry(self.domain, entry, update=False)

        if not _entry == None and _entry.__dict__.has_key('result_attribute') and not _entry.result_attribute == '':
            old_canon_attr = _entry.result_attribute

        entry_changes = self.recipient_policy(entry)

        if entry.has_key(result_attribute) and entry_changes.has_key(result_attribute):
            if not entry[result_attribute] == entry_changes[result_attribute]:
                old_canon_attr = entry[result_attribute]

        log.debug(
                _("Result from recipient policy: %r") % (entry_changes),
                level=8
            )

        if entry_changes.has_key(result_attribute) and not old_canon_attr == None:
            if not entry_changes[result_attribute] == old_canon_attr:
                self.imap.user_mailbox_rename(
                        old_canon_attr,
                        entry_changes[result_attribute]
                    )

        for key in entry_changes.keys():
            entry[key] = entry_changes[key]
            self.set_entry_attribute(entry, key, entry[key])

        cache.get_entry(self.domain, entry)

        self.imap.connect(domain=self.domain)

        if entry.has_key(result_attribute) and \
                not entry.has_key(result_attribute) == None:

            if not self.imap.user_mailbox_exists(entry[result_attribute]):
                folder = self.imap.user_mailbox_create(entry[result_attribute])
                server = self.imap.user_mailbox_server(folder)
            else:
                folder = "user%s%s" % (
                        self.imap.separator,
                        entry[result_attribute]
                    )

                server = self.imap.user_mailbox_server(folder)

            self.user_quota(entry, folder)

            mailserver_attr = self.config_get('mailserver_attribute')
            if not entry.has_key(mailserver_attr):
                self.set_entry_attribute(entry, mailserver_attr, server)
            else:
                if not entry[mailserver_attr] == server:
                    # TODO: Should actually transfer mailbox
                    self.set_entry_attribute(entry, mailserver_attr, server)

        else:
            log.warning(
                    _("Kolab user %s does not have a result attribute %r") % (
                            entry['id'],
                            result_attribute
                        )
                )

    def _disconnect(self):
        self._unbind()
        del self.ldap
        self.ldap = None
        self.bind = False

    def _entry_dict(self, value):
        """
            Tests if 'value' is a valid entry dictionary with a DN contained
            within key 'dn'.

            Returns True or False
        """
        if isinstance(value, dict):
            if value.has_key('dn'):
                return True

        return False

    def _entry_dn(self, value):
        """
            Tests if 'value' is a valid DN.

            Returns True or False
        """

        # Only basestrings can be DNs
        if not isinstance(value, basestring):
            return False

        try:
            import ldap.dn
            ldap_dn = ldap.dn.explode_dn(value)
        except ldap.DECODING_ERROR:
            # This is not a DN.
            return False

        return True

    def _entry_type(self, entry_id):
        """
            Return the type of object for an entry.
        """
        self._bind()

        entry_dn = self.entry_dn(entry_id)

        base_dn = self.config_get('base_dn')

        for _type in ['user', 'group', 'sharedfolder']:
            __filter = self.config_get('kolab_%s_filter' % (_type))
            if __filter == None:
                __filter = self.config_get('%s_filter' % (_type))

            if not __filter == None:
                try:
                    result = self._regular_search(entry_dn, filterstr=__filter)
                except:
                    result = self._regular_search(
                            base_dn,
                            filterstr="(%s=%s)" %(
                                    self.config_get('unique_attribute'),
                                    entry_id['id'])
                                )

                if not result:
                    continue
                else:
                    return _type

    def _find_user_dn(self, login, realm):
        """
            Find the distinguished name (DN) for an entry in LDAP.
        """

        domain_root_dn = self._kolab_domain_root_dn(self.domain)

        base_dn = self.config_get('user_base_dn')
        if base_dn == None:
            base_dn = self.config_get('base_dn')

        auth_attrs = self.config_get_list('auth_attributes')

        auth_search_filter = [ '(|' ]

        for auth_attr in auth_attrs:
            auth_search_filter.append('(%s=%s)' % (auth_attr,login))
            auth_search_filter.append(
                    '(%s=%s@%s)' % (
                            auth_attr,
                            login,
                            self.domain
                        )
                )

        auth_search_filter.append(')')

        auth_search_filter = ''.join(auth_search_filter)

        search_filter = "(&%s%s)" % (
                auth_search_filter,
                user_filter
            )

        _results = self._search(
                user_base_dn,
                filterstr=search_filter,
                attrlist=[ 'dn' ],
                override_search='_regular_search'
            )

        if len(_results) == 1:
            (_user_dn, _user_attrs) = _results[0]
        else:
            # Retry to find the user_dn with just uid=%s against the root_dn,
            # if the login is not fully qualified
            if len(login.split('@')) < 2:
                search_filter = "(uid=%s)" % (login)
                _results = self._search(
                        domain,
                        filterstr=search_filter,
                        attrlist=[ 'dn' ]
                    )

                if len(_results) == 1:
                    (_user_dn, _user_attrs) = _results[0]
                else:
                    # Overall fail
                    return False
            else:
                return False

        return _user_dn

    def _kolab_domain_root_dn(self, domain):
        self._bind()

        log.debug(_("Finding domain root dn for domain %s") % (domain), level=8)

        bind_dn = conf.get('ldap', 'bind_dn')
        bind_pw = conf.get('ldap', 'bind_pw')

        domain_base_dn = conf.get('ldap', 'domain_base_dn', quiet=True)

        if not domain_base_dn == "":

            # If we haven't returned already, let's continue searching
            domain_name_attribute = conf.get('ldap', 'domain_name_attribute')

            _results = self._search(
                    domain_base_dn,
                    ldap.SCOPE_SUBTREE,
                    "(%s=%s)" % (domain_name_attribute,domain),
                    override_search='_regular_search'
                )

            domains = []
            for _domain in _results:
                (domain_dn, _domain_attrs) = _domain
                domain_rootdn_attribute = conf.get(
                        'ldap',
                        'domain_rootdn_attribute'
                    )
                _domain_attrs = utils.normalize(_domain_attrs)
                if _domain_attrs.has_key(domain_rootdn_attribute):
                    return _domain_attrs[domain_rootdn_attribute]

        else:
            if conf.has_option('ldap', 'base_dn'):
                return conf.get('ldap', 'base_dn')

        return utils.standard_root_dn(domain)

    def _kolab_filter(self):
        """
            Compose a filter using the relevant settings from configuration.
        """
        _filter = "(|"
        for _type in ['user', 'group', 'resource', 'sharedfolder']:
            __filter = self.config_get('kolab_%s_filter' % (_type))
            if __filter == None:
                __filter = self.config_get('%s_filter' % (_type))

            if not __filter == None:
                _filter = "%s%s" % (_filter,__filter)

        _filter = "%s)" % (_filter)

        return _filter

    def _list_domains(self):
        """
            Find the domains related to this Kolab setup, and return a list of
            DNS domain names.

            Returns a list of tuples, each tuple containing the primary domain
            name and a list of secondary domain names.

            This function should only be called by the primary instance of Auth.
        """

        log.debug(_("Listing domains..."), level=8)

        self.connect()

        bind_dn = conf.get('ldap', 'bind_dn')
        bind_pw = conf.get('ldap', 'bind_pw')

        domain_base_dn = conf.get('ldap', 'domain_base_dn', quiet=True)

        if domain_base_dn == "":
            # No domains are to be found in LDAP, return an empty list.
            # Note that the Auth() base itself handles this case.
            return []

        # If we haven't returned already, let's continue searching
        domain_filter = conf.get('ldap', 'domain_filter')

        if domain_base_dn == None or domain_filter == None:
            return []

        # TODO: this function should be wrapped for error handling
        try:
            self.ldap.simple_bind_s(bind_dn, bind_pw)
        except ldap.SERVER_DOWN, e:
            raise AuthBackendError, _("Authentication database DOWN")

        dna = self.config_get('domain_name_attribute')
        if dna == None:
            dna = 'associateddomain'

        try:
            _search = self._search(
                    domain_base_dn,
                    ldap.SCOPE_SUBTREE,
                    domain_filter,
                    # TODO: Where we use associateddomain is actually
                    # configurable
                    [ dna ],
                    override_search='_regular_search'
                )
        except:
            return []

        domains = []

        for domain_dn, domain_attrs in _search:
            primary_domain = None
            secondary_domains = []

            domain_attrs = utils.normalize(domain_attrs)

            # TODO: Where we use associateddomain is actually configurable
            if type(domain_attrs[dna]) == list:
                primary_domain = domain_attrs[dna].pop(0)
                secondary_domains = domain_attrs[dna]
            else:
                primary_domain = domain_attrs[dna]

            domains.append((primary_domain,secondary_domains))

        return domains

    def _reconnect(self):
        """
            Reconnect to LDAP
        """
        self._disconnect()
        self.connect()

    def _synchronize_callback(self, *args, **kw):
        """
           Determine the characteristics of the callback being placed, and
           what data is contained within *args and **kw exactly.

           The exact form and shape of the feedback very much depends on the
           supportedControl used to even get the data.
        """

        log.debug(
                "auth.ldap.LDAP._synchronize_callback(args %r, kw %r)" % (
                        args,
                        kw
                    ),
                level=9
            )

        # Typical for Persistent Change Control EntryChangeNotification
        if kw.has_key('change_type'):
            change_type = None

            change_dict = {
                    'change_type': kw['change_type'],
                    'previous_dn': kw['previous_dn'],
                    'change_number': kw['change_number'],
                    'dn': kw['dn']
                }

            entry = utils.normalize(kw['entry'])
            entry['dn'] = kw['dn']

            unique_attr = self.config_get('unique_attribute')
            entry['id'] = entry[unique_attr]

            try:
                entry['type'] = self._entry_type(entry)
            except:
                entry['type'] = "unknown"

            log.debug(_("Entry type: %s") % (entry['type']), level=8)

            if change_dict['change_type'] == None:
                # This entry was in the start result set
                eval("self._change_none_%s(entry, change_dict)" % (entry['type']))
            else:
                if isinstance(change_dict['change_type'], int):
                    change = psearch.CHANGE_TYPES_STR[change_dict['change_type']]
                    change = change.lower()
                else:
                    change = change_dict['change_type']

                eval(
                        "self._change_%s_%s(entry, change_dict)" % (
                                change,
                                entry['type']
                            )
                    )

        # Typical for Paged Results Control
        elif kw.has_key('entry') and isinstance(kw['entry'], list):
            for entry_dn,entry_attrs in kw['entry']:
                entry = { 'dn': entry_dn }
                entry_attrs = utils.normalize(entry_attrs)
                for attr in entry_attrs.keys():
                    entry[attr.lower()] = entry_attrs[attr]

                unique_attr = self.config_get('unique_attribute')
                entry['id'] = entry[unique_attr]

                try:
                    entry['type'] = self._entry_type(entry)
                except:
                    entry['type'] = "unknown"

                log.debug(_("Entry type: %s") % (entry['type']), level=8)

                eval("self._change_none_%s(entry, None)" % (entry['type']))

#                result_attribute = conf.get('cyrus-sasl', 'result_attribute')
#
#                rcpt_addrs = self.recipient_policy(entry)
#
#                log.debug(_("Recipient Addresses: %r") % (rcpt_addrs), level=9)
#
#                for key in rcpt_addrs.keys():
#                    entry[key] = rcpt_addrs[key]
#
#                cache.get_entry(self.domain, entry)
#
#                self.imap.connect(domain=self.domain)
#
#                if not self.imap.user_mailbox_exists(entry[result_attribute]):
#                    folder = self.imap.user_mailbox_create(
#                            entry[result_attribute]
#                        )
#
#                    server = self.imap.user_mailbox_server(folder)

    def _unbind(self):
        """
            Discard the current set of bind credentials.

            Virtually disconnects the LDAP connection, and should be followed by
            a call to _bind() afterwards.
        """

        self.ldap.unbind()
        self.bind = False

    ###
    ### Backend search functions
    ###

    def _persistent_search(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):

        _results = []

        psearch_server_controls = []

        psearch_server_controls.append(psearch.PersistentSearchControl(
                    criticality=True,
                    changeTypes=[ 'add', 'delete', 'modify', 'modDN' ],
                    changesOnly=False,
                    returnECs=True
                )
            )

        _search = self.ldap.search_ext(
                base_dn,
                scope=scope,
                filterstr=filterstr,
                attrlist=attrlist,
                attrsonly=attrsonly,
                timeout=timeout,
                serverctrls=psearch_server_controls
            )

        ecnc = psearch.EntryChangeNotificationControl

        while True:
            res_type,res_data,res_msgid,_None,_None,_None = self.ldap.result4(
                    _search,
                    all=0,
                    add_ctrls=1,
                    add_intermediates=1,
                    resp_ctrl_classes={ecnc.controlType:ecnc}
                )

            change_type = None
            previous_dn = None
            change_number = None

            for dn,entry,srv_ctrls in res_data:
                log.debug(_("LDAP Search Result Data Entry:"), level=8)
                log.debug("    DN: %r" % (dn), level=8)
                log.debug("    Entry: %r" % (entry), level=8)

                ecn_ctrls = [
                        c for c in srv_ctrls
                        if c.controlType == ecnc.controlType
                    ]

                if ecn_ctrls:
                    change_type = ecn_ctrls[0].changeType
                    previous_dn = ecn_ctrls[0].previousDN
                    change_number = ecn_ctrls[0].changeNumber
                    change_type_desc = psearch.CHANGE_TYPES_STR[change_type]

                    log.debug(
                            _("Entry Change Notification attributes:"),
                            level=8
                        )

                    log.debug(
                            "    " + _("Change Type: %r (%r)") % (
                                    change_type,
                                    change_type_desc
                                ),
                            level=8
                        )

                    log.debug(
                            "    " + _("Previous DN: %r") % (previous_dn),
                            level=8
                        )

                if callback:
                    callback(
                            dn=dn,
                            entry=entry,
                            previous_dn=previous_dn,
                            change_type=change_type,
                            change_number=change_number,
                            primary_domain=primary_domain,
                            secondary_domains=secondary_domains
                        )

    def _paged_search(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):

        page_size = 500
        critical = True
        _results = []

        server_page_control = SimplePagedResultsControl(page_size=page_size)

        _search = self.ldap.search_ext(
                base_dn,
                scope=scope,
                filterstr=filterstr,
                attrlist=attrlist,
                attrsonly=attrsonly,
                serverctrls=[server_page_control]
            )

        pages = 0
        while True:
            pages += 1
            try:
                (
                        _result_type,
                        _result_data,
                        _result_msgid,
                        _result_controls
                    ) = self.ldap.result3(_search)

            except ldap.NO_SUCH_OBJECT, e:
                log.warning(
                        _("Object %s searched no longer exists") % (base_dn)
                    )

                break

            if callback:
                callback(entry=_result_data)

            _results.extend(_result_data)
            if (pages % 2) == 0:
                log.debug(_("%d results...") % (len(_results)))

            pctrls = [
                    c for c in _result_controls
                        if c.controlType == LDAP_CONTROL_PAGED_RESULTS
                ]

            if pctrls:
                if hasattr(pctrls[0], 'size'):
                    size = pctrls[0].size
                    cookie = pctrls[0].cookie
                else:
                    size, cookie = pctrls[0].controlValue

                if cookie:
                    server_page_control.cookie = cookie
                    _search = self.ldap.search_ext(
                            base_dn,
                            scope=scope,
                            filterstr=filterstr,
                            attrlist=attrlist,
                            attrsonly=attrsonly,
                            serverctrls=[server_page_control]
                        )
                else:
                    # TODO: Error out more verbose
                    break
            else:
                # TODO: Error out more verbose
                print "Warning:  Server ignores RFC 2696 control."
                break

        return _results

    def _vlv_search(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):
        pass

    def _sync_repl(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):

        import ldapurl
        import syncrepl

        ldap_url = ldapurl.LDAPUrl(self.config_get('ldap_uri'))

        ldap_sync_conn = syncrepl.DNSync(
                '/var/lib/kolab/syncrepl_%s.db' % (self.domain),
                ldap_url.initializeUrl(),
                trace_level=2,
                callback=self._synchronize_callback
            )

        bind_dn = self.config_get('bind_dn')
        bind_pw = self.config_get('bind_pw')

        ldap_sync_conn.simple_bind_s(bind_dn, bind_pw)

        msgid = ldap_sync_conn.syncrepl_search(
                base_dn,
                scope,
                mode='refreshAndPersist',
                filterstr=filterstr,
                attrlist=attrlist,
            )

        try:
            # Here's where returns need to be taken into account...
            while ldap_sync_conn.syncrepl_poll(all=1, msgid=msgid):
                pass
        except KeyboardInterrupt:
            pass

    def _regular_search(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):

        log.debug(_("Searching with filter %r") % (filterstr), level=8)

        _search = self.ldap.search(
                base_dn,
                scope=scope,
                filterstr=filterstr,
                attrlist=attrlist,
                attrsonly=attrsonly
            )

        _results = []
        _result_type = None

        while not _result_type == ldap.RES_SEARCH_RESULT:
            (_result_type, _result) = self.ldap.result(_search, False, 0)

            if not _result == None:
                for result in _result:
                    _results.append(result)

        return _results

    def _search(self,
            base_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr="(objectClass=*)",
            attrlist=None,
            attrsonly=0,
            timeout=-1,
            override_search=False,
            callback=False,
            primary_domain=None,
            secondary_domains=[]
        ):
        """
            Search LDAP.

            Use the priority ordered SUPPORTED_LDAP_CONTROLS and use
            the first one supported.
        """

        if len(self.ldap.supported_controls) < 1:
            for control_num in SUPPORTED_LDAP_CONTROLS.keys():
                log.debug(
                        _("Checking for support for %s on %s") % (
                                SUPPORTED_LDAP_CONTROLS[control_num]['desc'],
                                self.domain
                            ),
                        level=8
                    )

            _search = self.ldap.search_s(
                    '',
                    scope=ldap.SCOPE_BASE,
                    attrlist=['supportedControl']
                )

            for (_result,_supported_controls) in _search:
                supported_controls = _supported_controls.values()[0]
                for control_num in SUPPORTED_LDAP_CONTROLS.keys():
                    if SUPPORTED_LDAP_CONTROLS[control_num]['oid'] in \
                            supported_controls:

                        log.debug(_("Found support for %s") % (
                                    SUPPORTED_LDAP_CONTROLS[control_num]['desc'],
                                ),
                                level=8
                            )

                        self.ldap.supported_controls.append(
                                SUPPORTED_LDAP_CONTROLS[control_num]['func']
                            )

        _results = []

        if not override_search == False:
            _use_ldap_controls = [ override_search ]
        else:
            _use_ldap_controls = self.ldap.supported_controls

        for supported_control in _use_ldap_controls:
            exec("""_results = self.%s(
                    %r,
                    scope=%r,
                    filterstr=%r,
                    attrlist=%r,
                    attrsonly=%r,
                    timeout=%r,
                    callback=callback,
                    primary_domain=%r,
                    secondary_domains=%r
                )""" % (
                        supported_control,
                        base_dn,
                        scope,
                        filterstr,
                        attrlist,
                        attrsonly,
                        timeout,
                        primary_domain,
                        secondary_domains
                    )
                )

        return _results