File: ldaputil.c

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

#include "dsgw.h"
#include "dbtdsgw.h"
#if !defined(USE_OPENLDAP)
#include "disptmpl.h"
#endif
#if XP_WIN32
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#endif
#include <errno.h>
#include "libadminutil/distadm.h"
#if !defined(USE_OPENLDAP)
#include <ldap_ssl.h>
#include <ldappr.h>
#endif

#if defined(USE_OPENLDAP)
/* the server depends on the old, deprecated ldap_explode behavior which openldap
   does not support - the use of the mozldap code should be seen as a temporary
   measure which we should remove as we improve our internal DN handling */
static char **mozldap_ldap_explode( const char *dn, const int notypes, const int nametype );
static char **mozldap_ldap_explode_dn( const char *dn, const int notypes );
static char **mozldap_ldap_explode_rdn( const char *rdn, const int notypes );
static LDAPFiltDesc *mozldap_ldap_init_getfilter( char *fname );
static LDAPFiltDesc *mozldap_ldap_init_getfilter_buf( char *buf, long buflen );
static void mozldap_ldap_getfilter_free( LDAPFiltDesc *lfdp );
static int mozldap_ldap_set_filter_additions( LDAPFiltDesc *lfdp, char *prefix, char *suffix );
static LDAPFiltInfo *mozldap_ldap_getfirstfilter( LDAPFiltDesc *lfdp, char *tagpat, char *value );
static LDAPFiltInfo *mozldap_ldap_getnextfilter( LDAPFiltDesc *lfdp );
static int mozldap_ldap_create_filter( char *filtbuf, unsigned long buflen, char *pattern, char *prefix, char *suffix, char *attr, char *value, char **valwords );
static char *filter_add_strn( char *f, char *flimit, char *v, size_t vlen );
static char *filter_add_value( char *f, char *flimit, char *v, int escape_all );
static char *convert_to_openldap_uri( const char *hostname_or_uri, int port, const char *proto );
static int break_into_words( char *str, char *delims, char ***wordsp );
#endif

static dsgwtmplinfo *init_listdisplay( char *tmplname, unsigned long options );
static int do_search( dsgwtmplinfo *tip, LDAP *ld, char *base, int scope,
	char *filter, LDAPMessage **msgpp );
static void handle_search_results( dsgwtmplinfo *tip, LDAP *ld, int rc,
	LDAPMessage *msgp, unsigned long options );
#if defined(USE_OPENLDAP)
static int get_rebind_credentials( LDAP *ld, LDAP_CONST char *url, ber_tag_t request, ber_int_t msgid, void *arg );
#else
static int get_rebind_credentials( LDAP *ld, char **whop, char **credp,
	int *methodp, int freeit, void *arg );
#endif
static void strcpy_special_undo( char *d, char *s );
static int entry2htmlwrite( void *fp, char *buf, int len );
static void emit_one_loc_dn( char *dn, char *friendlyname, char *rootname,
	int only_one );
static char *uid2dn( LDAP *ld, char *uid, char *base, int *ldaprc,
	char **lderrtxtp, char **errsp );
static void return_one_attr( LDAP *ld, LDAPMessage *entry, char *attrtype,
	char *mimetype, int valindex );
static void break_up_one_attr( char *attr, char **attrtypep, char **mimetypep,
	int *valindexp );
static LDAPFiltDesc *dsgw_ldap_init_getfilter( char *path );
static int dsgw_ldap_set_filter_additions( LDAPFiltDesc *lfdp, char *prefix, char *suffix );
static LDAPFiltInfo *dsgw_ldap_getfirstfilter( LDAPFiltDesc *lfdp, char *tagpat, char *value );
static LDAPFiltInfo *dsgw_ldap_getnextfilter( LDAPFiltDesc *lfdp );

/* binddn and bindpasswd are used in get_rebind_credentials() */
static char *binddn = NULL, *bindpasswd = NULL;

/*
 * initialize various LDAP library things -- any non-NULL parameters are
 *	initialized and set.  If an error occurs, this function will not
 *	return at all.
 * If an LDAP connection was opened, this function will return either
 * DSGW_BOUND_ASUSER if a valid cookie was found in the environment
 * and we were able to bind to the directory as that user.  If no
 * cookie was found, or the cookie would not be used to bind, then
 * an anonymous bind is performed and DSGW_BOUND_ANONYMOUS is returned.
 * If skipac (skip authentication check) is non-zero, then this
 * function will always authenticate as NULL.
 *
 * If we are configured to use a local LDAP database instead of a real
 * directory server, we always do an unauthenticated bind but we return
 * DSGW_BOUND_ASUSER.  This is done to keep our CGIs that check for a
 * return code of DSGW_BOUND_ASUSER happy.
 *
 * If skipauthwarning is set, then we don't display the javascript
 * auth warning for searches. - RJP
 */
int
dsgw_init_ldap( LDAP **ldp, LDAPFiltDesc **lfdpp, int skipac, int skipauthwarning )
{
    char	*path;
    char	*userid, *dn, *rndstr, *passwd, *cookie, *p;
    int		ret = 0, optval, limit;
    struct berval cred = {0};
#ifdef XP_WIN32
    WSADATA	wsadata;
#endif

    /* LDAP search filters */
    if ( lfdpp != NULL ) {
	path = dsgw_file2path( gc->gc_configdir, DSGW_FILTERFILE );
	if (( *lfdpp = dsgw_ldap_init_getfilter( path )) == NULL ) {
	    dsgw_error( DSGW_ERR_BADCONFIG, path, DSGW_ERROPT_EXIT, 0, NULL );
	}
	free( path );
	ret =  0;
    }

#ifdef XP_WIN32

    if( ret = WSAStartup(0x0101, &wsadata ) != 0 )
	dsgw_error( DSGW_ERR_WSAINIT, NULL, DSGW_ERROPT_EXIT, 0, NULL );

#endif /* XP_WIN32 */

    /* LDAP connection */
    if ( ldp != NULL ) {
	if ( gc == NULL ) {
	    dsgw_error( DSGW_ERR_INTERNAL, 
		    XP_GetClientStr(DBT_ldapInitLcacheInitAttemptedBefor_),
		    DSGW_ERROPT_EXIT, 0, NULL );
	}
	if ( gc->gc_localdbconf == NULL ) {
#if defined(USE_OPENLDAP)
	    char *ldapurl;
	    if ( gc->gc_ldapssl ) {
		if ( gc->gc_securitypath == NULL ) {
		    dsgw_error( DSGW_ERR_SSLINIT, gc->gc_securitypath,
				DSGW_ERROPT_EXIT, 0, NULL );
		}
		ldapurl = convert_to_openldap_uri( gc->gc_ldapserver, 
		                                   gc->gc_ldapport, "ldaps" );
	    } else {
		ldapurl = convert_to_openldap_uri( gc->gc_ldapserver, 
		                                   gc->gc_ldapport, "ldap" );
	    }
	    ret = ldap_initialize(ldp, (const char *)ldapurl);
	    if (ret) {
		*ldp = NULL; /* make sure to call dsgw_error */
	    }
	    free(ldapurl);
#else
	    /* "Real LDAP server" case */
	    if ( gc->gc_ldapssl ) {
		if ( gc->gc_securitypath == NULL ) {
		    dsgw_error( DSGW_ERR_SSLINIT, gc->gc_securitypath,
				DSGW_ERROPT_EXIT, 0, NULL );
		}
		if ( ldapssl_client_init( gc->gc_securitypath,
			NULL ) < 0 ) {
		    dsgw_error( DSGW_ERR_SSLINIT, gc->gc_securitypath,
				DSGW_ERROPT_EXIT, 0, NULL );
		}
		*ldp = ldapssl_init( gc->gc_ldapserver, gc->gc_ldapport, 1 );
		dsgw_NSSInitializedAlready = 1;
	    } else {
		*ldp = ldap_init( gc->gc_ldapserver, gc->gc_ldapport );
	    }
#endif
	    if ( *ldp == NULL ) {
		dsgw_error( DSGW_ERR_LDAPINIT, NULL, DSGW_ERROPT_EXIT, 0,
			NULL );
	    }
	} 
	if ( gc->gc_ldapssl ) {
#if defined(USE_OPENLDAP)
	    char *certdir = gc->gc_securitypath;
	    int optval = 0;
#endif /* !USE_OPENLDAP */
	    int ssl_strength = 0;

		/* verify certificate only */
#if defined(USE_OPENLDAP)
	    ssl_strength = LDAP_OPT_X_TLS_NEVER;
#else /* !USE_OPENLDAP */
	    ssl_strength = LDAPSSL_AUTH_CERT;
#endif /* !USE_OPENLDAP */

#if defined(USE_OPENLDAP)
	    if ((ret = ldap_set_option(*ldp, LDAP_OPT_X_TLS_REQUIRE_CERT, &ssl_strength))) {
		dsgw_error( DSGW_ERR_SSLINIT, "require cert option", DSGW_ERROPT_EXIT,
			    0, NULL );
	    }
	    /* tell it where our cert db is */
	    if ((ret = ldap_set_option(*ldp, LDAP_OPT_X_TLS_CACERTDIR, certdir))) {
		dsgw_error( DSGW_ERR_SSLINIT, gc->gc_securitypath, DSGW_ERROPT_EXIT,
			    0, NULL );
	    }
#if defined(LDAP_OPT_X_TLS_PROTOCOL_MIN)
	    optval = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
	    if ((ret = ldap_set_option(*ldp, LDAP_OPT_X_TLS_PROTOCOL_MIN, &optval))) {
		dsgw_error( DSGW_ERR_SSLINIT, "minimum protocol level to SSLv3", DSGW_ERROPT_EXIT,
			    0, NULL );
	    }
#endif /* LDAP_OPT_X_TLS_PROTOCOL_MIN */
	    if ((ret = ldap_set_option(*ldp, LDAP_OPT_X_TLS_NEWCTX, &optval))) {
		dsgw_error( DSGW_ERR_SSLINIT, "new security context",
			    DSGW_ERROPT_EXIT, 0, NULL );
	    }
#else  /* !USE_OPENLDAP */
	    if ((ret = ldapssl_set_strength(*ldp, ssl_strength)) ||
		(ret = ldapssl_set_option(*ldp, SSL_ENABLE_SSL2, PR_FALSE)) ||
		(ret = ldapssl_set_option(*ldp, SSL_ENABLE_SSL3, PR_TRUE)) ||
		(ret = ldapssl_set_option(*ldp, SSL_ENABLE_TLS, PR_TRUE))) {
		int prerr = PR_GetError();

		dsgw_error( DSGW_ERR_SSLINIT, (char *)PR_ErrorToString(prerr, PR_LANGUAGE_I_DEFAULT),
			    DSGW_ERROPT_EXIT, 0, NULL );
	    }
	    /* tell bind code we are using SSL */
	    ldap_set_option(*ldp, LDAP_OPT_SSL, LDAP_OPT_ON);
#endif /* !USE_OPENLDAP */
	}
	rndstr = dn = NULL;
	passwd = dsgw_get_cgi_var( "passwd", DSGW_CGIVAR_OPTIONAL );
	if (passwd && passwd[0]) {
	    unescape_entities(passwd); /* unescape before using with ldap */
	}

	if (( p = dsgw_get_cgi_var( "ldapsizelimit", DSGW_CGIVAR_OPTIONAL ))
		!= NULL ) {
	    limit = atoi( p );
	    (void) ldap_set_option( *ldp, LDAP_OPT_SIZELIMIT, &limit );
	}

	if (( p = dsgw_get_cgi_var( "ldaptimelimit", DSGW_CGIVAR_OPTIONAL ))
		!= NULL ) {
	    limit = atoi( p );
	    (void) ldap_set_option( *ldp, LDAP_OPT_TIMELIMIT, &limit );
	}

	/*
	 * we don't bother with authentication if:
	 *  the "skipac" flag is non-zero OR
	 *  no "passwd" form element was passed in and we are using local db
	 */
	if ( !skipac && ( passwd != NULL || gc->gc_localdbconf == NULL )) {
	    /*
	     * There are several ways in which authentication might
	     * happen.
	     */
	    if ( gc->gc_admserv ) {
		/*
		 * We're running under the admin server, so ask libadmin
		 * for the user's credentials.  If a password comes as a form
		 * field, it overrides value we get from admin server
		 */
		(void)dsgw_get_adm_identity( *ldp, &userid, &dn,
			( passwd == NULL ) ? &passwd : NULL, DSGW_ERROPT_EXIT );

#ifdef DSGW_DEBUG
		dsgw_log( "dsgw_init_ldap: run under admserv, user id = %s, "
			"dn = %s, passwd = %s, skipac = %d, dn = 0x%p\n",
			userid == NULL ? "NULL" : userid,
			dn == NULL ? "NULL" : dn,
			passwd == NULL ? "NULL" : passwd,
			skipac, dn );
#endif
	    } else {
		/*
		 * Not running under admin server.  The DN and password
		 * might come in as form fields, or the authentication
		 * might be accomplished via a client-side cookie which
		 * gets looked up in the gateway's cookie database.
		 */

		/* check for dn/binddn in request */
		if ( passwd != NULL ) {
		    if (( dn = dsgw_get_escaped_cgi_var( "escapedbinddn",
			    "binddn", DSGW_CGIVAR_OPTIONAL )) == NULL &&
			    ( dn = dsgw_get_cgi_var( "dn",
			    DSGW_CGIVAR_OPTIONAL )) == NULL ) {
			free( passwd );
			passwd = NULL;
		    } else {
			/* got DN:  undo extra level of escaping */
			dsgw_form_unescape( dn );
		    }
		}

		if ( passwd == NULL ) {
		    /* Check for a valid authentication cookie */
		    cookie = dsgw_get_auth_cookie();
		    if ( cookie != NULL ) {
			if ( dsgw_parse_cookie( cookie, &rndstr, &dn ) == 0 ) {
			    int ckrc;
			    if (( ckrc = dsgw_ckdn2passwd( rndstr, dn,
				    &passwd )) != 0 ) {

				passwd = NULL;
				dn = NULL;
				/* 
				 * Delete the cookie and print out the error message.
				 * dn2passwd_error() returns 1 if the CGI should exit,
				 * 0 if it should continue.
				 */
				if (dsgw_dn2passwd_error( ckrc, skipauthwarning )) {
				    exit( 0 );
				}

			    }
			}
		    }

		    if ( rndstr != NULL ) {
			free( rndstr );
		    }
		    if ( cookie != NULL ) {
			free( cookie );
		    }
		}
	    }
	}

	/*
	 * try to use LDAP version 3 but fall back to v2 if bind fails
	 */
	optval = LDAP_VERSION3;
	(void)ldap_set_option( *ldp, LDAP_OPT_PROTOCOL_VERSION, &optval );

	/*
	 * If everything above failed to set the dn/password, then use
	 * the binddn and bindpw, if any.
	 */
	if (dn == NULL && passwd == NULL && 
	    strlen(gc->gc_binddn) > 0 && strlen(gc->gc_bindpw) > 0) {
	  dn = dsgw_ch_strdup(gc->gc_binddn);
	  passwd = dsgw_ch_strdup(gc->gc_bindpw);
	}

	cred.bv_val = passwd;
	cred.bv_len = passwd ? strlen(passwd) : 0;
	if (( ret = ldap_sasl_bind_s( *ldp, dn, LDAP_SASL_SIMPLE, &cred, 
	                         NULL, NULL, NULL )) == LDAP_PROTOCOL_ERROR ) {
		optval = LDAP_VERSION2;
		(void)ldap_set_option( *ldp, LDAP_OPT_PROTOCOL_VERSION,
			&optval );
		ret = ldap_sasl_bind_s( *ldp, dn, "SIMPLE", &cred, 
	                                NULL, NULL, NULL );
	}

	if ( ret != LDAP_SUCCESS ){
	    dsgw_ldap_error( *ldp, DSGW_ERROPT_DURINGBIND );

	    /* Display back button */
	    dsgw_form_begin( NULL, NULL );
	    dsgw_emits( "\n<CENTER><TABLE border=2 width=\"100%\"><TR>\n" );
	    dsgw_emits( "<TD WIDTH=\"100%\" ALIGN=\"center\">\n" );
	    dsgw_emitf( "<INPUT TYPE=\"button\" VALUE=\"%s\" "
		       "onClick=\"history.back()\">\n",
		       XP_GetClientStr(DBT_goBack_) );
	    dsgw_emits( "\n</TABLE></CENTER></FORM>\n" );
	    exit(0);
	}

	if (( dn != NULL ) && ( passwd != NULL )) {
	    ret = DSGW_BOUND_ASUSER;
	    binddn = dn;
	    bindpasswd = passwd;
	    ldap_set_rebind_proc( *ldp, get_rebind_credentials, NULL );
	} else if ( gc->gc_localdbconf != NULL ) {
	    ret = DSGW_BOUND_ASUSER;	/* a small, harmless lie */
	} else {
	    ret = DSGW_BOUND_ANONYMOUS;
	}

    }
    return ret;
}


/* 
 * get user identity from the admin. server (if running under it)
 *	if uidp is non-NULL, it is set to point to user's login id.
 *	if dnp is non-NULL, it is set to point to user's DN.
 *	if pwdp is non-NULL, it is set to point to user's password.
 * Returns: 0 if all goes well, -1 if an error occurs.
 *
 * Note that ld is used only if dnp != NULL, and then only if the admin server
 * returns NULL when asked for the DN.
 */
int
dsgw_get_adm_identity( LDAP *ld, char **uidp, char **dnp, char **pwdp,
	int erropts  )
{
    int		rc, need_to_get_dn;
    char	*uid;
    static int	adm_inited = 0;

    if ( !gc->gc_admserv ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_notRunningUnderTheAdministration_),
		erropts, 0, NULL );
	return( -1 );
    }

    if ( !adm_inited ) {
	if ( ADM_InitializePermissions( &rc ) < 0 ) {
	    dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		    XP_GetClientStr(DBT_couldNotInitializePermissions_),
		    erropts, 0, NULL );
	    return( -1 );
	}
	adm_inited = 1;
    }

    need_to_get_dn = ( dnp != NULL );

    if ( need_to_get_dn && ADM_GetUserDNString( &rc, dnp ) < 0 ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotMapUsernameToADnErrorFro_),
		erropts, 0, NULL );
	return( -1 );
    }

    /*
     * get userid if:
     *    1. requested by caller (uidp != NULL)
     * or 2. DN was requested but Admin Server didn't return the DN
     */
    if (( uidp != NULL || ( need_to_get_dn && *dnp == NULL )) &&
	    ( ADM_GetCurrentUsername( &rc, &uid ) < 0 || uid == NULL )) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotGetCurrentUsername_), erropts,
		0, NULL );
	return( -1 );
    }

    if ( uidp != NULL ) {
	*uidp = uid;
    }

    if ( need_to_get_dn && *dnp == NULL ) {
	/*
	 * try to map userid to DN using LDAP search
	 */
	int	lderr;
	char	*errstr, *lderrtxt;

	if (( *dnp = uid2dn( ld, uid, gc->gc_ldapsearchbase, &lderr,
		&lderrtxt, &errstr )) == NULL ) {
	    dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL, errstr, erropts, lderr,
		    lderrtxt );
	    return( -1 );
	}
    }

    if ( pwdp != NULL && ADM_GetCurrentPassword( &rc, pwdp ) < 0 ) {
	dsgw_error( DSGW_ERR_ADMSERV_CREDFAIL,
		XP_GetClientStr(DBT_couldNotGetCurrentUserPassword_), erropts,
		0, NULL );
	return( -1 );
    }

    return( 0 );
}


void
dsgw_ldap_error( LDAP *ld, int erropts )
{
    int		lderr;
    char	*lderrtxt = NULL;

    lderr = dsgw_ldap_get_lderrno( ld, NULL, &lderrtxt );
    dsgw_error( DSGW_ERR_LDAPGENERAL, dsgw_ldaperr2string( lderr ),
		erropts, lderr, lderrtxt );
}


struct ldap_searchobj *
dsgw_type2searchobj( struct ldap_searchobj *solistp, char *type )
{
    struct ldap_searchobj	*sop;

    for ( sop = ldap_first_searchobj( solistp ); sop != NULL;
	    sop = ldap_next_searchobj( solistp, sop )) {
	if ( strcasecmp( type, sop->so_objtypeprompt ) == 0 ) {
	    return( sop );
	}
    }

    return( NULL );
}


struct ldap_searchattr *
dsgw_label2searchattr( struct ldap_searchobj *sop, char *label )
{
    struct ldap_searchattr *sap;

    for ( sap = sop->so_salist; sap != NULL; sap = sap->sa_next ) {
	if ( strcasecmp( label, sap->sa_attrlabel ) == 0 ) {
	    return( sap );
	}
    }

    return( NULL );
}


struct ldap_searchmatch *
dsgw_prompt2searchmatch( struct ldap_searchobj *sop, char *prompt )
{
    struct ldap_searchmatch *smp;

    for ( smp = sop->so_smlist; smp != NULL; smp = smp->sm_next ) {
	if ( strcasecmp( prompt, smp->sm_matchprompt ) == 0 ) {
	    return( smp );
	}
    }

    return( NULL );
}


static dsgwtmplinfo *
init_listdisplay( char *tmplname, unsigned long options )
{
    char	*s;

    if (( s = dsgw_get_cgi_var( "listtemplate", DSGW_CGIVAR_OPTIONAL ))
	    != NULL ) {
	tmplname = s;
    }

    return( dsgw_display_init( DSGW_TMPLTYPE_LIST, tmplname, options ));
}


void
dsgw_smart_search( LDAP *ld, struct ldap_searchobj *sop, LDAPFiltDesc *lfdp,
	char *base, char *value, unsigned long options )
{
    int			rc;
    LDAPFiltInfo	*lfip;
    dsgwtmplinfo	*tip;
    LDAPMessage		*msgp;

    dsgw_ldap_set_filter_additions( lfdp, sop->so_filterprefix, NULL );
    tip = init_listdisplay( sop->so_objtypeprompt, options );

    if (( lfip = dsgw_ldap_getfirstfilter( lfdp, sop->so_filtertag, value ))
	    == NULL ) {
	dsgw_error( DSGW_ERR_NOFILTERS, sop->so_objtypeprompt,
		DSGW_ERROPT_EXIT, 0, NULL );
    }

    for ( ; lfip != NULL; lfip = dsgw_ldap_getnextfilter( lfdp )) {
	dsgw_set_searchdesc( tip, NULL, lfip->lfi_desc, value );

	rc = do_search( tip, ld, base, sop->so_defaultscope, lfip->lfi_filter,
		&msgp );

	if ( rc != LDAP_SUCCESS ||
		( msgp != NULL && ldap_count_entries( ld, msgp ) > 0 )) {
	    if ( strstr( lfip->lfi_filter, "~=" ) != NULL ) {
		/* always list if approximate filter used to find entry */
		options |= DSGW_DISPLAY_OPT_LIST_IF_ONE;
	    }
	    break;	/* error or got some entries:  stop searching */
	}
    }

    handle_search_results( tip, ld, rc, msgp, options );
}


void
dsgw_pattern_search( LDAP *ld, char *listtmpl,
	char *searchdesc2, char *searchdesc3, char *searchdesc4,
	char *filtpattern, char *filtprefix, char *filtsuffix, char *attr,
	char *base, int scope, char *value, unsigned long options )
{
    char		buf[ 4096 ];
    int			rc;
    dsgwtmplinfo	*tip;
    LDAPMessage		*msgp;

    tip = init_listdisplay( listtmpl, options );

    dsgw_ldap_create_filter( buf, sizeof( buf ), filtpattern,
	    filtprefix, filtsuffix, attr, value, NULL );

    dsgw_set_searchdesc( tip, searchdesc2, searchdesc3, searchdesc4 );

    rc = do_search( tip, ld, base, scope, buf, &msgp );
    handle_search_results( tip, ld, rc, msgp, options );
}


/*
 * Perform URL-based search.
 * Note that if "ld" is NULL, this routine sets gc->gc_ldapserver and
 * gc->gc_ldapport globals itself, calls dsgw_init_ldap(), and then does
 * the URL-based search.  If "ld" is not NULL, no initialization is done
 * here.
 * Note: ported from 389-ds-base ldap/servers/slapd/ldaputil.c
 */
void
dsgw_ldapurl_search( LDAP *ld, char *ldapurl )
{
    int			rc, ec, did_init_ldap;
    LDAPMessage		*msgp;
    LDAPURLDesc		*ludp;
    unsigned long	no_options = 0;
    int                 one_attr = 0;

    if (( rc = dsgw_ldap_url_parse( ldapurl, &ludp, 0, NULL )) != 0 ) {
	switch ( rc ) {
	case LDAP_URL_ERR_BADSCOPE:
	    ec = DSGW_ERR_LDAPURL_BADSCOPE;
	    break;
	case LDAP_URL_ERR_MEM:
	    ec = DSGW_ERR_NOMEMORY;
	    break;
#if defined(USE_OPENLDAP)
	case LDAP_URL_ERR_BADSCHEME:
	    ec = DSGW_ERR_BADSCHEME;
	    break;
	case LDAP_URL_ERR_BADENCLOSURE:
	    ec = DSGW_ERR_BADENCLOSURE;
	    break;
	case LDAP_URL_ERR_BADURL:
	    ec = DSGW_ERR_BADURL;
	    break;
	case LDAP_URL_ERR_BADHOST:
	    ec = DSGW_ERR_BADHOST;
	    break;
	case LDAP_URL_ERR_BADATTRS:
	    ec = DSGW_ERR_BADATTRS;
	    break;
	case LDAP_URL_ERR_BADFILTER:
	    ec = DSGW_ERR_BADFILTER;
	    break;
	case LDAP_URL_ERR_BADEXTS:
	    ec = DSGW_ERR_BADEXTS;
	    break;
#else /* !USE_OPENLDAP */
	case LDAP_URL_ERR_NODN:
	    ec = DSGW_ERR_LDAPURL_NODN;
	    break;
	case LDAP_URL_ERR_NOTLDAP:
	default:
	    ec = DSGW_ERR_LDAPURL_NOTLDAP;
	    break;
#endif
	}
	dsgw_error( ec, ldapurl, DSGW_ERROPT_EXIT, 0, NULL );
    }

    if ( ld == NULL ) {
	one_attr = ( ludp->lud_attrs != NULL && ludp->lud_attrs[ 0 ] != NULL && ludp->lud_attrs[ 1 ] == NULL );
	(void)dsgw_init_ldap( &ld, NULL, 0, one_attr );
	did_init_ldap = 1;
    } else {
	did_init_ldap = 0;
    }

    /* XXX a bit of a hack:  if it looks like only a DN was included, we
     * assume that a read of the entry is desired.
     */
    if ( (ludp->lud_scope == LDAP_SCOPE_BASE) &&
	 ( (NULL == ludp->lud_filter) ||
	   (strcasecmp( ludp->lud_filter, "(objectClass=*)" ) == 0) ) ) {
	dsgw_read_entry( ld, ludp->lud_dn, NULL, NULL, ludp->lud_attrs,
		no_options );
    } else {
	dsgwtmplinfo	*tip;

	dsgw_send_header();
	tip = init_listdisplay( "urlsearch", no_options );
	dsgw_set_searchdesc( tip, NULL, XP_GetClientStr(DBT_theLDAPFilterIs_), ldapurl );
	rc = do_search( tip, ld, ludp->lud_dn, ludp->lud_scope,
		ludp->lud_filter, &msgp );
	handle_search_results( tip, ld, rc, msgp, no_options );
    }

    if ( did_init_ldap ) {
	ldap_unbind_ext( ld, NULL, NULL );
    }
}


/*
 * do the actual search over LDAP.  Return an LDAP error code.
 */
static int
do_search( dsgwtmplinfo *tip, LDAP *ld, char *base, int scope, char *filter,
	LDAPMessage **msgpp )
{
    char		**attrlist, *attrs[ 3 ];

    *msgpp = NULL;

    if ( tip == NULL || tip->dsti_attrs == NULL ) {
	attrs[ 0 ] = DSGW_ATTRTYPE_OBJECTCLASS;
	if ( tip != NULL && tip->dsti_sortbyattr != NULL ) {
	    attrs[ 1 ] = tip->dsti_sortbyattr;
	    attrs[ 2 ] = NULL;
	} else {
	    attrs[ 1 ] = NULL;
	}
	attrlist = attrs;
    } else {
	attrlist = tip->dsti_attrs;
    }
#ifdef DSGW_DEBUG
    dsgw_log ("ldap_search_ext_s(ld,\"%s\",%i,\"%s\")\n", base, scope, filter);
#endif
    return( ldap_search_ext_s( ld, base, scope, filter, attrlist, 0, 
                               NULL, NULL, NULL /* no timelimit */,
                               -1 /* no sizelimit */, msgpp ));
}


static int
is_subtype( const char *sub, const char *sup )
{
    auto const size_t subLen = strlen( sub );
    auto const size_t supLen = strlen( sup );
    if ( subLen < supLen ) return 0;
    if ( subLen == supLen ) return !strcasecmp( sub, sup );
    if ( sub[supLen] != ';' ) return 0;
    return !strncasecmp( sub, sup, strlen( sup ));
}

static const struct berval* LDAP_C LDAP_CALLBACK
dsgw_keygen( void *arg, LDAP *ld, LDAPMessage *entry )
{
    auto const char* sortbyattr = (char*)arg;
    auto struct berval* result = NULL;

    if (sortbyattr == NULL) {	/* sort by DN */
	auto char* DN = ldap_get_dn( ld, entry );
	if (DN) {
	    result = dsgw_strkeygen( CASE_INSENSITIVE, DN );
	    ldap_memfree( DN );
	}
    } else {
	auto char* attr;
	auto BerElement *ber;
	for (attr = ldap_first_attribute( ld, entry, &ber ); attr != NULL; 
	     attr = ldap_next_attribute ( ld, entry, ber ) ) {
	    auto struct berval **vals;
	    if ( is_subtype( attr, sortbyattr ) &&
		NULL != ( vals = ldap_get_values_len( ld, entry, attr ))) {
		auto size_t i;
		for ( i = 0; vals[i] && vals[i]->bv_val; ++i ) {
		    auto struct berval* key = dsgw_strkeygen( CASE_INSENSITIVE, 
		                                              vals[i]->bv_val );
		    if ( result == NULL || dsgw_keycmp( NULL, key, result ) < 0 ) {
			auto struct berval* tmp = result;
			result = key;
			key = tmp;
#ifdef DSGW_DEBUG
			{
			    auto char* ev = dsgw_strdup_escaped( vals[i]->bv_val );
			    auto char* DN = ldap_get_dn( ld, entry );
			    dsgw_log( "dsgw_keygen(%s,%s) %p %s\n", sortbyattr, DN, (void*)result, ev );
			    ldap_memfree( DN );
			    free( ev );
			}
#endif
		    }
		    if ( key != NULL ) {
			dsgw_keyfree( arg, key );
		    }
		}
		ldap_value_free_len( vals );
	    }
	    ldap_memfree( attr );
	}
	if ( ber != NULL ) {
	    ber_free( ber, 0 );
	}
    }
    return result ? result : /* no such attribute */ dsgw_key_last;
}

static void
handle_search_results( dsgwtmplinfo *tip, LDAP *ld, int rc, LDAPMessage *msgp,
	unsigned long options )
{
    int		count;
    LDAPMessage	*entry;
    char	*dn, *errortext, *lderrtxt;
    struct berval **ocvals = NULL;

    count = ( msgp == NULL ) ? 0 : ldap_count_entries( ld, msgp );
    if ( rc == LDAP_SUCCESS ) {
	errortext = NULL;
	lderrtxt = NULL;
    } else {
	errortext = dsgw_ldaperr2string( rc );
	(void)dsgw_ldap_get_lderrno( ld, NULL, &lderrtxt );
    }
    dsgw_set_search_result( tip, count, errortext, lderrtxt );

    if ( count > 0 ) {
	entry = ldap_first_entry( ld, msgp );

	if ( count == 1 && ( options & DSGW_DISPLAY_OPT_LIST_IF_ONE ) == 0 ) {
	    /* found exactly one entry:  read and display it */
	    dn = ldap_get_dn( ld, entry );
	    ocvals = ldap_get_values_len( ld, entry, DSGW_ATTRTYPE_OBJECTCLASS );
	    ldap_msgfree( msgp );

	    dsgw_read_entry( ld, dn, ocvals, NULL, NULL, options );

	    if ( ocvals ) {
		ldap_value_free_len( ocvals );
	    }
	    return;
	}

	/* list entries */
#ifdef DSGW_DEBUG
	dsgw_log( "handle_search_results: sort entries by %s\n",
		  tip->dsti_sortbyattr ? tip->dsti_sortbyattr : "DN" );
#endif
	ldap_keysort_entries( ld, &msgp, tip->dsti_sortbyattr,
		dsgw_keygen, dsgw_keycmp, dsgw_keyfree );
	for ( entry = ldap_first_entry( ld, msgp ); entry != NULL;
		entry = ldap_next_entry( ld, entry )) {
	    dsgw_display_entry( tip, ld, entry, NULL, NULL );
	}
	if ( options & DSGW_DISPLAY_OPT_DNLIST_JS ) {
	    int i;
	    char *edn, *js0, *js1;
	    char **xdn;
	    struct berval **snvals = NULL;

	    dsgw_emits( "<SCRIPT type=\"text/javascript\">\n" );
	    dsgw_emits( "var dnlist = new Array;\n" );
	    for ( i = 0, entry = ldap_first_entry( ld, msgp ); entry != NULL;
		    i++, entry = ldap_next_entry( ld, entry )) {
		dn = ldap_get_dn( ld, entry );
		edn = dsgw_strdup_escaped( dn );
		xdn = dsgw_ldap_explode_dn( dn, 1 );
		dsgw_emitf( "dnlist[%d] = new Object\n", i );
		dsgw_emitf( "dnlist[%d].edn = '%s';\n", i, edn );
		js0 = dsgw_escape_quotes( xdn[ 0 ] );
		if ( xdn[1] != NULL ) {
		    js1 = dsgw_escape_quotes( xdn[ 1 ] );
		    dsgw_emitf( "dnlist[%d].rdn = '%s, %s';\n", i, js0, js1 );
		    free( js1 );
		} else {
		    dsgw_emitf( "dnlist[%d].rdn = '%s';\n", i, js0 );
		}
		free( js0 );
		snvals = ldap_get_values_len( ld, entry, "sn" );
		if ( snvals == NULL ) {
		    js0 = NULL;
		} else {
		    js0 = dsgw_escape_quotes( snvals[ 0 ]->bv_val );
		    ldap_value_free_len( snvals );
		}
		dsgw_emitf( "dnlist[%d].sn = '%s';\n", i, ( js0 == NULL ) ?
			" " : js0 );
		if ( js0 != NULL ) {
		    free( js0 );
		}

		dsgw_emitf( "dnlist[%d].selected = false;\n", i );
		free( edn );
		dsgw_charray_free( xdn );
		ldap_memfree( dn );
	    }
	    dsgw_emitf( "dnlist.count = %d;\n", i );
	    dsgw_emitf( "</SCRIPT>\n" );
	}
	ldap_msgfree( msgp );
    } else {
	/* Count <= 0 */
	if ( options & DSGW_DISPLAY_OPT_DNLIST_JS ) {
	    dsgw_emitf( "<SCRIPT type=\"text/javascript\">\n" );
	    dsgw_emitf( "var dnlist = new Array;\n" );
	    dsgw_emitf( "dnlist.count = 0;\n" );
	    dsgw_emitf( "</SCRIPT>\n" );
	}
    }

    dsgw_display_done( tip, NULL );
}

#include "disptmpl.h"
/*
 * read and display a single entry.  If ocvals is non-NULL, it should
 * contain the list of objectClass values for this entry.
 */ 
void
dsgw_read_entry( LDAP *ld, char *dn, struct berval **ocvals, char *tmplname,
	char **attrs, unsigned long options )
{
    int			rc, one_attr, freeocvals, valindex;
    char		*tmpattr, *attr0, *mimetype;
    LDAPMessage		*msgp, *entry, *aomsgp, *aoentry;
    dsgwtmpl		*tmpl;
    dsgwtmplinfo	*tip;

    if (( options & DSGW_DISPLAY_OPT_AUTH ) != 0 ) {
	/*
	 * XXX hack -- if we are trying to authenticate, we don't generate an
	 * entry display at all.  Instead, we generate an authenticate form.
	 */
	dsgw_send_header();
	dsgw_emit_auth_form( dn );
	return;
    }

    one_attr = ( attrs != NULL && attrs[ 0 ] != NULL && attrs[ 1 ] == NULL );
    if ( one_attr ) {
	break_up_one_attr( attrs[ 0 ], &tmpattr, &mimetype, &valindex );
	if ( strcasecmp( tmpattr, "_vcard" ) == 0 ) {	/* VCards are special */
	    dsgw_vcard_from_entry( ld, dn, mimetype );
	    return;
	}
	attr0 = attrs[ 0 ];     /* replace first & only attr. */
	attrs[ 0 ] = tmpattr;
    } else {
	attr0 = NULL;
    }

    if ( tmplname == NULL && ( tmplname = dsgw_get_cgi_var( "displaytemplate",
	    DSGW_CGIVAR_OPTIONAL )) == NULL && attrs == NULL ) {
	/* determine what display template to use based on objectClass values */
	freeocvals = 0;
	if ( ocvals == NULL ) {	/* read entry to get objectClasses */
	    char	*attrs[ 2 ];

	    attrs[ 0 ] = DSGW_ATTRTYPE_OBJECTCLASS;
	    attrs[ 1 ] = NULL;

	    if (( rc = ldap_search_ext_s( ld, dn, LDAP_SCOPE_BASE, 
	                      "objectClass=*", attrs, 0, 
	                      NULL, NULL, NULL /* no timelimit */,
	                      -1 /* no sizelimit */, &msgp )) != LDAP_SUCCESS ||
		    ( entry = ldap_first_entry( ld, msgp )) == NULL ) {
		dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	    }
	    ocvals = ldap_get_values_len( ld, msgp, DSGW_ATTRTYPE_OBJECTCLASS );
	    if ( ocvals ) {
	        freeocvals = 1;
	    }
	    ldap_msgfree( msgp );
	}

	if ( ocvals == NULL || ( tmpl = dsgw_oc2template( ocvals )) == NULL ) {
	    tmplname = NULL;
	} else {
	    tmplname = tmpl->dstmpl_name;
	}

	if ( freeocvals ) {
	    ldap_value_free_len( ocvals );
	}
    }

    if ( tmplname == NULL ) {
	tip = NULL;

	if ( !one_attr ) {
	    char	*title;

	    if (( title = dsgw_ldap_dn2ufn( dn )) == NULL ) {
		title = dn;
	    }
	    dsgw_send_header();
	    dsgw_html_begin( title, 1 );
	    if (title != dn) {
		free(title);
	    }
	    dsgw_emitf( "<FONT SIZE=\"+1\">\n%s\n</FONT>\n",
	    XP_GetClientStr(DBT_noteThereIsNoDisplayTemplateForT_) );
	} 

    } else if (( tip = dsgw_display_init( DSGW_TMPLTYPE_DISPLAY, tmplname,
	    options )) != NULL ) {
	dsgw_send_header();
	attrs = tip->dsti_attrs;
    }

    /* now read the attributes needed for the template */
    if (( rc = ldap_search_ext_s( ld, dn, LDAP_SCOPE_BASE, "objectClass=*",
                                  attrs, 0, NULL, NULL, 
                                  NULL /* no timelimit */,
                                  -1 /* no sizelimit */,
                                  &msgp )) != LDAP_SUCCESS ) {
	dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
    }

    if (( entry = ldap_first_entry( ld, msgp )) == NULL ) {
	ldap_msgfree( msgp );
	dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
    }

    /* and retrieve attribute types only if we need any of them */
    if ( one_attr || tip == NULL || tip->dsti_attrsonly_attrs == NULL ) {
	aomsgp = NULL;
    } else {
        if (( rc = ldap_search_ext_s( ld, dn, LDAP_SCOPE_BASE, "objectClass=*",
                                      tip->dsti_attrsonly_attrs, 1, NULL, NULL, 
                                      NULL /* no timelimit */,
                                      -1 /* no sizelimit */,
                                      &aomsgp )) != LDAP_SUCCESS ) {
	    dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	}

	/*
	 * if no entries were returned, "aoentry" will be set to NULL by the
	 * next statement.  We don't treat that as an error since we know the
	 * entry exists.  It probably just means none of the "attrsonly" types
	 * were present in the entry.
	 */
	aoentry = ldap_first_entry( ld, aomsgp );
    }

    /* display it (finally!) */
    if ( one_attr ) {
	return_one_attr( ld, entry, attrs[ 0 ], mimetype, valindex );
    } else if ( tip == NULL ) {
	/* no template available -- display in an ugly but complete manner */
	if (( rc = ldap_entry2html( ld, NULL, entry, NULL, NULL, NULL,
		entry2htmlwrite, stdout, "\n", 0, LDAP_DISP_OPT_HTMLBODYONLY,
		NULL, NULL )) != LDAP_SUCCESS )
	{
	    dsgw_ldap_error( ld, DSGW_ERROPT_EXIT );
	}
	dsgw_html_end();
    } else {
	/* use template to create a nicely formatted display */
	dsgw_display_entry( tip, ld, entry, aoentry, NULL );
	dsgw_display_done( tip, dn );
    }

    if ( attr0 != NULL ) {
	attrs[ 0 ] = attr0;     /* if we replaced this, put original back */
    }

    if ( msgp != NULL ) {
	ldap_msgfree( msgp );
    }
    if ( aomsgp != NULL ) {
	ldap_msgfree( aomsgp );
    }
}


/*
 * return 1 if the entry already exists, 0 if not, -1 if some error occurs
 */
int
dsgw_ldap_entry_exists( LDAP *ld, char *dn, char **matchedp,
	unsigned long erropts )
{
    LDAPMessage *msgp;
    int		rc;

    msgp = NULL;
    if ( matchedp != NULL ) {
	*matchedp = NULL;
    }

    if (( rc = do_search( NULL, ld, dn, LDAP_SCOPE_BASE, "(objectClass=*)",
	    &msgp )) != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT ) {
	dsgw_ldap_error( ld, erropts );
    }

    if ( msgp == NULL || rc == LDAP_NO_SUCH_OBJECT ) {
	rc = 0;
	if ( matchedp != NULL ) {
	    (void)dsgw_ldap_get_lderrno( ld, matchedp, NULL );
	}
    } else {
	rc = ( ldap_count_entries( ld, msgp ) > 0 ? 1 : 0 );
	ldap_msgfree( msgp );
    }

    return( rc );
}


static int
entry2htmlwrite( void *fp, char *buf, int len )
{
        return( fwrite( buf, len, 1, (FILE *)fp ) == 0 ? -1 : len );
}


/*
 * return 1 if the entry's parent exists, 0 if not, -1 if some error occurs.
 * If the entry is the same as gc->gc_ldapsearchbase, then we return 1,
 * so we don't prevent people from adding their organizational entry.
 */
int
dsgw_ldap_parent_exists( LDAP *ld, char *dn, unsigned long erropts )
{
    LDAPMessage *msgp;
    int		rc;

    /* Is "dn" == gc->gc_ldapsearchbase? */
    msgp = NULL;
    if (( rc = do_search( NULL, ld, dn, LDAP_SCOPE_BASE, "(objectClass=*)",
	    &msgp )) != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT ) {
	dsgw_ldap_error( ld, erropts );
    }

    if ( msgp == NULL ) {
	rc = 0;
    } else {
	rc = ( ldap_count_entries( ld, msgp ) > 0 ? 1 : 0 );
	ldap_msgfree( msgp );
    }

    return( rc );
}

#if defined(USE_OPENLDAP)
/*
 * this function is called back by LIBLDAP when chasing referrals
 */
static int 
get_rebind_credentials( LDAP *ld, LDAP_CONST char *url, 
                        ber_tag_t request, ber_int_t msgid,
                        void *arg )
{
    struct berval cred = {0};
    cred.bv_val = bindpasswd;
    cred.bv_len = bindpasswd ? strlen(bindpasswd) : 0;
    return ldap_sasl_bind_s( ld, binddn, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL );
}
#else
/*
 * this function is called back by LIBLDAP when chasing referrals
 */
static int 
get_rebind_credentials( LDAP *ld, char **whop, char **credp,
	int *methodp, int freeit, void *arg )
{
    if ( !freeit ) {
	*whop = binddn;
	*credp = bindpasswd;
	*methodp = LDAP_AUTH_SIMPLE;
    }

    return( LDAP_SUCCESS );
}
#endif

char *
dsgw_get_binddn()
{
    return( binddn );
}

/*
 * return 1 if bound using "dn"
 * return 0 if definitely bound as someone else
 * return "def_answer" is we can't tell for sure
 */
int
dsgw_bound_as_dn( char *dn, int def_answer )
{
    int		i, rc;
    char	**rdns1, **rdns2;

    if ( binddn == NULL ) {
	/*
	 * not authenticated: if not using local db or using it as an
	 * end-user, return the default
	 */
	if ( gc->gc_localdbconf == NULL || gc->gc_enduser ) {
	    return( def_answer );
	}

	/*
         * if using local db as an admin, return "bound as someone else"
	 * since there is no access control enforced anyways.
	 */
	return( 0 );
    }

    /* first try a simple case-insensitive comparison */
    if ( strcasecmp( binddn, dn ) == 0 ) {
	return( 1 );	/* DNs are the same */
    }

    /*
     * These DNs may not have the same spacing or punctuation.  Compare RDN
     * components to eliminate any differences.
     */
    if (( rdns1 = dsgw_ldap_explode_dn( binddn, 0 )) == NULL ) {
	return( def_answer );	/* we don't know: return the default */
    }

    if (( rdns2 = dsgw_ldap_explode_dn( dn, 0 )) == NULL ) {
	dsgw_charray_free( rdns1 );
	return( def_answer );	/* we don't know: return the default */
    }

    for ( i = 0; rdns1[ i ] != NULL && rdns2[ i ] != NULL; ++i ) {
	if ( strcasecmp( rdns1[ i ], rdns2[ i ] ) != 0 ) {
	    break;	/* DNs are not the same */
	}
    }

    rc = ( rdns1[ i ] == NULL && rdns2[ i ] == NULL );

    dsgw_charray_free( rdns1 );
    dsgw_charray_free( rdns2 );

    return( rc );
}



/*
 * Compare 2 DNs.  Return 1 if they are equivalent, 0 if not.
 */
int
dsgw_dn_cmp( char *dn1, char *dn2 )
{
    int		i, rc;
    char	**rdns1, **rdns2;

    /* first try a simple case-insensitive comparison */
    if ( dsgw_utf8casecmp( (unsigned char *)dn1, (unsigned char *)dn2 ) == 0 ) {
	return( 1 );	/* DNs are the same */
    }

    /*
     * These DNs may not have the same spacing or punctuation.  Compare RDN
     * components to eliminate any differences.
     */
    if (( rdns1 = dsgw_ldap_explode_dn( dn1, 0 )) == NULL ) {
	return( 0 );	/* we don't know: return 0 */
    }

    if (( rdns2 = dsgw_ldap_explode_dn( dn2, 0 )) == NULL ) {
	dsgw_charray_free( rdns1 );
	return( 0 );	/* we don't know: return 0 */
    }

    for ( i = 0; rdns1[ i ] != NULL && rdns2[ i ] != NULL; ++i ) {
	if ( dsgw_utf8casecmp( (unsigned char *)rdns1[ i ], (unsigned char *)rdns2[ i ] ) != 0 ) {
	    break;	/* DNs are not the same */
	}
    }

    rc = ( rdns1[ i ] == NULL && rdns2[ i ] == NULL );

    dsgw_charray_free( rdns1 );
    dsgw_charray_free( rdns2 );

    return( rc );
}


/*
 * Return the parent of dn.  The caller is responsible for freeing the
 * returned value.  Returns NULL on error.
 */
char *
dsgw_dn_parent( char *dn )
{
    char *dnp;
    int i;
    char **rdns;
    size_t len;

    if ( dn == NULL || !*dn ) {
	return( NULL );
    }

    len = strlen(dn);
    dnp = dsgw_ch_malloc( len );
    dnp[ 0 ] = '\0';
    if (( rdns = dsgw_ldap_explode_dn( dn, 0 )) == NULL ) {
	free(dnp);
	return NULL;
    }
    for ( i = 1; (rdns[0] != NULL) && (rdns[ i ] != NULL); i++ ) {
	strcat( dnp, rdns[ i ] );
	strcat( dnp, "," );
    }
    /* Get rid of the trailing "," we just appended */
    len = strlen(dnp);
    if (len > 0) {
	dnp[ len - 1 ] = '\0';
    }
    dsgw_charray_free( rdns );
    return( dnp );
}
    

/*
 * Return 1 if dn1 is the immediate ancestor of dn2, 0 otherwise.
 */
int
dsgw_is_dnparent( char *dn1, char *dn2 )
{
    char *dnp;
    int rc;

    /* A null or zero-length DN cannot have a parent */
    if ( dn2 == NULL || strlen( dn2 ) == 0 ) {
	return 0;
    }

    dnp = dsgw_dn_parent( dn2 );
    rc = dsgw_dn_cmp( dn1, dnp );
    free( dnp );

    return rc;
}


/*
 * return malloc'd array of RDN attribute value pairs
 * each element of the array is a string that looks like:  TAG=VALUE
 * this is used to extract values from the RDN when a new entry is added
 */
char **
dsgw_rdn_values( char *dn )
{
    char	**rdns, **rdncomps, *val;
    int		i;

    if (( rdns = dsgw_ldap_explode_dn( dn, 0 )) == NULL ) {
	return( NULL );
    }

    rdncomps = dsgw_ldap_explode_rdn( rdns[0], 0 );
    dsgw_charray_free( rdns );
    if ( rdncomps == NULL ) {
	return( NULL );
    }

    for ( i = 0; rdncomps[ i ] != NULL; ++i ) {
	if (( val = strchr( rdncomps[ i ], '=' )) == NULL ) {
	    dsgw_charray_free( rdncomps );
	    return( NULL );
	}
	++val;
	strcpy_special_undo( val, val );	/* undo in place */
    }

    return( rdncomps );
}


/*
 * the following routine was lifted from servers/slapd/ava.c
 * it removes special quoting, etc. from values that appear in an LDAP DN
 */
static void
strcpy_special_undo( char *d, char *s )
{
    int     quote;
 
    quote = 0;
    if ( *s == '"' ) {
	    s++;
	    quote = 1;
    }
    for ( ; *s; LDAP_UTF8INC(s)) {
	switch ( *s ) {
	case '"':
	    break;
	case '\\':
	    s++;
	    /* FALL */
	default:
	    d += LDAP_UTF8COPY (d, s);
	    break;
	}
    }
    *d = '\0'; LDAP_UTF8DEC(d);
    if ( quote && *d == '"' ) {
	*d = '\0';
    }
}


static char *
uid2dn( LDAP *ld, char *uid, char *base, int *ldaprc, char **lderrtxtp,
	char **errsp )
{
    char *attrs[] = { "objectclass", NULL };
    char filtbuf[ 85 ];	/* max of 80 char. uid + "uid=" + zero terminator */
    int rc, count;
    LDAPMessage *result;
    LDAPMessage *e;
    char *dn;
    
    *ldaprc = LDAP_SUCCESS;	/* optimistic */
    *errsp = *lderrtxtp = NULL;

    if ( ld == NULL || uid == NULL || strlen( uid ) > 80 ) {
	*errsp = XP_GetClientStr(DBT_invalidUserIdOrNullLdapHandle_);
	return NULL;
    }
    PR_snprintf( filtbuf, sizeof(filtbuf), "uid=%s", uid );

    if (( rc = ldap_search_ext_s( ld, base, LDAP_SCOPE_SUBTREE, filtbuf,
                                  attrs, 1, NULL, NULL, 
                                  NULL /* no timelimit */,
                                  -1 /* no sizelimit */,
                                  &result )) != LDAP_SUCCESS ) {
	*ldaprc = rc;
	(void)dsgw_ldap_get_lderrno( ld, NULL, lderrtxtp );
	return NULL;
    }
    if (( count = ldap_count_entries( ld, result )) != 1 ) {
	/* Search either returned no entries, or more than one entry */
	ldap_msgfree( result );
	if ( count == 0 ) {
	    *errsp = XP_GetClientStr(DBT_noMatchForUserId_);
	} else {
	    *errsp = XP_GetClientStr(DBT_moreThanOneMatchForUserId_);
	}
	return NULL;
    }

    dn = NULL;
    if (( e = ldap_first_entry( ld, result )) == NULL ||
	    ( dn = ldap_get_dn( ld, e )) == NULL ) {
	*ldaprc = dsgw_ldap_get_lderrno( ld, NULL, NULL );
    }
    ldap_msgfree( result );
    return( dn );
}


/*
 * Emit an HTML "SELECT" object that contains all the o's and ou's that
 * are underneath our default searchbase.  If there are none other than
 * the searchbase, we emit a hidden HTML TEXT object that contains the
 * searchbase and the "prefix" and "suffix" are not used.  The values for
 * the SELECT options and for the TEXT object are all escaped DNs.
 *  
 * Location popup directives look like this:
 *	<-- DS_LOCATIONPOPUP "name=VARNAME" "prefix=PREFIX" "suffix=SUFFIX" -->
 *
 * If "prefix" and/or "suffix" are omitted, they default to "".
 * If "name" is omitted it defaults to "base".
 *
 * If there are "location" directives in the dsgw.conf file, we use those
 * instead of actually searching the directory.
 */
void
dsgw_emit_location_popup( LDAP *ld, int argc, char **argv, int erropts )
{
    char	line[BIG_LINE];
    char	*varname, *prefix, *suffix, *rootname, *dn;
    int		i, count, did_init_ldap;
    LDAPMessage	*res, *e;

    if (( varname = get_arg_by_name( "name", argc, argv )) == NULL ) {
	varname = "base";
    }
    if (( prefix = get_arg_by_name( "prefix", argc, argv )) == NULL ) {
	prefix = "";
    }
    if (( suffix = get_arg_by_name( "suffix", argc, argv )) == NULL ) {
	suffix = "";
    }
    rootname = get_arg_by_name( "rootname", argc, argv );

    did_init_ldap = 0;
    res = NULL;

    if ( gc->gc_newentryloccount > 0 ) {
	count = gc->gc_newentryloccount;
    } else {
	char		*attrs[ 3 ];
	int		rc;

	if ( ld == NULL ) {
	    (void)dsgw_init_ldap( &ld, NULL, 0, 0 );
	    did_init_ldap = 1;
	}
	attrs[ 0 ] = "o";
	attrs[ 1 ] = "ou";
	attrs[ 2 ] = NULL;

	rc = ldap_search_ext_s( ld, gc->gc_ldapsearchbase, LDAP_SCOPE_SUBTREE,
	        "(|(objectclass=organization)(objectclass=organizationalunit))",
	        attrs, 1, NULL, NULL, NULL /* no timelimit */,
	        -1 /* no sizelimit */, &res );
	if ( rc != LDAP_SUCCESS || res == NULL ) {
	    dsgw_ldap_error( ld, erropts );
	    return;
	}

	count = ldap_count_entries( ld, res );
	if ( gc->gc_ldapsearchbase == NULL || *gc->gc_ldapsearchbase == '\0' ) {
	    ++count;	/* include base DN even if it is "" */
	} else {
	    /*
	     * check to see if search base was one of the entries returned
	     * we want to always list the base entry, so we need to check
	     */
	    for ( e = ldap_first_entry( ld, res ); e != NULL;
		    e = ldap_next_entry( ld, e )) {
		if (( dn = ldap_get_dn( ld, e )) == NULL ) {
		    dsgw_ldap_error( ld, erropts );
		    ldap_msgfree( res );
		    return;
		}

		rc = dsgw_dn_cmp( dn, gc->gc_ldapsearchbase );
		free( dn );
		if ( rc ) {	/* base DN was returned */
		    break;
		}
	    }
	    if ( e == NULL ) {
		++count;	/* include base DN even if was not returned */
	    }
	}
    }

    if ( count > 1 ) {
	PR_snprintf( line, sizeof(line), "%s\n<SELECT NAME=\"%s\">\n",
		prefix, varname );
    } else {
	PR_snprintf( line, sizeof(line), "<INPUT TYPE=\"hidden\" NAME=\"%s\" ",
		varname );
    }
    dsgw_emits( line );

    if ( gc->gc_newentryloccount > 0 ) {
	for ( i = 0; i < gc->gc_newentryloccount; ++i ) {
	    emit_one_loc_dn( gc->gc_newentrylocs[ i ].dsloc_dnsuffix,
		    gc->gc_newentrylocs[i].dsloc_fullname, rootname,
		    ( count < 2 ));
	}
    } else {
	/* always include the base dn first */
	emit_one_loc_dn( gc->gc_ldapsearchbase, NULL, rootname, ( count < 2 ));

	/* XXXmcs it would be nice to do a more intelligent sort here */
#ifdef DSGW_DEBUG
	dsgw_log( "dsgw_emit_location_popup: ldap_sort_entries(NULL)\n" );
#endif
	ldap_sort_entries( ld, &res, NULL, dsgw_strcmp (CASE_INSENSITIVE));

	for ( e = ldap_first_entry( ld, res ); e != NULL;
		e = ldap_next_entry( ld, e )) {
	    if (( dn = ldap_get_dn( ld, e )) == NULL ) {
		dsgw_ldap_error( ld, erropts );
		ldap_msgfree( res );
		return;
	    }

	    if ( !dsgw_dn_cmp( dn, gc->gc_ldapsearchbase )) {
		emit_one_loc_dn( dn, NULL, rootname, ( count < 2 ));
	    }
	    free( dn );
	}
    }

    if ( count > 1 ) {
	PR_snprintf( line, sizeof(line), "</SELECT>\n%s\n", suffix );
	dsgw_emits( line );
    }

    if ( res != NULL ) {
	ldap_msgfree( res );
    }
    if ( did_init_ldap ) {
	ldap_unbind_ext( ld, NULL, NULL );
    }
}


static void
emit_one_loc_dn( char *dn, char *friendlyname, char *rootname, int only_one )
{
    char	*escapeddn, **rdns, line[ BIG_LINE ];

    rdns = NULL;
    escapeddn = dsgw_strdup_escaped( dn );

    if ( !only_one ) {
	dsgw_emits( "<OPTION" );
    }

    if ( friendlyname == NULL ) {	/* use first component of DN */
	if ( *dn == '\0' ) {
	    friendlyname = ( rootname == NULL ? XP_GetClientStr(DBT_theEntireDirectory_)
		    : rootname );
	} else if (( rdns = dsgw_ldap_explode_dn( dn, 1 )) == NULL
		|| rdns[ 0 ] == NULL ) {
	    friendlyname = dn;
	} else {
	    friendlyname = rdns[ 0 ];
	}
    }

    PR_snprintf( line, sizeof(line), " VALUE=\"%s\">%s\n", escapeddn,
	    only_one ? "" : friendlyname );
    free( escapeddn );
    if ( rdns != NULL ) {
	dsgw_charray_free( rdns );
    }
    dsgw_emits( line );
}


/*
 * Return a MIME document that contains a single value.
 * XXX:  does this really belong in ldaputil.c?
 */
static void
return_one_attr( LDAP *ld, LDAPMessage *entry, char *attrtype, char *mimetype,
	int valindex )
{
    char		*val;
    struct berval	**bvals;
    unsigned long	vlen;

    if (( bvals = ldap_get_values_len( ld, entry, attrtype )) == NULL ) {
	dsgw_error( DSGW_ERR_NOATTRVALUE, attrtype, DSGW_ERROPT_EXIT, 0, NULL );
    }

    if ( valindex > ldap_count_values_len( bvals )) {
	dsgw_error( DSGW_ERR_NOATTRVALUE, attrtype, DSGW_ERROPT_EXIT, 0, NULL );
    }

    val = bvals[ valindex ]->bv_val;
    vlen = bvals[ valindex ]->bv_len;

    fprintf( stdout, "Content-Type: %s\n", mimetype );
    fprintf( stdout, "Content-Length: %ld\n\n", vlen );

#ifdef XP_WIN32
    /* flush any data on stdout before changing the mode */
    fflush( stdout );

    /* set the mode to binary 
       so windows doesn't replace with carriage
       return line feed and mess everything up
    */
    _setmode( _fileno( stdout ), _O_BINARY );
#endif

    fwrite( val, vlen, 1, stdout );

#ifdef XP_WIN32
    /* flush any remaining binary data */
    fflush( stdout );

    /* set the mode back to text */
    _setmode( _fileno( stdout ), _O_TEXT );
#endif

    ldap_value_free_len( bvals );
    free( attrtype );
}


/*
 * The general format of attrtype is:
 *	<attrtype> [ &<mimetype> ] [ &<valindex> ]
 * This routine breaks it up.  Callers should free( *attrtypep ) after they
 * are done using attrtypep and mimetypep.
 */
static void
break_up_one_attr( char *attr, char **attrtypep, char **mimetypep,
	int *valindexp )
{
    char	*p;

    *attrtypep = dsgw_ch_strdup( attr );

    *mimetypep = "text/plain";	/* default */
    *valindexp = 0;		/* default: retrieve first value */

    if (( p = strchr( *attrtypep, '&' )) != NULL ) {
	*p++ = '\0';
	if ( *p != '\0' ) {
	    *mimetypep = p;
	    if (( p = strchr( *mimetypep, '&' )) != NULL ) {
		*p++ = '\0';
		*valindexp = atoi( p );
	    }
	}
    }
}

/*
  emacs settings
  Local Variables:
  indent-tabs-mode: t
  tab-width: 8
  End:
*/

#if defined(USE_OPENLDAP)
/* mozldap ldap_init and ldap_url_parse accept a hostname in the form
   host1[:port1]SPACEhost2[:port2]SPACEhostN[:portN]
   where SPACE is a single space (0x20) character
   for openldap, we have to convert this to a string like this:
   PROTO://host1[:port1]/SPACEPROTO://host2[:port2]/SPACEPROTO://hostN[:portN]/
   where PROTO is ldap or ldaps or ldapi
   if proto is NULL, assume hostname_or_uri is really a valid ldap uri
*/
static char *
convert_to_openldap_uri( const char *hostname_or_uri, int port, 
                         const char *proto )
{
    char *retstr = NULL;
    char *my_copy = NULL;
    char *start = NULL;
    char *iter = NULL;
    char *s = NULL;
    const char *brkstr = " ";

    if (!hostname_or_uri) {
	return NULL;
    }

    my_copy = dsgw_ch_strdup(hostname_or_uri);
    /* see if hostname_or_uri is an ldap uri */
    if (!proto && !PL_strncasecmp(my_copy, "ldap", 4)) {
	start = my_copy + 4;
	if ((*start == 's') || (*start == 'i')) {
	    start++;
	}
	if (!PL_strncmp(start, "://", 3)) {
	    *start = '\0';
	    proto = my_copy;
	    start += 3;
	} else {
	    dsgw_error( DSGW_ERR_LDAPINIT, NULL, DSGW_ERROPT_EXIT, 0, NULL );
	}
    } else if (!proto) {
	dsgw_error( DSGW_ERR_LDAPINIT, NULL, DSGW_ERROPT_EXIT, 0, NULL );
    } else {
	start = my_copy; /* just assume it's not a uri */
    }
	    
    for (s = ldap_utf8strtok_r(my_copy, brkstr, &iter); s != NULL;
	 s = ldap_utf8strtok_r(NULL, brkstr, &iter)) {
	char *ptr;
	int last = 0;
	/* strtok will grab the '/' at the end of the uri, if any,
	   so terminate parsing there */
	if ((ptr = strchr(s, '/'))) {
	    *ptr = '\0';
	    last = 1;
	}
	if (retstr) {
	    retstr = PR_sprintf_append(retstr, "/ %s://%s", proto, s);
	} else {
	    retstr = PR_smprintf("%s://%s", proto, s);
	}
	if (last) {
	    break;
	}
    }

    /* add the port on the last one */
    retstr = PR_sprintf_append(retstr, ":%d/", port);
    free(my_copy);
    return retstr;    
}

#define LDAP_DN		1
#define LDAP_RDN	2

#define INQUOTE		1
#define OUTQUOTE	2

static char **
mozldap_ldap_explode( const char *dn, const int notypes, const int nametype )
{
	char	*p, *q, *rdnstart, **rdns = NULL;
	size_t	plen = 0;
	int		state = 0;
	int		count = 0;
	int		startquote = 0;
	int		endquote = 0;
	int		len = 0;
	int		goteq = 0;

	if ( dn == NULL ) {
		dn = "";
	}

	while ( ldap_utf8isspace( (char *)dn )) { /* ignore leading spaces */
		++dn;
	}

	p = rdnstart = (char *) dn;
	state = OUTQUOTE;

	do {
		p += plen;
		plen = 1;
		switch ( *p ) {
		case '\\':
			if ( *++p == '\0' )
				p--;
			else
				plen = LDAP_UTF8LEN(p);
			break;
		case '"':
			if ( state == INQUOTE )
				state = OUTQUOTE;
			else
				state = INQUOTE;
			break;
		case '+': if ( nametype != LDAP_RDN ) break;
		case ';':
		case ',':
		case '\0':
			if ( state == OUTQUOTE ) {
				/*
				 * semicolon and comma are not valid RDN
				 * separators.
				 */
				if ( nametype == LDAP_RDN && 
					( *p == ';' || *p == ',' || !goteq)) {
					dsgw_charray_free( rdns );
					return NULL;
				}
				if ( (*p == ',' || *p == ';') && !goteq ) {
                                   /* If we get here, we have a case similar
				    * to <attr>=<value>,<string>,<attr>=<value>
				    * This is not a valid dn */
				    dsgw_charray_free( rdns );
				    return NULL;
				}
				goteq = 0;
				++count;
				if ( rdns == NULL ) {
					if (( rdns = (char **)dsgw_ch_malloc( 8
						 * sizeof( char *))) == NULL )
						return( NULL );
				} else if ( count >= 8 ) {
					if (( rdns = (char **)dsgw_ch_realloc(
					    (char *)rdns, (count+1) *
					    sizeof( char *))) == NULL )
						return( NULL );
				}
				rdns[ count ] = NULL;
				endquote = 0;
				if ( notypes ) {
					for ( q = rdnstart;
					    q < p && *q != '='; ++q ) {
						;
					}
					if ( q < p ) { /* *q == '=' */
						rdnstart = ++q;
					}
					if ( *rdnstart == '"' ) {
						startquote = 1;
						++rdnstart;
					}
					
					if ( (*(p-1) == '"') && startquote ) {
						endquote = 1;
						--p;
					}
				}

				len = p - rdnstart;
				if (( rdns[ count-1 ] = (char *)dsgw_ch_calloc(
				    1, len + 1 )) != NULL ) {
				    	memcpy( rdns[ count-1 ], rdnstart,
					    len );
					if ( !endquote ) {
						/* trim trailing spaces */
						while ( len > 0 &&
						    ldap_utf8isspace(
						    &rdns[count-1][len-1] )) {
							--len;
						}
					}
					rdns[ count-1 ][ len ] = '\0';
				}

				/*
				 *  Don't forget to increment 'p' back to where
				 *  it should be.  If we don't, then we will
				 *  never get past an "end quote."
				 */
				if ( endquote == 1 )
					p++;

				rdnstart = *p ? p + 1 : p;
				while ( ldap_utf8isspace( rdnstart ))
					++rdnstart;
			}
			break;
		case '=':
			if ( state == OUTQUOTE ) {
				goteq = 1;
			}
			/* FALL */
		default:
			plen = LDAP_UTF8LEN(p);
			break;
		}
	} while ( *p );

	return( rdns );
}

static char **
mozldap_ldap_explode_dn( const char *dn, const int notypes )
{
	return( mozldap_ldap_explode( dn, notypes, LDAP_DN ) );
}

static char **
mozldap_ldap_explode_rdn( const char *rdn, const int notypes )
{
	return( mozldap_ldap_explode( rdn, notypes, LDAP_RDN ) );
}

#endif /* USE_OPENLDAP */

int
dsgw_ldap_url_parse(const char *url, LDAPURLDesc **ludpp, int require_dn, int *secure)
{
    PR_ASSERT(url);
    PR_ASSERT(ludpp);
    int rc;
    const char *url_to_use = url;
#if defined(USE_OPENLDAP)
    char *urlescaped = NULL;
#endif

    if (secure) {
        *secure = 0;
    }
#if defined(USE_OPENLDAP)
    /* openldap does not support the non-standard multi host:port URLs supported
       by mozldap - so we have to fake out openldap - replace all spaces with %20 -
       replace all but the last colon with %3A
       Go to the 3rd '/' or to the end of the string (convert only the host:port part) */
    if (url) {
	char *p = strstr(url, "://");
	if (p) {
	    int foundspace = 0;
	    int coloncount = 0;
	    char *lastcolon = NULL;
	    p += 3;
	    for (; *p && (*p != '/'); p++) {
		if (*p == ' ') {
		    foundspace = 1;
		}
		if (*p == ':') {
		    coloncount++;
		    lastcolon = p;
		}
	    }
	    if (foundspace) {
		char *src = NULL, *dest = NULL;
		/* have to convert url */
		/* len * 3 is way too much, but acceptable */
		urlescaped = dsgw_ch_calloc(strlen(url) * 3, sizeof(char));
		dest = urlescaped;
		/* copy the scheme */
	        src = strstr(url, "://");
		src += 3;
		memcpy(dest, url, src-url);
		dest += (src-url);
		/* we have to convert all spaces to %20 - we have to convert
		   all colons except the last one to %3A */
		for (; *src; ++src) {
		    if (src < p) {
			if (*src == ' ') {
			    memcpy(dest, "%20", 3);
			    dest += 3;
			} else if ((coloncount > 1) && (*src == ':') && (src != lastcolon)) {
			    memcpy(dest, "%3A", 3);
			    dest += 3;
			} else {
			    *dest++ = *src;
			}
		    } else {
			*dest++ = *src;
		    }
		}
		*dest = '\0';
		url_to_use = urlescaped;
	    }
	}
    }
#endif

#if defined(HAVE_LDAP_URL_PARSE_NO_DEFAULTS)
    rc = ldap_url_parse_no_defaults(url_to_use, ludpp, require_dn);
    if (!rc && *ludpp && secure) {
        *secure = (*ludpp)->lud_options & LDAP_URL_OPT_SECURE;
    }
#else /* openldap */
#if defined(HAVE_LDAP_URL_PARSE_EXT) && defined(LDAP_PVT_URL_PARSE_NONE) && defined(LDAP_PVT_URL_PARSE_NOEMPTY_DN)
    rc = ldap_url_parse_ext(url_to_use, ludpp, require_dn ? LDAP_PVT_URL_PARSE_NONE : LDAP_PVT_URL_PARSE_NOEMPTY_DN);
#else
    rc = ldap_url_parse(url_to_use, ludpp);
    if ((rc || !*ludpp) && !require_dn) { /* failed - see if failure was due to missing dn */
        size_t len = strlen(url_to_use);
        /* assume the url is just scheme://host:port[/] - add the empty string
           as the DN (adding a trailing / first if needed) and try to parse
           again
        */
        char *urlcopy = PR_smprintf("%s%s%s", url_to_use, (url_to_use[len-1] == '/' ? "" : "/"), "");
        if (*ludpp) {
            ldap_free_urldesc(*ludpp); /* free the old one, if any */
        }
        rc = ldap_url_parse(urlcopy, ludpp);
        free(urlcopy);
        if (0 == rc) { /* only problem was the DN - free it */
            free(((*ludpp)->lud_dn));
        }
    }
#endif
    if (!rc && *ludpp && secure) {
        *secure = (*ludpp)->lud_scheme && !strcmp((*ludpp)->lud_scheme, "ldaps");
    }
#endif /* openldap */

#if defined(USE_OPENLDAP)
    if (urlescaped && (*ludpp) && (*ludpp)->lud_host) {
	/* have to unescape lud_host - can unescape in place */
	char *p = strstr((*ludpp)->lud_host, "://");
	if (p) {
	    char *dest = NULL;
	    p += 3;
	    dest = p;
	    /* up to the first '/', unescape the host */
	    for (; *p && (*p != '/'); p++) {
		if (!strncmp(p, "%20", 3)) {
		    *dest++ = ' ';
		    p += 2;
		} else if (!strncmp(p, "%3A", 3)) {
		    *dest++ = ':';
		    p += 2;
		} else {
		    *dest++ = *p;
		}
	    }
	    /* just copy the remainder of the host, if any */
	    while (*p) {
		*dest++ = *p++;
	    }
	    *dest = '\0';
	}
    }
    free(urlescaped);

#endif
    if ( *ludpp && ((*ludpp)->lud_scope == -1) ) {
	(*ludpp)->lud_scope = LDAP_SCOPE_BASE;
    }
    if ( *ludpp && (*ludpp)->lud_dn && (*((*ludpp)->lud_dn) == '\0') ) {
	(*ludpp)->lud_dn = NULL;
    }
    return rc;
}

char **
dsgw_ldap_explode_rdn( const char *rdn, int notypes )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_explode_rdn( rdn, notypes );
#else
    return ldap_explode_dn( rdn, notypes );
#endif
}

char **
dsgw_ldap_explode_dn( const char *dn, int notypes )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_explode_dn( dn, notypes );
#else
    return ldap_explode_dn( dn, notypes );
#endif
}

static LDAPFiltDesc *
dsgw_ldap_init_getfilter( char *path )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_init_getfilter( path );
#else
    return ldap_init_getfilter( path );
#endif
}

static int
dsgw_ldap_set_filter_additions( LDAPFiltDesc *lfdp, char *prefix, char *suffix )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_set_filter_additions( lfdp, prefix, suffix );
#else
    return ldap_set_filter_additions( lfdp, prefix, suffix );
#endif
}

static LDAPFiltInfo *
dsgw_ldap_getfirstfilter( LDAPFiltDesc *lfdp, char *tagpat, char *value )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_getfirstfilter( lfdp, tagpat, value );
#else
    return ldap_getfirstfilter( lfdp, tagpat, value );
#endif
}

static LDAPFiltInfo *
dsgw_ldap_getnextfilter( LDAPFiltDesc *lfdp )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_getnextfilter( lfdp );
#else
    return ldap_getnextfilter( lfdp );
#endif
}

int 
dsgw_ldap_create_filter( char *filtbuf, unsigned long buflen, 
                         char *pattern, char *prefix, char *suffix, 
                         char *attr, char *value, char **valwords )
{
#if defined(USE_OPENLDAP)
    return mozldap_ldap_create_filter( filtbuf, buflen, pattern, prefix, 
                                       suffix, attr, value, valwords );
#else
    return ldap_create_filter( filtbuf, buflen, pattern, prefix, suffix, 
                               attr, value, valwords );
#endif
}

int
dsgw_ldap_get_lderrno(LDAP *ld, char **m, char **s)
{
    int rc = LDAP_SUCCESS;

#if defined(USE_OPENLDAP)
    ldap_get_option(ld, LDAP_OPT_RESULT_CODE, &rc);
    if (m) {
        ldap_get_option(ld, LDAP_OPT_MATCHED_DN, m);
    }
    if (s) {
#ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
        ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, s);
#else
        ldap_get_option(ld, LDAP_OPT_ERROR_STRING, s);
#endif
    }
#else /* !USE_OPENLDAP */
    rc = ldap_get_lderrno( ld, m, s );
#endif
    return rc;
}

char **
dsgw_ldap_get_values(LDAP *ld, LDAPMessage *entry, const char *attrtype)
{
#if defined(USE_OPENLDAP)
    struct berval **bvals = NULL;
    char **vals = NULL;
    int ii;

    bvals = ldap_get_values_len(ld, entry, attrtype);

    if (!bvals) {
        return vals;
    }

    for (ii = 0; bvals[ii]; ++ii);
    vals = (char **)dsgw_ch_malloc((ii + 1) * sizeof(char *));
    for (ii = 0; vals && bvals && bvals[ii]; ++ii) {
        vals[ii] = PL_strndup(bvals[ii]->bv_val, bvals[ii]->bv_len);
    }
    ldap_value_free_len(bvals);
    if (vals) {
        vals[ii] = NULL;
    }
    return vals;
#else
    return ldap_get_values(ld, entry, attrtype);
#endif
}

typedef int (VOIDCMP_CALLBACK)(const void*, const void*);
int
dsgw_sort_values(
    struct berval	**vals,
    DSGW_VALCMP_CALLBACK *cmp
)
{
    int nel;

    if (!vals) {
	return 0;
    }

    for ( nel = 0; vals[nel] != NULL; nel++ )
	;	/* NULL */

    qsort(vals, nel, sizeof(struct berval *), (VOIDCMP_CALLBACK *)cmp);

    return 0;
}

char *
dsgw_ldap_dn2ufn(const char *dn)
{
#if defined(USE_OPENLDAP)
    char *retval = ldap_dn2ufn(dn);
    if (!retval) {
	retval = strdup("");
    }
    return retval;
#else
    return ldap_dn2ufn(dn);
#endif
}

#if defined(USE_OPENLDAP)
static LDAPFiltDesc *
mozldap_ldap_init_getfilter( char *fname )
{
    FILE		*fp;
    char		*buf;
    long		rlen, len;
    int 		eof;
    LDAPFiltDesc	*lfdp;

    if (( fp = fopen( fname, "r" )) == NULL ) {
	return( NULL );
    }

    if ( fseek( fp, 0L, SEEK_END ) != 0 ) {	/* move to end to get len */
	fclose( fp );
	return( NULL );
    }

    len = ftell( fp );

    if ( fseek( fp, 0L, SEEK_SET ) != 0 ) {	/* back to start of file */
	fclose( fp );
	return( NULL );
    }

    if (( buf = dsgw_ch_malloc( (size_t)len )) == NULL ) {
	fclose( fp );
	return( NULL );
    }

    rlen = fread( buf, 1, (size_t)len, fp );
    eof = feof( fp );
    fclose( fp );

    if ( rlen != len && !eof ) {	/* error:  didn't get the whole file */
	free( buf );
	return( NULL );
    }


    lfdp = mozldap_ldap_init_getfilter_buf( buf, rlen );
    free( buf );

    return( lfdp );
}

static LDAPFiltDesc *
mozldap_ldap_init_getfilter_buf( char *buf, long buflen )
{
    LDAPFiltDesc	*lfdp;
    LDAPFiltList	*flp, *nextflp;
    LDAPFiltInfo	*fip, *nextfip;
    char		*errmsg, *tag, **tok;
    int			tokcnt, i;

    if ( (buf == NULL) || (buflen < 0) ||
	 ( lfdp = (LDAPFiltDesc *)dsgw_ch_calloc(1, sizeof(LDAPFiltDesc)))
	 == NULL ) {
	return( NULL );
    }

    flp = nextflp = NULL;
    fip = NULL;
    tag = NULL;

    while ( buflen > 0 && ( tokcnt = nsldapi_next_line_tokens( &buf, &buflen,
	    &tok )) > 0 ) {
	switch( tokcnt ) {
	case 1:		/* tag line */
	    if ( tag != NULL ) {
		free( tag );
	    }
	    tag = tok[ 0 ];
	    free( tok );
	    break;
	case 4:
	case 5:		/* start of filter info. list */
	    if (( nextflp = (LDAPFiltList *)dsgw_ch_calloc( 1,
		    sizeof( LDAPFiltList ))) == NULL ) {
		mozldap_ldap_getfilter_free( lfdp );
		return( NULL );
	    }
	    nextflp->lfl_tag = dsgw_ch_strdup( tag );
	    nextflp->lfl_pattern = tok[ 0 ];
	    if (( errmsg = re_comp( nextflp->lfl_pattern )) != NULL ) {
		mozldap_ldap_getfilter_free( lfdp );
		dsgw_charray_free( tok );
		return( NULL );
	    }
		
	    nextflp->lfl_delims = tok[ 1 ];
	    nextflp->lfl_ilist = NULL;
	    nextflp->lfl_next = NULL;
	    if ( flp == NULL ) {	/* first one */
		lfdp->lfd_filtlist = nextflp;
	    } else {
		flp->lfl_next = nextflp;
	    }
	    flp = nextflp;
	    fip = NULL;
	    for ( i = 2; i < 5; ++i ) {
		tok[ i - 2 ] = tok[ i ];
	    }
	    /* fall through */

	case 2:
	case 3:		/* filter, desc, and optional search scope */
	    if ( nextflp != NULL ) { /* add to info list */
		if (( nextfip = (LDAPFiltInfo *)dsgw_ch_calloc( 1,
			sizeof( LDAPFiltInfo ))) == NULL ) {
		    mozldap_ldap_getfilter_free( lfdp );
		    dsgw_charray_free( tok );
		    return( NULL );
		}
		if ( fip == NULL ) {	/* first one */
		    nextflp->lfl_ilist = nextfip;
		} else {
		    fip->lfi_next = nextfip;
		}
		fip = nextfip;
		nextfip->lfi_next = NULL;
		nextfip->lfi_filter = tok[ 0 ];
		nextfip->lfi_desc = tok[ 1 ];
		if ( tok[ 2 ] != NULL ) {
		    if ( strcasecmp( tok[ 2 ], "subtree" ) == 0 ) {
			nextfip->lfi_scope = LDAP_SCOPE_SUBTREE;
		    } else if ( strcasecmp( tok[ 2 ], "onelevel" ) == 0 ) {
			nextfip->lfi_scope = LDAP_SCOPE_ONELEVEL;
		    } else if ( strcasecmp( tok[ 2 ], "base" ) == 0 ) {
			nextfip->lfi_scope = LDAP_SCOPE_BASE;
		    } else {
			dsgw_charray_free( tok );
			mozldap_ldap_getfilter_free( lfdp );
			return( NULL );
		    }
		    free( tok[ 2 ] );
		    tok[ 2 ] = NULL;
		} else {
		    nextfip->lfi_scope = LDAP_SCOPE_SUBTREE;	/* default */
		}
		nextfip->lfi_isexact = ( strchr( tok[ 0 ], '*' ) == NULL &&
			strchr( tok[ 0 ], '~' ) == NULL );
		free( tok );
	    }
	    break;

	default:
	    dsgw_charray_free( tok );
	    mozldap_ldap_getfilter_free( lfdp );
	    return( NULL );
	}
    }

    if ( tag != NULL ) {
	free( tag );
    }

    return( lfdp );
}

static void
mozldap_ldap_getfilter_free( LDAPFiltDesc *lfdp )
{
    LDAPFiltList	*flp, *nextflp;
    LDAPFiltInfo	*fip, *nextfip;

    if ( lfdp == NULL ) {
	return;
    }

    for ( flp = lfdp->lfd_filtlist; flp != NULL; flp = nextflp ) {
	for ( fip = flp->lfl_ilist; fip != NULL; fip = nextfip ) {
	    nextfip = fip->lfi_next;
	    free( fip->lfi_filter );
	    free( fip->lfi_desc );
	    free( fip );
	}
	nextflp = flp->lfl_next;
	free( flp->lfl_pattern );
	free( flp->lfl_delims );
	free( flp->lfl_tag );
	free( flp );
    }

    if ( lfdp->lfd_curval != NULL ) {
	free( lfdp->lfd_curval );
    }
    if ( lfdp->lfd_curvalcopy != NULL ) {
	free( lfdp->lfd_curvalcopy );
    }
    if ( lfdp->lfd_curvalwords != NULL ) {
	free( lfdp->lfd_curvalwords );
    }
    if ( lfdp->lfd_filtprefix != NULL ) {
	free( lfdp->lfd_filtprefix );
    }
    if ( lfdp->lfd_filtsuffix != NULL ) {
	free( lfdp->lfd_filtsuffix );
    }

    free( lfdp );
}

int
mozldap_ldap_set_filter_additions( LDAPFiltDesc *lfdp, 
                                   char *prefix, char *suffix )
{
    if ( lfdp == NULL ) {
	return( LDAP_PARAM_ERROR );
    }

    if ( lfdp->lfd_filtprefix != NULL ) {
	free( lfdp->lfd_filtprefix );
    }
    lfdp->lfd_filtprefix = ( prefix == NULL ) ? NULL : dsgw_ch_strdup( prefix );

    if ( lfdp->lfd_filtsuffix != NULL ) {
	free( lfdp->lfd_filtsuffix );
    }
    lfdp->lfd_filtsuffix = ( suffix == NULL ) ? NULL : dsgw_ch_strdup( suffix );

    return( LDAP_SUCCESS );
}

LDAPFiltInfo *
mozldap_ldap_getfirstfilter( LDAPFiltDesc *lfdp, char *tagpat, char *value )
{
    LDAPFiltList	*flp;

    if ( lfdp == NULL || tagpat == NULL || value == NULL ) {
	return( NULL );	/* punt */
    }

    if ( lfdp->lfd_curvalcopy != NULL ) {
	free( lfdp->lfd_curvalcopy );
	free( lfdp->lfd_curvalwords );
    }

    free(lfdp->lfd_curval);
    if ((lfdp->lfd_curval = dsgw_ch_strdup(value)) == NULL) {
	return( NULL );
    }

    lfdp->lfd_curfip = NULL;

    for ( flp = lfdp->lfd_filtlist; flp != NULL; flp = flp->lfl_next ) {
	if ( re_comp( tagpat ) == NULL && re_exec( flp->lfl_tag ) == 1
		&& re_comp( flp->lfl_pattern ) == NULL
		&& re_exec( lfdp->lfd_curval ) == 1 ) {
	    lfdp->lfd_curfip = flp->lfl_ilist;
	    break;
	}
    }

    if ( lfdp->lfd_curfip == NULL ) {
	return( NULL );
    }

    if (( lfdp->lfd_curvalcopy = dsgw_ch_strdup( value )) == NULL ) {
	return( NULL );
    }

    if ( break_into_words( lfdp->lfd_curvalcopy, flp->lfl_delims,
		&lfdp->lfd_curvalwords ) < 0 ) {
	free( lfdp->lfd_curvalcopy );
	lfdp->lfd_curvalcopy = NULL;
	return( NULL );
    }

    return( mozldap_ldap_getnextfilter( lfdp ));
}


LDAPFiltInfo *
mozldap_ldap_getnextfilter( LDAPFiltDesc *lfdp )
{
    LDAPFiltInfo	*fip;

    if ( lfdp == NULL || ( fip = lfdp->lfd_curfip ) == NULL ) {
	return( NULL );
    }

    lfdp->lfd_curfip = fip->lfi_next;

    mozldap_ldap_create_filter( lfdp->lfd_filter, LDAP_FILT_MAXSIZ, 
	    fip->lfi_filter, lfdp->lfd_filtprefix, lfdp->lfd_filtsuffix, 
	    NULL, lfdp->lfd_curval, lfdp->lfd_curvalwords );
    lfdp->lfd_retfi.lfi_filter = lfdp->lfd_filter;
    lfdp->lfd_retfi.lfi_desc = fip->lfi_desc;
    lfdp->lfd_retfi.lfi_scope = fip->lfi_scope;
    lfdp->lfd_retfi.lfi_isexact = fip->lfi_isexact;

    return( &lfdp->lfd_retfi );
}

int
mozldap_ldap_create_filter( char *filtbuf, unsigned long buflen, char *pattern,
	char *prefix, char *suffix, char *attr, char *value, char **valwords )
{
	char	*p, *f, *flimit;
	int	i, wordcount, wordnum, endwordnum, escape_all;

    /* 
     * there is some confusion on what to create for a filter if 
     * attr or value are null pointers.  For now we just leave them
     * as TO BE DEALT with
     */

	if ( filtbuf == NULL || buflen == 0 || pattern == NULL ){
		return( LDAP_PARAM_ERROR );
	}
	
	if ( valwords == NULL ) {
	    wordcount = 0;
	} else {
	    for ( wordcount = 0; valwords[ wordcount ] != NULL; ++wordcount ) {
		;
	    }
	}

	f = filtbuf;
	flimit = filtbuf + buflen - 1;

	if ( prefix != NULL ) {
	    f = filter_add_strn( f, flimit, prefix, strlen( prefix ));
	}

	for ( p = pattern; f != NULL && *p != '\0'; ++p ) {
	    if ( *p == '%' ) {
		++p;
		if ( *p == 'v' || *p == 'e' ) {
		    escape_all = ( *p == 'e' );
		    if ( ldap_utf8isdigit( p+1 )) {
			++p;
			wordnum = *p - '1';
			if ( *(p+1) == '-' ) {
			    ++p;
			    if ( ldap_utf8isdigit( p+1 )) {
				++p;
				endwordnum = *p - '1';	/* e.g., "%v2-4" */
				if ( endwordnum > wordcount - 1 ) {
				    endwordnum = wordcount - 1;
				}
			    } else {
				endwordnum = wordcount - 1;  /* e.g., "%v2-" */
			    }
			} else {
			    endwordnum = wordnum;	/* e.g., "%v2" */
			}

			if ( wordcount > 0 ) {
			    for ( i = wordnum; i <= endwordnum; ++i ) {
				if ( i > wordnum ) {  /* add blank btw words */
				    f = filter_add_strn( f, flimit, " ", 1 );
				    if ( f == NULL ) break;
				}
				f = filter_add_value( f, flimit, valwords[ i ],
					escape_all );
				if ( f == NULL ) break;
			    }
			}
		    } else if ( *(p+1) == '$' ) {
			++p;
			if ( wordcount > 0 ) {
			    wordnum = wordcount - 1;
			    f = filter_add_value( f, flimit,
				    valwords[ wordnum ], escape_all );
			}
		    } else if ( value != NULL ) {
			f = filter_add_value( f, flimit, value, escape_all );
		    }
		} else if ( *p == 'a' && attr != NULL ) {
		    f = filter_add_strn( f, flimit, attr, strlen( attr ));
		} else {
		    *f++ = *p;
		}
	    } else {
		*f++ = *p;
	    }
	    if ( f > flimit ) { /* overflow */
		f = NULL;
	    }
	}

	if ( suffix != NULL && f != NULL) {
	    f = filter_add_strn( f, flimit, suffix, strlen( suffix ));
	}

	if ( f == NULL ) {
	    *flimit = '\0';
	    return( LDAP_SIZELIMIT_EXCEEDED );
	}
	*f = '\0';
	return( LDAP_SUCCESS );
}

static int
break_into_words( char *str, char *delims, char ***wordsp )
{
    char	*word, **words;
    int		count;
    char	*lasts;
	
    if (( words = (char **)dsgw_ch_calloc( 1, sizeof( char * ))) == NULL ) {
	return( -1 );
    }
    count = 0;
    words[ count ] = NULL;

    word = ldap_utf8strtok_r( str, delims, &lasts );
    while ( word != NULL ) {
	if (( words = (char **)dsgw_ch_realloc( words,
		( count + 2 ) * sizeof( char * ))) == NULL ) {
	    return( -1 );
	}

	words[ count ] = word;
	words[ ++count ] = NULL;
	word = ldap_utf8strtok_r( NULL, delims, &lasts );
    }
	
    *wordsp = words;
    return( count );
}

static char*
filter_add_strn( char *f, char *flimit, char *v, size_t vlen )
     /* Copy v into f.  If flimit is too small, return NULL;
      * otherwise return (f + vlen).
      */
{
    auto size_t flen = flimit - f;
    if ( vlen > flen ) { /* flimit is too small */
	if ( flen > 0 ) memmove( f, v, flen );
	return NULL;
    }
    if ( vlen > 0 ) memmove( f, v, vlen );
    return f + vlen;
}

static char*
filter_add_value( char *f, char *flimit, char *v, int escape_all )
     /* Copy v into f, but with parentheses escaped.  But only escape * and \
      * if escape_all is non-zero so that either "*" or "\2a" can be used in
      * v, with different meanings.
      * If flimit is too small, return NULL; otherwise
      * return (f + the number of bytes copied).
      */
{
    auto char x[4];
    auto size_t slen;
    while ( f && *v ) {
	switch ( *v ) {
	case '*':
	    if ( escape_all ) {
		f = filter_add_strn( f, flimit, "\\2a", 3 );
		v++;
	    } else {
		if ( f < flimit ) {
		    *f++ = *v++;
		} else {
		    f = NULL; /* overflow */
		}
	    }
	    break;

	case '(':
	case ')':
	    sprintf( x, "\\%02x", (unsigned)*v );
	    f = filter_add_strn( f, flimit, x, 3 );
	    v++;
	    break;

	case '\\':
	    if ( escape_all ) {
		f = filter_add_strn( f, flimit, "\\5c", 3 );
		v++;
	    } else {
		slen = (ldap_utf8isxdigit( v+1 ) &&
			ldap_utf8isxdigit( v+2 )) ? 3 : (v[1] ? 2 : 1);
		f = filter_add_strn( f, flimit, v, slen );
		v += slen;
	    }
	    break;
	    
	default:
	    if ( f < flimit ) {
		*f++ = *v++;
	    } else {
		f = NULL; /* overflow */
	    }
	    break;
	}
    }
    return f;
}

#endif

/*
  emacs settings
  Local Variables:
  indent-tabs-mode: t
  tab-width: 8
  End:
*/