aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/sasl/plugins/digestmd5.c
blob: 59f87135f68614c554596ce54225267b66771023 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
/* DIGEST-MD5 SASL plugin
 * Ken Murchison
 * Rob Siemborski
 * Tim Martin
 * Alexey Melnikov 
 */
/* 
 * Copyright (c) 1998-2016 Carnegie Mellon University.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The name "Carnegie Mellon University" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For permission or any other legal
 *    details, please contact  
 *      Carnegie Mellon University
 *      Center for Technology Transfer and Enterprise Creation
 *      4615 Forbes Avenue
 *      Suite 302
 *      Pittsburgh, PA  15213
 *      (412) 268-7393, fax: (412) 268-7395
 *      innovation@andrew.cmu.edu
 *
 * 4. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by Computing Services
 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
 *
 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <config.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef macintosh
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include <fcntl.h>
#include <ctype.h>

/* DES support */
#ifdef WITH_DES
# ifdef WITH_SSL_DES
#  include <openssl/des.h>
#  include <openssl/opensslv.h>
#  if (OPENSSL_VERSION_NUMBER >= 0x0090700f) && \
      !defined(OPENSSL_ENABLE_OLD_DES_SUPPORT)
#   define des_cblock DES_cblock
#   define des_key_schedule DES_key_schedule
#   define des_key_sched(k,ks) \
           DES_key_sched((k),&(ks))
#   define des_cbc_encrypt(i,o,l,k,iv,e) \
           DES_cbc_encrypt((i),(o),(l),&(k),(iv),(e))
#   define des_ede2_cbc_encrypt(i,o,l,k1,k2,iv,e) \
           DES_ede2_cbc_encrypt((i),(o),(l),&(k1),&(k2),(iv),(e))
#  endif /* OpenSSL 0.9.7+ w/o old DES support */
# else /* system DES library */
#ifdef HAVE_DES_H
#  error #include <des.h>
#endif
# endif
#endif /* WITH_DES */

#ifdef WIN32
# include <winsock2.h>
#else /* Unix */
# include <netinet/in.h>
#endif /* WIN32 */

#include <sasl.h>
#include <saslplug.h>

#include "plugin_common.h"

#ifndef WIN32
extern int strcasecmp(const char *s1, const char *s2);
#endif /* end WIN32 */

#ifdef macintosh
#error #include <sasl_md5_plugin_decl.h>
#endif

/* external definitions */

#define bool int

#ifndef TRUE
#define TRUE  (1)
#define FALSE (0)
#endif

/* MAX_UIN32_DIV_10 * 10 + MAX_UIN32_MOD_10 == 2^32-1 == 4294967295 */
#define MAX_UIN32_DIV_10    429496729
#define MAX_UIN32_MOD_10    5

#define DEFAULT_BUFSIZE	    0xFFFF
#define MAX_SASL_BUFSIZE    0xFFFFFF

/*****************************  Common Section  *****************************/

/* Definitions */
#define NONCE_SIZE (32)		/* arbitrary */

/* Layer Flags */
#define DIGEST_NOLAYER    (1)
#define DIGEST_INTEGRITY  (2)
#define DIGEST_PRIVACY    (4)

/* defines */
#define HASHLEN 16
typedef unsigned char HASH[HASHLEN + 1];
#define HASHHEXLEN 32
typedef unsigned char HASHHEX[HASHHEXLEN + 1];

#define MAC_SIZE 10
#define MAC_OFFS 2

const char *SEALING_CLIENT_SERVER="Digest H(A1) to client-to-server sealing key magic constant";
const char *SEALING_SERVER_CLIENT="Digest H(A1) to server-to-client sealing key magic constant";

const char *SIGNING_CLIENT_SERVER="Digest session key to client-to-server signing key magic constant";
const char *SIGNING_SERVER_CLIENT="Digest session key to server-to-client signing key magic constant";

#define HT	(9)
#define CR	(13)
#define LF	(10)
#define SP	(32)
#define DEL	(127)

#define NEED_ESCAPING	"\"\\"

#define REALM_CHAL_PREFIX	"Available realms:"

static char *quote (char *str);

struct context;

/* function definitions for cipher encode/decode */
typedef int cipher_function_t(struct context *,
			      const char *,
			      unsigned,
			      unsigned char[],
			      char *,
			      unsigned *);

typedef int cipher_init_t(struct context *, unsigned char [16], 
                                            unsigned char [16]);
typedef void cipher_free_t(struct context *);

enum Context_type { SERVER = 0, CLIENT = 1 };

typedef struct cipher_context cipher_context_t;

/* cached auth info used for fast reauth */
typedef struct reauth_entry {
    char *authid;
    char *realm;
    unsigned char *nonce;
    unsigned int nonce_count;
    unsigned char *cnonce;

    union {
	struct {
	    time_t timestamp;
	} s; /* server stuff */

	struct {
	    char *serverFQDN;
	    int protection;
	    struct digest_cipher *cipher;
	    unsigned long server_maxbuf;

	    /* for HTTP mode (RFC 2617) only */
	    char *algorithm;
	    unsigned char *opaque;
	} c; /* client stuff */
    } u;
} reauth_entry_t;

typedef struct reauth_cache {
    /* static stuff */
    enum Context_type i_am;	/* are we the client or server? */
    time_t timeout;
    void *mutex;
    unsigned size;

    reauth_entry_t *e;		/* fixed-size hash table of entries */
} reauth_cache_t;

/* global context for reauth use */
typedef struct digest_glob_context { 
   reauth_cache_t *reauth; 
} digest_glob_context_t;

/* context that stores info */
typedef struct context {
    int state;			/* state in the authentication we are in */
    enum Context_type i_am;	/* are we the client or server? */
    int http_mode;    		/* use RFC 2617 compatible protocol? */
    
    reauth_cache_t *reauth;

    char *authid;
    char *realm;
    unsigned char *nonce;
    unsigned int nonce_count;
    unsigned char *cnonce;

    /* only used by the client */
    char ** realms;
    int realm_cnt;

    char *response_value;
    
    unsigned int seqnum;
    unsigned int rec_seqnum;	/* for checking integrity */
    
    HASH Ki_send;
    HASH Ki_receive;
    
    HASH HA1;			/* Kcc or Kcs */
    
    /* copy of utils from the params structures */
    const sasl_utils_t *utils;
    
    /* For general use */
    char *out_buf;
    unsigned out_buf_len;
    
    /* for encoding/decoding */
    buffer_info_t *enc_in_buf;
    char *encode_buf, *decode_buf, *decode_packet_buf;
    unsigned encode_buf_len, decode_buf_len, decode_packet_buf_len;

    decode_context_t decode_context;

    /* if privacy mode is used use these functions for encode and decode */
    cipher_function_t *cipher_enc;
    cipher_function_t *cipher_dec;
    cipher_init_t *cipher_init;
    cipher_free_t *cipher_free;
    struct cipher_context *cipher_enc_context;
    struct cipher_context *cipher_dec_context;
} context_t;

struct digest_cipher {
    char *name;
    sasl_ssf_t ssf;
    int n; /* bits to make privacy key */
    int flag; /* a bitmask to make things easier for us */
    
    cipher_function_t *cipher_enc;
    cipher_function_t *cipher_dec;
    cipher_init_t *cipher_init;
    cipher_free_t *cipher_free;
};
#if 0
static const unsigned char *COLON = ":";
#else
static const unsigned char COLON[] = { ':', '\0' };
#endif
/* Hashes a string to produce an unsigned short */
static unsigned hash(const char *str)
{
    unsigned val = 0;
    int i;

    while (str && *str) {
	i = (int) *str;
	val ^= i;
	val <<= 1;
	str++;
    }

    return val;
}

static void CvtHex(HASH Bin, HASHHEX Hex)
{
    unsigned short  i;
    unsigned char   j;
    
    for (i = 0; i < HASHLEN; i++) {
	j = (Bin[i] >> 4) & 0xf;
	if (j <= 9)
	    Hex[i * 2] = (j + '0');
	else
	    Hex[i * 2] = (j + 'a' - 10);
	j = Bin[i] & 0xf;
	if (j <= 9)
	    Hex[i * 2 + 1] = (j + '0');
	else
	    Hex[i * 2 + 1] = (j + 'a' - 10);
    }
    Hex[HASHHEXLEN] = '\0';
}

/*
 * calculate request-digest/response-digest as per HTTP Digest spec
 */
void
DigestCalcResponse(const sasl_utils_t * utils,
		   HASHHEX HA1,	/* HEX(H(A1)) */
		   unsigned char *pszNonce,	/* nonce from server */
		   unsigned int pszNonceCount,	/* 8 hex digits */
		   unsigned char *pszCNonce,	/* client nonce */
		   unsigned char *pszQop,	/* qop-value: "", "auth",
						 * "auth-int" */
		   unsigned char *pszDigestUri,	/* requested URL */
		   unsigned char *pszMethod,
		   HASHHEX HEntity,	/* H(entity body) if qop="auth-int" */
		   HASHHEX Response	/* request-digest or response-digest */
    )
{
    MD5_CTX         Md5Ctx;
    HASH            HA2;
    HASH            RespHash;
    HASHHEX         HA2Hex;
    unsigned char ncvalue[10];
    
    /* calculate H(A2) */
    utils->MD5Init(&Md5Ctx);
    
    if (pszMethod != NULL) {
	utils->MD5Update(&Md5Ctx, pszMethod, (unsigned) strlen((char *) pszMethod));
    }
    utils->MD5Update(&Md5Ctx, (unsigned char *) COLON, 1);
    
    /* utils->MD5Update(&Md5Ctx, (unsigned char *) "AUTHENTICATE:", 13); */
    utils->MD5Update(&Md5Ctx, pszDigestUri, (unsigned) strlen((char *) pszDigestUri));
    if (strcasecmp((char *) pszQop, "auth") != 0) {
	/* append ":00000000000000000000000000000000" */
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
    }
    utils->MD5Final(HA2, &Md5Ctx);
    CvtHex(HA2, HA2Hex);
    
    /* calculate response */
    utils->MD5Init(&Md5Ctx);
    utils->MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
    utils->MD5Update(&Md5Ctx, COLON, 1);
    utils->MD5Update(&Md5Ctx, pszNonce, (unsigned) strlen((char *) pszNonce));
    utils->MD5Update(&Md5Ctx, COLON, 1);
    if (*pszQop) {
	sprintf((char *)ncvalue, "%08x", pszNonceCount);
	utils->MD5Update(&Md5Ctx, ncvalue, (unsigned) strlen((char *)ncvalue));
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, pszCNonce, (unsigned) strlen((char *) pszCNonce));
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, pszQop, (unsigned) strlen((char *) pszQop));
	utils->MD5Update(&Md5Ctx, COLON, 1);
    }
    utils->MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
    utils->MD5Final(RespHash, &Md5Ctx);
    CvtHex(RespHash, Response);
}

static bool UTF8_In_8859_1(const unsigned char *base, size_t len)
{
    const unsigned char *scan, *end;
    
    end = base + len;
    for (scan = base; scan < end; ++scan) {
	if (*scan > 0xC3)
	    break;			/* abort if outside 8859-1 */
	if (*scan >= 0xC0 && *scan <= 0xC3) {
	    if (++scan == end || *scan < 0x80 || *scan > 0xBF)
		break;
	}
    }
    
    /* if scan >= end, then this is a 8859-1 string. */
    return (scan >= end);
}

/*
 * if the string is entirely in the 8859-1 subset of UTF-8, then translate to
 * 8859-1 prior to MD5
 */
static void MD5_UTF8_8859_1(const sasl_utils_t * utils,
			    MD5_CTX * ctx,
			    bool In_ISO_8859_1,
			    const unsigned char *base,
			    int len)
{
    const unsigned char *scan, *end;
    unsigned char   cbuf;
    
    end = base + len;
    
    /* if we found a character outside 8859-1, don't alter string */
    if (!In_ISO_8859_1) {
	utils->MD5Update(ctx, base, len);
	return;
    }
    /* convert to 8859-1 prior to applying hash */
    do {
	for (scan = base; scan < end && *scan < 0xC0; ++scan);
	if (scan != base)
	    utils->MD5Update(ctx, base, (unsigned) (scan - base));
	if (scan + 1 >= end)
	    break;
	cbuf = ((scan[0] & 0x3) << 6) | (scan[1] & 0x3f);
	utils->MD5Update(ctx, &cbuf, 1);
	base = scan + 2;
    }
    while (base < end);
}

/**
 * Returns true if it mangled the username.
 */
static bool DigestCalcSecret(const sasl_utils_t * utils,
		            unsigned char *pszUserName,
		            unsigned char *pszRealm,
		            unsigned char *Password,
		            int PasswordLen,
		            bool Ignore_8859,
		            HASH HA1)
{
    bool            In_8859_1;
    bool            Any_8859_1 = FALSE;
    MD5_CTX         Md5Ctx;
    
    /* Chris Newman clarified that the following text in DIGEST-MD5 spec
       is bogus: "if name and password are both in ISO 8859-1 charset"
       We shoud use code example instead */
    
    utils->MD5Init(&Md5Ctx);
    
    /* We have to convert UTF-8 to ISO-8859-1 if possible */
    if (Ignore_8859 == FALSE) {
	In_8859_1 = UTF8_In_8859_1(pszUserName, strlen((char *) pszUserName));
	MD5_UTF8_8859_1(utils, &Md5Ctx, In_8859_1,
			pszUserName, (unsigned) strlen((char *) pszUserName));
	Any_8859_1 |= In_8859_1;
    } else {
	utils->MD5Update(&Md5Ctx, pszUserName, (unsigned) strlen((char *) pszUserName));
    }
    
    utils->MD5Update(&Md5Ctx, COLON, 1);
    
    /* a NULL realm is equivalent to the empty string */
    if (pszRealm != NULL && pszRealm[0] != '\0') {
	if (Ignore_8859 == FALSE) {
	    /* We have to convert UTF-8 to ISO-8859-1 if possible */
	    In_8859_1 = UTF8_In_8859_1(pszRealm, strlen((char *) pszRealm));
	    MD5_UTF8_8859_1(utils, &Md5Ctx, In_8859_1,
			    pszRealm, (unsigned) strlen((char *) pszRealm));
	    Any_8859_1 |= In_8859_1;
	} else {
	   utils->MD5Update(&Md5Ctx, pszRealm, (unsigned) strlen((char *) pszRealm));
	}
    }  
    
    utils->MD5Update(&Md5Ctx, COLON, 1);

    if (Ignore_8859 == FALSE) {
	/* We have to convert UTF-8 to ISO-8859-1 if possible */
	In_8859_1 = UTF8_In_8859_1(Password, PasswordLen);
	MD5_UTF8_8859_1(utils, &Md5Ctx, In_8859_1,
			Password, PasswordLen);
	Any_8859_1 |= In_8859_1;
    } else {
	utils->MD5Update(&Md5Ctx, Password, PasswordLen);
    }
    utils->MD5Final(HA1, &Md5Ctx);

    return Any_8859_1;
}

static unsigned char *create_nonce(const sasl_utils_t * utils)
{
    unsigned char  *base64buf;
    int             base64len;
    
    char           *ret = (char *) utils->malloc(NONCE_SIZE);
    if (ret == NULL)
	return NULL;
    
    utils->rand(utils->rpool, (char *) ret, NONCE_SIZE);
    
    /* base 64 encode it so it has valid chars */
    base64len = (NONCE_SIZE * 4 / 3) + (NONCE_SIZE % 3 ? 4 : 0);
    
    base64buf = (unsigned char *) utils->malloc(base64len + 1);
    if (base64buf == NULL) {
	utils->seterror(utils->conn, 0, "Unable to allocate final buffer");
	return NULL;
    }
    
    /*
     * Returns SASL_OK on success, SASL_BUFOVER if result won't fit
     */
    if (utils->encode64(ret, NONCE_SIZE,
			(char *) base64buf, base64len, NULL) != SASL_OK) {
	utils->free(ret);
	return NULL;
    }
    utils->free(ret);
    
    return base64buf;
}

static int add_to_challenge(const sasl_utils_t *utils,
			    char **str, unsigned *buflen, unsigned *curlen,
			    char *name,
			    unsigned char *value,
			    bool need_quotes)
{
    size_t          namesize = strlen(name);
    size_t          valuesize = strlen((char *) value);
    unsigned        newlen;
    int             ret;
    
    newlen = (unsigned) (*curlen + 1 + namesize + 2 + valuesize + 2);
    ret = _plug_buf_alloc(utils, str, buflen, newlen);
    if(ret != SASL_OK) return ret;

    if (*curlen > 0) {
	strcat(*str, ",");
	strcat(*str, name);
    } else {
	strcpy(*str, name);
    }
    
    if (need_quotes) {
	strcat(*str, "=\"");

	/* Check if the value needs quoting */
	if (strpbrk ((char *)value, NEED_ESCAPING) != NULL) {
	    char * quoted = quote ((char *) value);
	    if (quoted == NULL)
		MEMERROR(utils);
	    valuesize = strlen(quoted);
	    /* As the quoted string is bigger, make sure we have enough
	       space now */
	    ret = _plug_buf_alloc(utils, str, buflen, newlen);
	    if (ret == SASL_OK) {
		strcat(*str, quoted);
		free (quoted);
	    } else {
		free (quoted);
		return ret;
	    }
	} else {
	    strcat(*str, (char *) value);
	}
	strcat(*str, "\"");
    } else {
	strcat(*str, "=");
	strcat(*str, (char *) value);
    }
    
    *curlen = newlen;
    return SASL_OK;
}

static int is_lws_char (char c)
{
    return (c == ' ' || c == HT || c == CR || c == LF);
}

static char *skip_lws (char *s)
{
    if (!s) return NULL;
    
    /* skipping spaces: */
    while (is_lws_char(s[0])) {
	if (s[0] == '\0') break;
	s++;
    }  
    
    return s;
}

/* Same as skip_lws, but do this right to left */
/* skip LWSP at the end of the value (if any), skip_r_lws returns pointer to
   the first LWSP character, NUL (if there were none) or NULL if the value
   is entirely from LWSP characters */
static char *skip_r_lws (char *s)
{
    char *end;
    size_t len;

    if (!s) return NULL;
    
    len = strlen(s);
    if (len == 0) return NULL;

    /* the last character before terminating NUL */
    end = s + len - 1;

    /* skipping spaces: */
    while (end > s && (end[0] == ' ' || end[0] == HT || end[0] == CR || end[0] == LF)) {
	end--;
    }  

    /* If all string from spaces, return NULL */
    if (end == s && (end[0] == ' ' || end[0] == HT || end[0] == CR || end[0] == LF)) {
	return NULL;
    } else {
	return (end + 1);
    }
}

static char *skip_token (char *s, int caseinsensitive)
{
    if(!s) return NULL;
    
    while (s[0]>SP) {
	if (s[0]==DEL || s[0]=='(' || s[0]==')' || s[0]=='<' || s[0]=='>' ||
	    s[0]=='@' || s[0]==',' || s[0]==';' || s[0]==':' || s[0]=='\\' ||
	    s[0]=='\'' || s[0]=='/' || s[0]=='[' || s[0]==']' || s[0]== '?' ||
	    s[0]=='=' || s[0]== '{' || s[0]== '}') {
	    if (caseinsensitive == 1) {
		if (!isupper((unsigned char) s[0]))
		    break;
	    } else {
		break;
	    }
	}
	s++;
    }  
    return s;
}

/* Convert a string to 32 bit unsigned integer.
   Any number of trailing spaces is allowed, but not a string
   entirely comprised of spaces */
static bool str2ul32 (char *str, unsigned long * value)
{
    unsigned int n;
    char c;

    if (str == NULL) {
	return (FALSE);
    }
    
    *value = 0;

    str = skip_lws (str);
    if (str[0] == '\0') {
	return (FALSE);
    }

    n = 0;
    while (str[0] != '\0') {
	c = str[0];
	if (!isdigit((int)c)) {
	    return (FALSE);
	}

/* Will overflow after adding additional digit */
	if (n > MAX_UIN32_DIV_10) {
	    return (FALSE);
	} else if (n == MAX_UIN32_DIV_10 && ((unsigned) (c - '0') > MAX_UIN32_MOD_10)) {
	    return (FALSE);
	}

	n = n * 10 + (unsigned) (c - '0');
	str++;
    }

    *value = n;
    return (TRUE);
}

/* NULL - error (unbalanced quotes), 
   otherwise pointer to the first character after the value.
   The function performs work in place. */
static char *unquote (char *qstr)
{
    char *endvalue;
    int   escaped = 0;
    char *outptr;
    
    if(!qstr) return NULL;
    
    if (qstr[0] == '"') {
	qstr++;
	outptr = qstr;
	
	for (endvalue = qstr; endvalue[0] != '\0'; endvalue++, outptr++) {
	    if (escaped) {
		outptr[0] = endvalue[0];
		escaped = 0;
	    }
	    else if (endvalue[0] == '\\') {
		escaped = 1;
		outptr--; /* Will be incremented at the end of the loop */
	    }
	    else if (endvalue[0] == '"') {
		break;
	    }      
	    else {
		outptr[0] = endvalue[0];      
	    }
	}
	
	if (endvalue[0] != '"') {
	    return NULL;
	}
	
	while (outptr <= endvalue) {
	    outptr[0] = '\0';
	    outptr++;
	}
	endvalue++;
    }
    else { /* not qouted value (token) */
	/* qstr already contains output */
	endvalue = skip_token(qstr,0);
    };
    
    return endvalue;  
}

/* Unlike unquote, this function returns an allocated quoted copy */
static char *quote (char *str)
{
    char *p;
    char *outp;
    char *result;
    int num_to_escape;		/* How many characters need escaping */
    
    if (!str) return NULL;

    num_to_escape = 0;
    p = strpbrk (str, NEED_ESCAPING);
    while (p != NULL) {
	num_to_escape++;
	p = strpbrk (p + 1, NEED_ESCAPING);
    }

    if (num_to_escape == 0) {
	return (strdup (str));
    }

    result = malloc (strlen(str) + num_to_escape + 1);
    if (result == NULL) {
        return NULL;
    }
    for (p = str, outp = result; *p; p++) {
	if (*p == '"' || *p == '\\') {
	    *outp = '\\';
	    outp++;
	}
	*outp = *p;
	outp++;
    }

    *outp = '\0';
    
    return (result);
}

static void get_pair(char **in, char **name, char **value)
{
    char  *endpair;
    char  *curp = *in;
    *name = NULL;
    *value = NULL;
    
    if (curp == NULL) return;

    while (curp[0] != '\0') {
	/* skipping spaces: */
	curp = skip_lws(curp);
        
	/* 'LWS "," LWS "," ...' is allowed by the DIGEST-MD5 ABNF */
	if (curp[0] == ',') {
	    curp++;
	} else {
	    break;
	}
    }

    if (curp[0] == '\0') {
	/* End of the string is not an error */
	*name = "";
	return;
    }

    *name = curp;
    
    curp = skip_token(curp,1);
    
    /* strip wierd chars */
    if (curp[0] != '=' && curp[0] != '\0') {
	*curp++ = '\0';
    };
    
    curp = skip_lws(curp);
    
    if (curp[0] != '=') { /* No '=' sign */ 
	*name = NULL;
	return;
    }
    
    curp[0] = '\0';
    curp++;
    
    curp = skip_lws(curp);  
    
    *value = (curp[0] == '"') ? curp+1 : curp;
    
    endpair = unquote (curp);
    if (endpair == NULL) { /* Unbalanced quotes */ 
	*name = NULL;
	*value = NULL;
	return;
    }

    /* An optional LWS is allowed after the value. Skip it. */
    if (is_lws_char (endpair[0])) {
	/* Remove the trailing LWS from the value */
	*endpair++ = '\0'; 
	endpair = skip_lws(endpair);
    }

    /* syntax check: MUST be '\0' or ',' */  
    if (endpair[0] == ',') {
	endpair[0] = '\0';
	endpair++; /* skipping <,> */
    } else if (endpair[0] != '\0') { 
	*name = NULL;
	*value = NULL;
	return;
    }
    
    *in = endpair;
}

#ifdef WITH_DES
struct des_context_s {
    des_key_schedule keysched;  /* key schedule for des initialization */
    des_cblock ivec;            /* initial vector for encoding */
    des_key_schedule keysched2; /* key schedule for 3des initialization */
};

typedef struct des_context_s des_context_t;

/* slide the first 7 bytes of 'inbuf' into the high seven bits of the
   first 8 bytes of 'keybuf'. 'keybuf' better be 8 bytes long or longer. */
static void slidebits(unsigned char *keybuf, unsigned char *inbuf)
{
    keybuf[0] = inbuf[0];
    keybuf[1] = (inbuf[0]<<7) | (inbuf[1]>>1);
    keybuf[2] = (inbuf[1]<<6) | (inbuf[2]>>2);
    keybuf[3] = (inbuf[2]<<5) | (inbuf[3]>>3);
    keybuf[4] = (inbuf[3]<<4) | (inbuf[4]>>4);
    keybuf[5] = (inbuf[4]<<3) | (inbuf[5]>>5);
    keybuf[6] = (inbuf[5]<<2) | (inbuf[6]>>6);
    keybuf[7] = (inbuf[6]<<1);
}

/******************************
 *
 * 3DES functions
 *
 *****************************/

static int dec_3des(context_t *text,
		    const char *input,
		    unsigned inputlen,
		    unsigned char digest[16] __attribute__((unused)),
		    char *output,
		    unsigned *outputlen)
{
    des_context_t *c = (des_context_t *) text->cipher_dec_context;
    int padding, p;
    
    des_ede2_cbc_encrypt((void *) input,
			 (void *) output,
			 inputlen,
			 c->keysched,
			 c->keysched2,
			 &c->ivec,
			 DES_DECRYPT);
    
    /* now chop off the padding */
    padding = output[inputlen - 11];
    if (padding < 1 || padding > 8) {
	/* invalid padding length */
	return SASL_FAIL;
    }
    /* verify all padding is correct */
    for (p = 1; p <= padding; p++) {
	if (output[inputlen - 10 - p] != padding) {
	    return SASL_FAIL;
	}
    }
    
    /* chop off the padding */
    *outputlen = inputlen - padding - 10;

    return SASL_OK;
}

static int enc_3des(context_t *text,
		    const char *input,
		    unsigned inputlen,
		    unsigned char digest[16],
		    char *output,
		    unsigned *outputlen)
{
    des_context_t *c = (des_context_t *) text->cipher_enc_context;
    int len;
    int paddinglen;
    
    /* determine padding length */
    paddinglen = 8 - ((inputlen + 10) % 8);
    
    /* now construct the full stuff to be ciphered */
    memcpy(output, input, inputlen);                /* text */
    memset(output+inputlen, paddinglen, paddinglen);/* pad  */
    memcpy(output+inputlen+paddinglen, digest, 10); /* hmac */
    
    len=inputlen+paddinglen+10;
    
    des_ede2_cbc_encrypt((void *) output,
			 (void *) output,
			 len,
			 c->keysched,
			 c->keysched2,
			 &c->ivec,
			 DES_ENCRYPT);
    
    *outputlen=len;
    
    return SASL_OK;
}

static int init_3des(context_t *text, 
		     unsigned char enckey[16],
		     unsigned char deckey[16])
{
    des_context_t *c;
    unsigned char keybuf[8];

    /* allocate enc & dec context */
    c = (des_context_t *) text->utils->malloc(2 * sizeof(des_context_t));
    if (c == NULL) return SASL_NOMEM;

    /* setup enc context */
    slidebits(keybuf, enckey);
    if (des_key_sched((des_cblock *) keybuf, c->keysched) < 0)
	return SASL_FAIL;

    slidebits(keybuf, enckey + 7);
    if (des_key_sched((des_cblock *) keybuf, c->keysched2) < 0)
	return SASL_FAIL;
    memcpy(c->ivec, ((char *) enckey) + 8, 8);

    text->cipher_enc_context = (cipher_context_t *) c;

    /* setup dec context */
    c++;
    slidebits(keybuf, deckey);
    if (des_key_sched((des_cblock *) keybuf, c->keysched) < 0)
	return SASL_FAIL;
    
    slidebits(keybuf, deckey + 7);
    if (des_key_sched((des_cblock *) keybuf, c->keysched2) < 0)
	return SASL_FAIL;
    
    memcpy(c->ivec, ((char *) deckey) + 8, 8);

    text->cipher_dec_context = (cipher_context_t *) c;
    
    return SASL_OK;
}


/******************************
 *
 * DES functions
 *
 *****************************/

static int dec_des(context_t *text, 
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16] __attribute__((unused)),
		   char *output,
		   unsigned *outputlen)
{
    des_context_t *c = (des_context_t *) text->cipher_dec_context;
    int p, padding = 0;
    
    des_cbc_encrypt((void *) input,
		    (void *) output,
		    inputlen,
		    c->keysched,
		    &c->ivec,
		    DES_DECRYPT);

    /* Update the ivec (des_cbc_encrypt implementations tend to be broken in
       this way) */
    memcpy(c->ivec, input + (inputlen - 8), 8);
    
    /* now chop off the padding */
    padding = output[inputlen - 11];
    if (padding < 1 || padding > 8) {
	/* invalid padding length */
	return SASL_FAIL;
    }
    /* verify all padding is correct */
    for (p = 1; p <= padding; p++) {
	if (output[inputlen - 10 - p] != padding) {
	    return SASL_FAIL;
	}
    }
    
    /* chop off the padding */
    *outputlen = inputlen - padding - 10;

    return SASL_OK;
}

static int enc_des(context_t *text,
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16],
		   char *output,
		   unsigned *outputlen)
{
    des_context_t *c = (des_context_t *) text->cipher_enc_context;
    int len;
    int paddinglen;
  
    /* determine padding length */
    paddinglen = 8 - ((inputlen+10) % 8);

    /* now construct the full stuff to be ciphered */
    memcpy(output, input, inputlen);                /* text */
    memset(output+inputlen, paddinglen, paddinglen);/* pad  */
    memcpy(output+inputlen+paddinglen, digest, 10); /* hmac */
    
    len = inputlen + paddinglen + 10;
    
    des_cbc_encrypt((void *) output,
                    (void *) output,
                    len,
                    c->keysched,
                    &c->ivec,
                    DES_ENCRYPT);
    
    /* Update the ivec (des_cbc_encrypt implementations tend to be broken in
       this way) */
    memcpy(c->ivec, output + (len - 8), 8);
    
    *outputlen = len;
    
    return SASL_OK;
}

static int init_des(context_t *text,
		    unsigned char enckey[16],
		    unsigned char deckey[16])
{
    des_context_t *c;
    unsigned char keybuf[8];

    /* allocate enc context */
    c = (des_context_t *) text->utils->malloc(2 * sizeof(des_context_t));
    if (c == NULL) return SASL_NOMEM;
    
    /* setup enc context */
    slidebits(keybuf, enckey);
    des_key_sched((des_cblock *) keybuf, c->keysched);

    memcpy(c->ivec, ((char *) enckey) + 8, 8);
    
    text->cipher_enc_context = (cipher_context_t *) c;

    /* setup dec context */
    c++;
    slidebits(keybuf, deckey);
    des_key_sched((des_cblock *) keybuf, c->keysched);

    memcpy(c->ivec, ((char *) deckey) + 8, 8);
    
    text->cipher_dec_context = (cipher_context_t *) c;

    return SASL_OK;
}

static void free_des(context_t *text)
{
    /* free des contextss. only cipher_enc_context needs to be free'd,
       since cipher_dec_context was allocated at the same time. */
    if (text->cipher_enc_context) text->utils->free(text->cipher_enc_context);
}

#endif /* WITH_DES */

#ifdef WITH_RC4
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>

static void free_rc4(context_t *text)
{
    if (text->cipher_enc_context) {
        EVP_CIPHER_CTX_free((EVP_CIPHER_CTX *)text->cipher_enc_context);
        text->cipher_enc_context = NULL;
    }
    if (text->cipher_dec_context) {
        EVP_CIPHER_CTX_free((EVP_CIPHER_CTX *)text->cipher_dec_context);
        text->cipher_dec_context = NULL;
    }
}

static int init_rc4(context_t *text,
		    unsigned char enckey[16],
		    unsigned char deckey[16])
{
    EVP_CIPHER_CTX *ctx;
    int rc;

    ctx = EVP_CIPHER_CTX_new();
    if (ctx == NULL) return SASL_NOMEM;

    rc = EVP_EncryptInit_ex(ctx, EVP_rc4(), NULL, enckey, NULL);
    if (rc != 1) return SASL_FAIL;

    text->cipher_enc_context = (void *)ctx;

    ctx = EVP_CIPHER_CTX_new();
    if (ctx == NULL) return SASL_NOMEM;

    rc = EVP_DecryptInit_ex(ctx, EVP_rc4(), NULL, deckey, NULL);
    if (rc != 1) return SASL_FAIL;

    text->cipher_dec_context = (void *)ctx;

    return SASL_OK;
}

static int dec_rc4(context_t *text,
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16] __attribute__((unused)),
		   char *output,
		   unsigned *outputlen)
{
    int len;
    int rc;

    /* decrypt the text part & HMAC */
    rc = EVP_DecryptUpdate((EVP_CIPHER_CTX *)text->cipher_dec_context,
                           (unsigned char *)output, &len,
                           (const unsigned char *)input, inputlen);
    if (rc != 1) return SASL_FAIL;

    *outputlen = len;

    rc = EVP_DecryptFinal_ex((EVP_CIPHER_CTX *)text->cipher_dec_context,
                             (unsigned char *)output + len, &len);
    if (rc != 1) return SASL_FAIL;

    *outputlen += len;

    /* subtract the HMAC to get the text length */
    *outputlen -= 10;

    return SASL_OK;
}

static int enc_rc4(context_t *text,
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16],
		   char *output,
		   unsigned *outputlen)
{
    int len;
    int rc;
    /* encrypt the text part */
    rc = EVP_EncryptUpdate((EVP_CIPHER_CTX *)text->cipher_enc_context,
                           (unsigned char *)output, &len,
                           (const unsigned char *)input, inputlen);
    if (rc != 1) return SASL_FAIL;

    *outputlen = len;

    /* encrypt the `MAC part */
    rc = EVP_EncryptUpdate((EVP_CIPHER_CTX *)text->cipher_enc_context,
                           (unsigned char *)output + *outputlen, &len,
                           digest, 10);
    if (rc != 1) return SASL_FAIL;

    *outputlen += len;

    rc = EVP_EncryptFinal_ex((EVP_CIPHER_CTX *)text->cipher_enc_context,
                             (unsigned char *)output + *outputlen, &len);
    if (rc != 1) return SASL_FAIL;

    *outputlen += len;

    return SASL_OK;
}
#else
/* quick generic implementation of RC4 */
struct rc4_context_s {
    unsigned char sbox[256];
    int i, j;
};

typedef struct rc4_context_s rc4_context_t;

static void rc4_init(rc4_context_t *text,
		     const unsigned char *key,
		     unsigned keylen)
{
    int i, j;
    
    /* fill in linearly s0=0 s1=1... */
    for (i=0;i<256;i++)
	text->sbox[i]=i;
    
    j=0;
    for (i = 0; i < 256; i++) {
	unsigned char tmp;
	/* j = (j + Si + Ki) mod 256 */
	j = (j + text->sbox[i] + key[i % keylen]) % 256;
	
	/* swap Si and Sj */
	tmp = text->sbox[i];
	text->sbox[i] = text->sbox[j];
	text->sbox[j] = tmp;
    }
    
    /* counters initialized to 0 */
    text->i = 0;
    text->j = 0;
}

static void rc4_encrypt(rc4_context_t *text,
			const char *input,
			char *output,
			unsigned len)
{
    int tmp;
    int i = text->i;
    int j = text->j;
    int t;
    int K;
    const char *input_end = input + len;
    
    while (input < input_end) {
	i = (i + 1) % 256;
	
	j = (j + text->sbox[i]) % 256;
	
	/* swap Si and Sj */
	tmp = text->sbox[i];
	text->sbox[i] = text->sbox[j];
	text->sbox[j] = tmp;
	
	t = (text->sbox[i] + text->sbox[j]) % 256;
	
	K = text->sbox[t];
	
	/* byte K is Xor'ed with plaintext */
	*output++ = *input++ ^ K;
    }
    
    text->i = i;
    text->j = j;
}

static void rc4_decrypt(rc4_context_t *text,
			const char *input,
			char *output,
			unsigned len)
{
    int tmp;
    int i = text->i;
    int j = text->j;
    int t;
    int K;
    const char *input_end = input + len;
    
    while (input < input_end) {
	i = (i + 1) % 256;
	
	j = (j + text->sbox[i]) % 256;
	
	/* swap Si and Sj */
	tmp = text->sbox[i];
	text->sbox[i] = text->sbox[j];
	text->sbox[j] = tmp;
	
	t = (text->sbox[i] + text->sbox[j]) % 256;
	
	K = text->sbox[t];
	
	/* byte K is Xor'ed with plaintext */
	*output++ = *input++ ^ K;
    }
    
    text->i = i;
    text->j = j;
}

static void free_rc4(context_t *text)
{
    /* free rc4 context structures */

    if (text->cipher_enc_context) {
        text->utils->free(text->cipher_enc_context);
        text->cipher_enc_context = NULL;
    }
    if (text->cipher_dec_context) {
        text->utils->free(text->cipher_dec_context);
        text->cipher_dec_context = NULL;
    }
}

static int init_rc4(context_t *text, 
		    unsigned char enckey[16],
		    unsigned char deckey[16])
{
    /* allocate rc4 context structures */
    text->cipher_enc_context=
	(cipher_context_t *) text->utils->malloc(sizeof(rc4_context_t));
    if (text->cipher_enc_context == NULL) return SASL_NOMEM;
    
    text->cipher_dec_context=
	(cipher_context_t *) text->utils->malloc(sizeof(rc4_context_t));
    if (text->cipher_dec_context == NULL) return SASL_NOMEM;
    
    /* initialize them */
    rc4_init((rc4_context_t *) text->cipher_enc_context,
             (const unsigned char *) enckey, 16);
    rc4_init((rc4_context_t *) text->cipher_dec_context,
             (const unsigned char *) deckey, 16);
    
    return SASL_OK;
}

static int dec_rc4(context_t *text,
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16] __attribute__((unused)),
		   char *output,
		   unsigned *outputlen)
{
    /* decrypt the text part & HMAC */
    rc4_decrypt((rc4_context_t *) text->cipher_dec_context, 
                input, output, inputlen);

    /* no padding so we just subtract the HMAC to get the text length */
    *outputlen = inputlen - 10;
    
    return SASL_OK;
}

static int enc_rc4(context_t *text,
		   const char *input,
		   unsigned inputlen,
		   unsigned char digest[16],
		   char *output,
		   unsigned *outputlen)
{
    /* pad is zero */
    *outputlen = inputlen+10;
    
    /* encrypt the text part */
    rc4_encrypt((rc4_context_t *) text->cipher_enc_context,
                input,
                output,
                inputlen);
    
    /* encrypt the HMAC part */
    rc4_encrypt((rc4_context_t *) text->cipher_enc_context, 
                (const char *) digest, 
		(output)+inputlen, 10);
    
    return SASL_OK;
}
#endif /* HAVE_OPENSSL */
#endif /* WITH_RC4 */

struct digest_cipher available_ciphers[] =
{
#ifdef WITH_RC4
    { "rc4-40", 40, 5, 0x01, &enc_rc4, &dec_rc4, &init_rc4, &free_rc4 },
    { "rc4-56", 56, 7, 0x02, &enc_rc4, &dec_rc4, &init_rc4, &free_rc4 },
    { "rc4", 128, 16, 0x04, &enc_rc4, &dec_rc4, &init_rc4, &free_rc4 },
#endif
#ifdef WITH_DES
    { "des", 55, 16, 0x08, &enc_des, &dec_des, &init_des, &free_des },
    { "3des", 112, 16, 0x10, &enc_3des, &dec_3des, &init_3des, &free_des },
#endif
    { NULL, 0, 0, 0, NULL, NULL, NULL, NULL }
};

static int create_layer_keys(context_t *text,
			     const sasl_utils_t *utils,
			     HASH key, int keylen,
			     unsigned char enckey[16],
			     unsigned char deckey[16])
{
    MD5_CTX Md5Ctx;
    
    utils->log(utils->conn, SASL_LOG_DEBUG,
	       "DIGEST-MD5 create_layer_keys()");

    utils->MD5Init(&Md5Ctx);
    utils->MD5Update(&Md5Ctx, key, keylen);
    if (text->i_am == SERVER) {
	utils->MD5Update(&Md5Ctx, (const unsigned char *) SEALING_SERVER_CLIENT, 
			 (unsigned) strlen(SEALING_SERVER_CLIENT));
    } else {
	utils->MD5Update(&Md5Ctx, (const unsigned char *) SEALING_CLIENT_SERVER,
			 (unsigned) strlen(SEALING_CLIENT_SERVER));
    }
    utils->MD5Final(enckey, &Md5Ctx);
    
    utils->MD5Init(&Md5Ctx);
    utils->MD5Update(&Md5Ctx, key, keylen);
    if (text->i_am != SERVER) {
	utils->MD5Update(&Md5Ctx, (const unsigned char *) SEALING_SERVER_CLIENT, 
			 (unsigned) strlen(SEALING_SERVER_CLIENT));
    } else {
	utils->MD5Update(&Md5Ctx, (const unsigned char *) SEALING_CLIENT_SERVER,
			 (unsigned) strlen(SEALING_CLIENT_SERVER));
    }
    utils->MD5Final(deckey, &Md5Ctx);
    
    /* create integrity keys */
    /* sending */
    utils->MD5Init(&Md5Ctx);
    utils->MD5Update(&Md5Ctx, text->HA1, HASHLEN);
    if (text->i_am == SERVER) {
	utils->MD5Update(&Md5Ctx, (const unsigned char *)SIGNING_SERVER_CLIENT, 
			 (unsigned) strlen(SIGNING_SERVER_CLIENT));
    } else {
	utils->MD5Update(&Md5Ctx, (const unsigned char *)SIGNING_CLIENT_SERVER,
			 (unsigned) strlen(SIGNING_CLIENT_SERVER));
    }
    utils->MD5Final(text->Ki_send, &Md5Ctx);
    
    /* receiving */
    utils->MD5Init(&Md5Ctx);
    utils->MD5Update(&Md5Ctx, text->HA1, HASHLEN);
    if (text->i_am != SERVER) {
	utils->MD5Update(&Md5Ctx, (const unsigned char *)SIGNING_SERVER_CLIENT, 
			 (unsigned) strlen(SIGNING_SERVER_CLIENT));
    } else {
	utils->MD5Update(&Md5Ctx, (const unsigned char *)SIGNING_CLIENT_SERVER,
			 (unsigned) strlen(SIGNING_CLIENT_SERVER));
    }
    utils->MD5Final(text->Ki_receive, &Md5Ctx);
    
    return SASL_OK;
}

static const unsigned short version = 1;

/*
 * privacy:
 * len, CIPHER(Kc, {msg, pag, HMAC(ki, {SeqNum, msg})[0..9]}), x0001, SeqNum
 *
 * integrity:
 * len, HMAC(ki, {SeqNum, msg})[0..9], x0001, SeqNum
 */
static int digestmd5_encode(void *context,
			    const struct iovec *invec,
			    unsigned numiov,
			    const char **output,
			    unsigned *outputlen)
{
    context_t *text = (context_t *) context;
    int tmp;
    unsigned int tmpnum;
    unsigned short int tmpshort;
    int ret;
    char *out;
    struct buffer_info *inblob, bufinfo;
    
    if(!context || !invec || !numiov || !output || !outputlen) {
	if (text) PARAMERROR(text->utils);
	return SASL_BADPARAM;
    }
    
    if (numiov > 1) {
	ret = _plug_iovec_to_buf(text->utils, invec, numiov, &text->enc_in_buf);
	if (ret != SASL_OK) return ret;
	inblob = text->enc_in_buf;
    } else {
	/* avoid the data copy */
	bufinfo.data = invec[0].iov_base;
	bufinfo.curlen = invec[0].iov_len;
	inblob = &bufinfo;
    }
    
    /* make sure the output buffer is big enough for this blob */
    ret = _plug_buf_alloc(text->utils, &(text->encode_buf),
			  &(text->encode_buf_len),
			  (4 +			/* for length */
			   inblob->curlen +	/* for content */
			   10 +			/* for MAC */
			   8 +			/* maximum pad */
			   6));			/* for ver and seqnum */
    if(ret != SASL_OK) return ret;
    
    /* skip by the length for now */
    out = (text->encode_buf)+4;
    
    /* construct (seqnum, msg)
     *
     * Use the output buffer so that the message text is already in place
     * for an integrity-only layer.
     */
    tmpnum = htonl(text->seqnum);
    memcpy(text->encode_buf, &tmpnum, 4);
    memcpy(text->encode_buf + 4, inblob->data, inblob->curlen);
    
    if (text->cipher_enc) {
	unsigned char digest[16];

	/* HMAC(ki, (seqnum, msg) ) */
	text->utils->hmac_md5((const unsigned char *) text->encode_buf,
			      inblob->curlen + 4, 
			      text->Ki_send, HASHLEN, digest);

	/* calculate the encrypted part */
	text->cipher_enc(text, inblob->data, inblob->curlen,
			 digest, out, outputlen);
	out+=(*outputlen);
    }
    else {
	/* HMAC(ki, (seqnum, msg) ) -- put directly into output buffer */
	text->utils->hmac_md5((const unsigned char *) text->encode_buf,
			      inblob->curlen + 4, 
			      text->Ki_send, HASHLEN,
			      (unsigned char *) text->encode_buf +
						inblob->curlen + 4);

	*outputlen = inblob->curlen + 10; /* for message + CMAC */
	out+=inblob->curlen + 10;
    }
    
    /* copy in version */
    tmpshort = htons(version);
    memcpy(out, &tmpshort, 2);	/* 2 bytes = version */
    
    out+=2;
    (*outputlen)+=2; /* for version */
    
    /* put in seqnum */
    tmpnum = htonl(text->seqnum);
    memcpy(out, &tmpnum, 4);	/* 4 bytes = seq # */  
    
    (*outputlen)+=4; /* for seqnum */
    
    /* put the 1st 4 bytes in */
    tmp=htonl(*outputlen);  
    memcpy(text->encode_buf, &tmp, 4);
    
    (*outputlen)+=4;
    
    *output = text->encode_buf;
    text->seqnum++;
    
    return SASL_OK;
}

static int digestmd5_decode_packet(void *context,
					   const char *input,
					   unsigned inputlen,
					   char **output,
					   unsigned *outputlen)
{
    context_t *text = (context_t *) context;
    int result;
    unsigned char *digest;
    int tmpnum;
    int lup;
    unsigned short ver;
    unsigned int seqnum;
    unsigned char checkdigest[16];
	
    if (inputlen < 16) {
	text->utils->seterror(text->utils->conn, 0, "DIGEST-MD5 SASL packets must be at least 16 bytes long");
	return SASL_FAIL;
    }

    /* check the version number */
    memcpy(&ver, input+inputlen-6, 2);
    ver = ntohs(ver);
    if (ver != version) {
	text->utils->seterror(text->utils->conn, 0, "Wrong Version");
	return SASL_FAIL;
    }
	
    /* check the sequence number */
    memcpy(&seqnum, input+inputlen-4, 4);
    seqnum = ntohl(seqnum);
	
    if (seqnum != text->rec_seqnum) {
	text->utils->seterror(text->utils->conn, 0,
	    "Incorrect Sequence Number: received %u, expected %u",
	    seqnum,
	    text->rec_seqnum);
	return SASL_FAIL;
    }

    /* allocate a buffer large enough for the output */
    result = _plug_buf_alloc(text->utils, &text->decode_packet_buf,
			     &text->decode_packet_buf_len,
			     inputlen	/* length of message */
			     - 6	/* skip ver and seqnum */
			     + 4);	/* prepend seqnum */
    if (result != SASL_OK) return result;
	
    /* construct (seqnum, msg) */
    tmpnum = htonl(text->rec_seqnum);
    memcpy(text->decode_packet_buf, &tmpnum, 4);

    text->rec_seqnum++; /* now increment it */

    *output = text->decode_packet_buf + 4; /* skip seqnum */

    if (text->cipher_dec) {
	/* decrypt message & HMAC into output buffer */
	result = text->cipher_dec(text, input, inputlen-6, NULL,
				  *output, outputlen);
	if (result != SASL_OK) return result;
    }
    else {
	/* copy message & HMAC into output buffer */
	memcpy(*output, input, inputlen - 6);
	*outputlen = inputlen - 16; /* -16 to skip HMAC, ver and seqnum */
    }
    digest = (unsigned char *) *output + (inputlen - 16);

    /* check the CMAC */

    /* HMAC(ki, (seqnum, msg) ) */
    text->utils->hmac_md5((const unsigned char *) text->decode_packet_buf,
			  (*outputlen) + 4, 
			  text->Ki_receive, HASHLEN, checkdigest);
	
    /* now check it */
    for (lup = 0; lup < 10; lup++)
	if (checkdigest[lup] != digest[lup]) {
	    text->utils->seterror(text->utils->conn, 0,
				  "CMAC doesn't match at byte %d!", lup);
	    return SASL_FAIL;
	}
	
    return SASL_OK;
}

static int digestmd5_decode(void *context,
				    const char *input, unsigned inputlen,
				    const char **output, unsigned *outputlen)
{
    context_t *text = (context_t *) context;
    int ret;
    
    ret = _plug_decode(&text->decode_context, input, inputlen,
		       &text->decode_buf, &text->decode_buf_len, outputlen,
		       digestmd5_decode_packet, text);
    
    *output = text->decode_buf;
    
    return ret;
}

static void digestmd5_common_mech_dispose(void *conn_context,
					  const sasl_utils_t *utils)
{
    context_t *text = (context_t *) conn_context;
    int lup;
    
    if (!text || !utils) return;
    
    utils->log(utils->conn, SASL_LOG_DEBUG,
	       "DIGEST-MD5 common mech dispose");

    if (text->authid) utils->free(text->authid);
    if (text->realm) utils->free(text->realm);

    if (text->realms) {
	/* need to free all the realms */
	for (lup = 0; lup < text->realm_cnt; lup++)
	    utils->free (text->realms[lup]);
	
	utils->free(text->realms);
    }

    if (text->nonce) utils->free(text->nonce);
    if (text->cnonce) utils->free(text->cnonce);

    if (text->cipher_free) text->cipher_free(text);
    
    /* free the stuff in the context */
    if (text->response_value) utils->free(text->response_value);
    
    _plug_decode_free(&text->decode_context);
    if (text->encode_buf) utils->free(text->encode_buf);
    if (text->decode_buf) utils->free(text->decode_buf);
    if (text->decode_packet_buf) utils->free(text->decode_packet_buf);
    if (text->out_buf) utils->free(text->out_buf);
    
    if (text->enc_in_buf) {
	if (text->enc_in_buf->data) utils->free(text->enc_in_buf->data);
	utils->free(text->enc_in_buf);
    }
    
    utils->free(conn_context);
}

static void clear_reauth_entry(reauth_entry_t *reauth, enum Context_type type,
			       const sasl_utils_t *utils)
{
    if (!reauth) return;

    if (reauth->authid) utils->free(reauth->authid);
    if (reauth->realm) utils->free(reauth->realm);
    if (reauth->nonce) utils->free(reauth->nonce);
    if (reauth->cnonce) utils->free(reauth->cnonce);

    if (type == CLIENT) {
	if (reauth->u.c.serverFQDN) utils->free(reauth->u.c.serverFQDN);
    }

    memset(reauth, 0, sizeof(reauth_entry_t));
}

static void digestmd5_common_mech_free(void *glob_context,
				       const sasl_utils_t *utils)
{
    digest_glob_context_t *my_glob_context =
	(digest_glob_context_t *) glob_context;
    reauth_cache_t *reauth_cache = my_glob_context->reauth;
    size_t n;

    utils->log(utils->conn, SASL_LOG_DEBUG,
	       "DIGEST-MD5 common mech free");
 
    /* Prevent anybody else from freeing this as well */
    my_glob_context->reauth = NULL;

    if (!reauth_cache) return;

    for (n = 0; n < reauth_cache->size; n++) {
	clear_reauth_entry(&reauth_cache->e[n], reauth_cache->i_am, utils);
    }
    if (reauth_cache->e) utils->free(reauth_cache->e);

    if (reauth_cache->mutex) {
	utils->mutex_free(reauth_cache->mutex);
	reauth_cache->mutex = NULL;
    }

    utils->free(reauth_cache);
}

/*****************************  Server Section  *****************************/

typedef struct server_context {
    context_t common;

    time_t timestamp;
    int stale;				/* last nonce is stale */
    sasl_ssf_t limitssf, requiressf;	/* application defined bounds */
} server_context_t;

static digest_glob_context_t server_glob_context;

static void DigestCalcHA1FromSecret(context_t * text,
				    const sasl_utils_t * utils,
				    HASH HA1,
				    unsigned char *authorization_id,
				    unsigned char *pszNonce,
				    unsigned char *pszCNonce,
				    HASHHEX SessionKey)
{
    MD5_CTX Md5Ctx;
    
    /* calculate session key */
    utils->MD5Init(&Md5Ctx);
    if (text->http_mode) {
	/* per RFC 2617 Errata ID 1649 */
	HASHHEX HA1Hex;
    
	CvtHex(HA1, HA1Hex);
	utils->MD5Update(&Md5Ctx, HA1Hex, HASHHEXLEN);
    }
    else {
	/* per RFC 2831 */
	utils->MD5Update(&Md5Ctx, HA1, HASHLEN);
    }
    utils->MD5Update(&Md5Ctx, COLON, 1);
    utils->MD5Update(&Md5Ctx, pszNonce, (unsigned) strlen((char *) pszNonce));
    utils->MD5Update(&Md5Ctx, COLON, 1);
    utils->MD5Update(&Md5Ctx, pszCNonce, (unsigned) strlen((char *) pszCNonce));
    if (authorization_id != NULL) {
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, authorization_id,
			(unsigned) strlen((char *) authorization_id));
    }
    utils->MD5Final(HA1, &Md5Ctx);
    
    CvtHex(HA1, SessionKey);
    
    
    /* save HA1 because we need it to make the privacy and integrity keys */
    memcpy(text->HA1, HA1, sizeof(HASH));
}

static char *create_response(context_t * text,
			     const sasl_utils_t * utils,
			     unsigned char *nonce,
			     unsigned int ncvalue,
			     unsigned char *cnonce,
			     char *qop,
			     const sasl_http_request_t *request,
			     HASH Secret,
			     char *authorization_id,
			     char **response_value)
{
    HASHHEX         SessionKey;
    HASH            EntityHash;
    HASHHEX         HEntity;
    HASHHEX         Response;
    char           *result;
    
    if (qop == NULL) qop = "auth";
    
    DigestCalcHA1FromSecret(text,
			    utils,
			    Secret,
			    (unsigned char *) authorization_id,
			    nonce,
			    cnonce,
			    SessionKey);

    if (text->http_mode) {
	/* per RFC 2617 */
	MD5_CTX Md5Ctx;

	utils->MD5Init(&Md5Ctx);
	utils->MD5Update(&Md5Ctx, request->entity, request->elen);
	utils->MD5Final(EntityHash, &Md5Ctx);
    }
    else {
	/* per RFC 2831 */
	memset(EntityHash, 0, HASHLEN);
    }
    CvtHex(EntityHash, HEntity);

    /* Calculate response for comparison with client's response */
    DigestCalcResponse(utils,
		       SessionKey,/* HEX(H(A1)) */
		       nonce,	/* nonce from server */
		       ncvalue,	/* 8 hex digits */
		       cnonce,	/* client nonce */
		       (unsigned char *) qop,	/* qop-value: "", "auth",
						 * "auth-int" */
		       (unsigned char *) request->uri,	/* requested URL */
		       (unsigned char *) request->method,
		       HEntity,	/* H(entity body) if qop="auth-int" */
		       Response	/* request-digest or response-digest */
	);
    
    result = utils->malloc(HASHHEXLEN + 1);
    memcpy(result, Response, HASHHEXLEN);
    result[HASHHEXLEN] = 0;
    
    /* Calculate response value for mutual auth with the client (NO Method) */
    if (response_value != NULL) {
	char * new_response_value;

	DigestCalcResponse(utils,
			   SessionKey,	/* HEX(H(A1)) */
			   nonce,	/* nonce from server */
			   ncvalue,	/* 8 hex digits */
			   cnonce,	/* client nonce */
			   (unsigned char *) qop,	/* qop-value: "", "auth",
							 * "auth-int" */
			   (unsigned char *) request->uri, /* requested URL */
			   NULL,
			   HEntity,	/* H(entity body) if qop="auth-int" */
			   Response	/* request-digest or response-digest */
	    );
	
	new_response_value = utils->realloc(*response_value, HASHHEXLEN + 1);
	if (new_response_value == NULL) {
	    free (*response_value);
	    *response_value = NULL;
	    return NULL;
	}
	*response_value = new_response_value;

	memcpy(*response_value, Response, HASHHEXLEN);
	(*response_value)[HASHHEXLEN] = 0;
    }
    return result;
}

static int get_server_realm(sasl_server_params_t * params, char **realm)
{
    /* look at user realm first */
    if (params->user_realm != NULL) {
	if(params->user_realm[0] != '\0') {
	    *realm = (char *) params->user_realm;
	} else {
	    /* Catch improperly converted apps */
	    params->utils->seterror(params->utils->conn, 0,
				    "user_realm is an empty string!");
	    return SASL_BADPARAM;
	}
    } else if (params->serverFQDN != NULL) {
	*realm = (char *) params->serverFQDN;
    } else {
	params->utils->seterror(params->utils->conn, 0,
				"no way to obtain DIGEST-MD5 realm");
	return SASL_FAIL;
    }
    
    return SASL_OK;
}

/*
 * Convert hex string to int
 */
static int htoi(unsigned char *hexin, unsigned int *res)
{
    size_t             lup, inlen;
    inlen = strlen((char *) hexin);
    
    *res = 0;
    for (lup = 0; lup < inlen; lup++) {
	switch (hexin[lup]) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	    *res = (*res << 4) + (hexin[lup] - '0');
	    break;
	    
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	    *res = (*res << 4) + (hexin[lup] - 'a' + 10);
	    break;
	    
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	    *res = (*res << 4) + (hexin[lup] - 'A' + 10);
	    break;
	    
	default:
	    return SASL_BADPARAM;
	}
	
    }
    
    return SASL_OK;
}

static int digestmd5_server_mech_new(void *glob_context,
				     sasl_server_params_t * sparams,
				     const char *challenge __attribute__((unused)),
				     unsigned challen __attribute__((unused)),
				     void **conn_context)
{
    context_t *text;
    
    /* holds state are in -- allocate server size */
    text = sparams->utils->malloc(sizeof(server_context_t));
    if (text == NULL)
	return SASL_NOMEM;
    memset((server_context_t *)text, 0, sizeof(server_context_t));
    
    text->state = 1;
    text->i_am = SERVER;
    text->http_mode = (sparams->flags & SASL_NEED_HTTP);
    text->reauth = ((digest_glob_context_t *) glob_context)->reauth;
    
    *conn_context = text;
    return SASL_OK;
}

static int
digestmd5_server_mech_step1(server_context_t *stext,
			    sasl_server_params_t *sparams,
			    const char *clientin __attribute__((unused)),
			    unsigned clientinlen __attribute__((unused)),
			    const char **serverout,
			    unsigned *serveroutlen,
			    sasl_out_params_t * oparams __attribute__((unused)))
{
    context_t *text = (context_t *) stext;
    int             result;
    char           *realm;
    unsigned char  *nonce;
    char           *charset = "utf-8";
    char qop[1024], cipheropts[1024];
    struct digest_cipher *cipher;
    unsigned       resplen;
    int added_conf = 0;
    char maxbufstr[64];
    
    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
			"DIGEST-MD5 server step 1");

    /* get realm */
    result = get_server_realm(sparams, &realm);
    if(result != SASL_OK) return result;
    
    /* what options should we offer the client? */
    qop[0] = '\0';
    cipheropts[0] = '\0';
    if (stext->requiressf == 0) {
	if (*qop) strcat(qop, ",");
	strcat(qop, "auth");
    }
    if (stext->requiressf <= 1 && stext->limitssf >= 1) {
	if (*qop) strcat(qop, ",");
	strcat(qop, "auth-int");
    }
    
    cipher = available_ciphers;
    while (cipher->name) {
	/* do we allow this particular cipher? */
	if (stext->requiressf <= cipher->ssf &&
	    stext->limitssf >= cipher->ssf) {
	    if (!added_conf) {
		if (*qop) strcat(qop, ",");
		strcat(qop, "auth-conf");
		added_conf = 1;
	    }
	    if (strlen(cipheropts) + strlen(cipher->name) + 1 >= 1024)
		return SASL_FAIL;
	    if (*cipheropts) strcat(cipheropts, ",");
	    strcat(cipheropts, cipher->name);
	}
	cipher++;
    }
    
    if (*qop == '\0') {
	/* we didn't allow anything?!? we'll return SASL_TOOWEAK, since
	   that's close enough */
	return SASL_TOOWEAK;
    }
    
    /*
     * digest-challenge  = 1#( realm | nonce | qop-options | stale | maxbuf |
     * charset | cipher-opts | auth-param )
     */
    
    nonce = create_nonce(sparams->utils);
    if (nonce == NULL) {
	SETERROR(sparams->utils, "internal erorr: failed creating a nonce");
	return SASL_FAIL;
    }
    
    resplen = 0;
    text->out_buf = NULL;
    text->out_buf_len = 0;
    if (add_to_challenge(sparams->utils,
				  &text->out_buf, &text->out_buf_len, &resplen,
				  "nonce", (unsigned char *) nonce,
				  TRUE) != SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge failed");
	return SASL_FAIL;
    }

    /* add to challenge; if we chose not to specify a realm, we won't
     * send one to the client */
    if (realm && add_to_challenge(sparams->utils,
				  &text->out_buf, &text->out_buf_len, &resplen,
				  "realm", (unsigned char *) realm,
				  TRUE) != SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge failed");
	return SASL_FAIL;
    }
    /*
     * qop-options A quoted string of one or more tokens indicating the
     * "quality of protection" values supported by the server.  The value
     * "auth" indicates authentication; the value "auth-int" indicates
     * authentication with integrity protection; the value "auth-conf"
     * indicates authentication with integrity protection and encryption.
     */
    
    /* add qop to challenge */
    if (add_to_challenge(sparams->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "qop", 
			 (unsigned char *) qop, TRUE) != SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge 3 failed");
	return SASL_FAIL;
    }
    
    /*
     *  Cipheropts - list of ciphers server supports
     */
    /* add cipher-opts to challenge; only add if there are some */
    if (strcmp(cipheropts,"")!=0)
	{
	    if (add_to_challenge(sparams->utils,
				 &text->out_buf, &text->out_buf_len, &resplen,
				 "cipher", (unsigned char *) cipheropts, 
				 TRUE) != SASL_OK) {
		SETERROR(sparams->utils,
			 "internal error: add_to_challenge 4 failed");
		return SASL_FAIL;
	    }
	}
    
    /* "stale" is true if a reauth failed because of a nonce timeout */
    if (stext->stale &&
	add_to_challenge(sparams->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "stale", (unsigned char *) "true", FALSE) != SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge failed");
	return SASL_FAIL;
    }
    
    /*
     * maxbuf A number indicating the size of the largest buffer the server
     * is able to receive when using "auth-int". If this directive is
     * missing, the default value is 65536. This directive may appear at most
     * once; if multiple instances are present, the client should abort the
     * authentication exchange.
     */
    if(sparams->props.maxbufsize) {
	snprintf(maxbufstr, sizeof(maxbufstr), "%u",
		 sparams->props.maxbufsize);
	if (add_to_challenge(sparams->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "maxbuf", 
			     (unsigned char *) maxbufstr, FALSE) != SASL_OK) {
	    SETERROR(sparams->utils,
		     "internal error: add_to_challenge 5 failed");
	    return SASL_FAIL;
	}
    }
    
    if (add_to_challenge(sparams->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "charset", 
			 (unsigned char *) charset, FALSE) != SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge 6 failed");
	return SASL_FAIL;
    }
    
    
    /*
     * algorithm 
     *  This directive is required for backwards compatibility with HTTP 
     *  Digest, which supports other algorithms. This directive is 
     *  required and MUST appear exactly once; if not present, or if multiple 
     *  instances are present, the client should abort the authentication 
     *  exchange. 
     *
     * algorithm         = "algorithm" "=" "md5-sess" 
     */
    
    if (add_to_challenge(sparams->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "algorithm",
			 (unsigned char *) "md5-sess", FALSE)!=SASL_OK) {
	SETERROR(sparams->utils, "internal error: add_to_challenge 7 failed");
	return SASL_FAIL;
    }
    
    /*
     * The size of a digest-challenge MUST be less than 2048 bytes!!!
     */
    if (*serveroutlen > 2048) {
	SETERROR(sparams->utils,
		 "internal error: challenge larger than 2048 bytes");
	return SASL_FAIL;
    }

    text->authid = NULL;
    if (_plug_strdup(sparams->utils, realm, &text->realm, NULL) != SASL_OK) {
	SETERROR(sparams->utils,
		 "internal error: out of memory when saving realm");
	return SASL_FAIL;
    }

    if (text->http_mode && text->reauth->timeout &&
	sparams->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */

	/* Create an initial cache entry for non-persistent HTTP connections */
	unsigned val = hash((char *) nonce) % text->reauth->size;

	clear_reauth_entry(&text->reauth->e[val], SERVER, sparams->utils);
	text->reauth->e[val].authid = NULL;
	text->reauth->e[val].realm = text->realm; text->realm = NULL;
	text->reauth->e[val].nonce = nonce;
	text->reauth->e[val].nonce_count = 1;
	text->reauth->e[val].cnonce = NULL;
	text->reauth->e[val].u.s.timestamp = time(0);

	sparams->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
    }
    else {
	text->nonce = nonce;
	text->nonce_count = 1;
	text->cnonce = NULL;
	stext->timestamp = time(0);
    }
    
    *serveroutlen = (unsigned) strlen(text->out_buf);
    *serverout = text->out_buf;
    
    text->state = 2;
    
    return SASL_CONTINUE;
}

static int digestmd5_server_mech_step2(server_context_t *stext,
				       sasl_server_params_t *sparams,
				       const char *clientin,
				       unsigned clientinlen,
				       const char **serverout,
				       unsigned *serveroutlen,
				       sasl_out_params_t * oparams)
{
    context_t *text = (context_t *) stext;
    /* verify digest */
    sasl_secret_t  *sec = NULL;
    int             result;
    char           *serverresponse = NULL;
    char           *username = NULL;
    char           *authorization_id = NULL;
    char           *realm = NULL;
    unsigned char  *nonce = NULL, *cnonce = NULL;
    unsigned int   noncecount = 0;
    char           *qop = NULL;
    char           *digesturi = NULL;
    sasl_http_request_t rfc2831_request;
    const sasl_http_request_t *request;
    char           *response = NULL;
    
    /* setting the default value (65536) */
    unsigned long  client_maxbuf = 65536;
    int            maxbuf_count = 0;  /* How many maxbuf instances was found */
    
    char           *charset = NULL;
    char           *cipher = NULL;
    unsigned int   n = 0;
    
    HASH           Secret;
    HASH           SecretBogus;
    bool           Try_8859_1 = FALSE;
    int            client_ignores_realm = 0;
    char           *full_username = NULL;
    char           *internal_username = NULL;
    int            canon_flags;

    /* password prop_request */
    const char *password_request[] = { SASL_AUX_PASSWORD,
#if defined(OBSOLETE_DIGEST_ATTR)
				       "*cmusaslsecretDIGEST-MD5",
#endif
				       NULL };
    size_t len;
    struct propval auxprop_values[2];
    
    /* can we mess with clientin? copy it to be safe */
    char           *in_start = NULL;
    char           *in = NULL;
    cipher_free_t  *old_cipher_free = NULL;
    
    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
			"DIGEST-MD5 server step 2");

    if (clientinlen == 0) {
	SETERROR(sparams->utils, "input expected in DIGEST-MD5, step 2");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }

    if (text->http_mode) {
	/* per RFC 2617 (HTTP Request as set by calling application) */
	request = sparams->http_request;
	if (!request) {
	    SETERROR(sparams->utils,
		     "missing HTTP request in DIGEST-MD5, step 2");
	    result = SASL_BADPARAM;
	    goto FreeAllMem;
	}
    }
    else {
	/* per RFC 2831 */
	rfc2831_request.method = "AUTHENTICATE";
	rfc2831_request.uri = NULL;  /* to be filled in below from response */
	rfc2831_request.entity = NULL;
	rfc2831_request.elen = 0;
	rfc2831_request.non_persist = 0;
	request = &rfc2831_request;
    }
    
    in = sparams->utils->malloc(clientinlen + 1);
    
    memcpy(in, clientin, clientinlen);
    in[clientinlen] = 0;
    
    in_start = in;
    
    
    /* parse what we got */
    while (in[0] != '\0') {
	char           *name = NULL, *value = NULL;
	get_pair(&in, &name, &value);
	
	if (name == NULL) {
	    SETERROR(sparams->utils,
		     "Parse error");
	    result = SASL_BADAUTH;
	    goto FreeAllMem;
	}
	
	if (*name == '\0') {
	    break;
	}

	/* Extracting parameters */
	
	/*
	 * digest-response  = 1#( username | realm | nonce | cnonce |
	 * nonce-count | qop | digest-uri | response | maxbuf | charset |
	 * cipher | auth-param )
	 */
	
	if (strcasecmp(name, "username") == 0) {
	    _plug_strdup(sparams->utils, value, &username, NULL);
	} else if (strcasecmp(name, "authzid") == 0) {
	    _plug_strdup(sparams->utils, value, &authorization_id, NULL);
	} else if (strcasecmp(name, "cnonce") == 0) {
	    _plug_strdup(sparams->utils, value, (char **) &cnonce, NULL);
	} else if (strcasecmp(name, "nc") == 0) {
	    if (htoi((unsigned char *) value, &noncecount) != SASL_OK) {
		SETERROR(sparams->utils,
			 "error converting hex to int");
		result = SASL_BADAUTH;
		goto FreeAllMem;
	    }
	} else if (strcasecmp(name, "realm") == 0) {
	    if (realm) {
		SETERROR(sparams->utils,
			 "duplicate realm: authentication aborted");
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	    _plug_strdup(sparams->utils, value, &realm, NULL);
	} else if (strcasecmp(name, "nonce") == 0) {
	    _plug_strdup(sparams->utils, value, (char **) &nonce, NULL);
	} else if (strcasecmp(name, "qop") == 0) {
	    if (qop) {
		SETERROR(sparams->utils,
			 "duplicate qop: authentication aborted");
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	    _plug_strdup(sparams->utils, value, &qop, NULL);
	} else if (strcasecmp(name, "digest-uri") == 0 ||  /* per RFC 2831 */
		   (text->http_mode &&
		    strcasecmp(name, "uri") == 0)) {	   /* per RFC 2617 */
            size_t service_len;

	    if (digesturi) {
		SETERROR(sparams->utils,
			 "duplicate digest-uri: authentication aborted");
		result = SASL_FAIL;
		goto FreeAllMem;
	    }

	    _plug_strdup(sparams->utils, value, &digesturi, NULL);

	    if (text->http_mode && request && request->uri) {
		/* Verify digest-uri matches HTTP request (per RFC 2617) */
		if (strcmp(digesturi, request->uri)) {
		    result = SASL_BADAUTH;
		    SETERROR(sparams->utils, 
			     "bad digest-uri: doesn't match HTTP request");
		    goto FreeAllMem;
		}
	    }
	    else {
		/* Verify digest-uri format (per RFC 2831):
		 *
		 * digest-uri-value  = serv-type "/" host [ "/" serv-name ]
		 */

		/* make sure it's the service that we're expecting */
		service_len = strlen(sparams->service);
		if (strncasecmp(digesturi, sparams->service, service_len) ||
		    digesturi[service_len] != '/') {
		    result = SASL_BADAUTH;
		    SETERROR(sparams->utils, 
			     "bad digest-uri: doesn't match service");
		    goto FreeAllMem;
		}

		/* xxx we don't verify the hostname component */

		rfc2831_request.uri = digesturi;
	    }
            
	} else if (strcasecmp(name, "response") == 0) {
	    _plug_strdup(sparams->utils, value, &response, NULL);
	} else if (strcasecmp(name, "cipher") == 0) {
	    _plug_strdup(sparams->utils, value, &cipher, NULL);
	} else if (strcasecmp(name, "maxbuf") == 0) {
	    maxbuf_count++;
	    if (maxbuf_count != 1) {
		result = SASL_BADAUTH;
		SETERROR(sparams->utils,
			 "duplicate maxbuf: authentication aborted");
		goto FreeAllMem;
	    } else if (str2ul32 (value, &client_maxbuf) == FALSE) {
		result = SASL_BADAUTH;
		SETERROR(sparams->utils, "invalid maxbuf parameter");
		goto FreeAllMem;
	    } else {
		if (client_maxbuf <= 16) {
		    result = SASL_BADAUTH;
		    SETERROR(sparams->utils,
			     "maxbuf parameter too small");
		    goto FreeAllMem;
		}

		if (client_maxbuf > MAX_SASL_BUFSIZE) {
		    result = SASL_BADAUTH;
		    SETERROR(sparams->utils,
			     "maxbuf parameter too big");
		    goto FreeAllMem;
		}
	    }
	} else if (strcasecmp(name, "charset") == 0) {
	    if (strcasecmp(value, "utf-8") != 0) {
		SETERROR(sparams->utils, "client doesn't support UTF-8");
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	    _plug_strdup(sparams->utils, value, &charset, NULL);
	} else if (strcasecmp(name,"algorithm") == 0) {
	    /* per RFC 2831: algorithm MUST be ignored if received */
	    if (text->http_mode && strcasecmp(value, "md5-sess") != 0) {
		/* per RFC 2617: algorithm MUST match that sent in challenge */
		SETERROR(sparams->utils, "'algorithm' isn't 'md5-sess'");
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	} else {
	    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
				"DIGEST-MD5 unrecognized pair %s/%s: ignoring",
				name, value);
	}
    }
    
    /*
     * username         = "username" "=" <"> username-value <">
     * username-value   = qdstr-val
     * cnonce           = "cnonce" "=" <"> cnonce-value <"> 
     * cnonce-value     = qdstr-val
     * nonce-count      = "nc" "=" nc-value
     * nc-value         = 8LHEX
     * qop              = "qop" "=" qop-value
     * digest-uri       = "digest-uri" "=" digest-uri-value
     * digest-uri-value = serv-type "/" host [ "/" serv-name ]
     * serv-type        = 1*ALPHA
     * host             = 1*( ALPHA | DIGIT | "-" | "." )
     * service          = host
     * response         = "response" "=" <"> response-value <">
     * response-value   = 32LHEX
     * LHEX             = "0" | "1" | "2" | "3" | "4" | "5" |
     * "6" | "7" | "8" | "9" | "a" | "b" | "c" | "d" | "e" | "f"
     * cipher           = "cipher" "=" cipher-value
     */
    /* Verifing that all required parameters were received */
    if ((username == NULL)) {
	SETERROR(sparams->utils, "required parameters missing: username");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }
    if ((nonce == NULL)) {
	SETERROR(sparams->utils, "required parameters missing: nonce");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }
    if ((noncecount == 0)) {
	SETERROR(sparams->utils, "required parameters missing: noncecount");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }
    if ((cnonce == NULL)) {
	SETERROR(sparams->utils, "required parameters missing: cnonce");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }
    if ((digesturi == NULL)) {
	SETERROR(sparams->utils, "required parameters missing: digesturi");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }
    if ((response == NULL)) {
	SETERROR(sparams->utils, "required parameters missing: response");
	result = SASL_BADAUTH;
	goto FreeAllMem;
    }

    if (realm == NULL) {
        /* From 2831bis:
           If the directive is missing, "realm-value" will set to
           the empty string when computing A1. */
	_plug_strdup(sparams->utils, "", &realm, NULL);
	sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
			"The client didn't send a realm, assuming empty string.");
#if 0
        if (text->realm[0] != '\0') {
            SETERROR(sparams->utils,
		 "realm changed: authentication aborted");
            result = SASL_BADAUTH;
            goto FreeAllMem;
        }
#endif
    }

    if (!text->nonce && text->reauth->timeout && text->reauth->size > 0) {
	unsigned val = hash((char *) nonce) % text->reauth->size;

	/* reauth attempt or continuation of HTTP Digest on a
	   non-persistent connection, see if we have any info for this nonce */
	if (sparams->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */
	    if (text->reauth->e[val].realm &&
		!strcmp(realm, text->reauth->e[val].realm) &&
		((text->reauth->e[val].nonce_count == 1) ||
		 (text->reauth->e[val].authid &&
		  !strcmp(username, text->reauth->e[val].authid)))) {

		_plug_strdup(sparams->utils, text->reauth->e[val].realm,
			     &text->realm, NULL);
		_plug_strdup(sparams->utils, (char *) text->reauth->e[val].nonce,
			     (char **) &text->nonce, NULL);
		text->nonce_count = text->reauth->e[val].nonce_count;
#if 0  /* XXX  Neither RFC 2617 nor RFC 2831 state that the cnonce
	  needs to remain constant for subsequent authentication to work */
		_plug_strdup(sparams->utils, (char *) text->reauth->e[val].cnonce,
			     (char **) &text->cnonce, NULL);
#endif
		stext->timestamp = text->reauth->e[val].u.s.timestamp;
	    }
	    sparams->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
	}

	if (!text->nonce) {
	    /* we don't have any reauth info */
	    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
				"No reauth info for '%s' found", nonce);

	    /* we will continue processing the response to determine
	       if the client knows the password and return stale accordingly */
	}
    }

    /* Sanity check the parameters */
    if (text->nonce) {
	/* CLAIM: realm is not NULL below */
	if (text->realm == NULL) {
	    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
				"The client specifies a realm when the server hasn't provided one. Using client's realm.");
	    _plug_strdup(sparams->utils, realm, &text->realm, NULL);
	} else if ((strcmp(realm, text->realm) != 0) &&
		   /* XXX - Not sure why the check for text->realm not being empty is needed,
		      as it should always be non-empty */
		   (text->realm[0] != 0)) {

	    client_ignores_realm = 1;
	    sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG,
				"The client tries to override server provided realm");
	    if (text->realm) sparams->utils->free(text->realm);
	    _plug_strdup(sparams->utils, realm, &text->realm, NULL);
	}

	if (strcmp((char *) nonce, (char *) text->nonce) != 0) {
	    SETERROR(sparams->utils,
		     "nonce changed: authentication aborted");
	    result = SASL_BADAUTH;
	    goto FreeAllMem;
	}
#if 0	/* XXX  Possible replay attack, but we will continue processing
	 * the response to determine if the client knows the password and
	 return stale accordingly */
	if (noncecount != text->nonce_count) {
	    SETERROR(sparams->utils,
		     "incorrect nonce-count: authentication aborted");
	    result = SASL_BADAUTH;
	    goto FreeAllMem;
	}
#endif
#if 0	/* XXX  Neither RFC 2617 nor RFC 2831 state that the cnonce
	   needs to remain constant for subsequent authentication to work */
	if (text->cnonce && strcmp((char *) cnonce, (char *) text->cnonce) != 0) {
	    SETERROR(sparams->utils,
		     "cnonce changed: authentication aborted");
	    result = SASL_BADAUTH;
	    goto FreeAllMem;
	}
#endif
    }
	    
    result = sparams->utils->prop_request(sparams->propctx, password_request);
    if(result != SASL_OK) {
	SETERROR(sparams->utils, "unable to obtain user password");
	goto FreeAllMem;
    }
    
    /* this will trigger the getting of the aux properties */
    /* Note that if we don't have an authorization id, we don't use it... */

    if (client_ignores_realm) {
	if (strlen(text->realm) == 0) {
	    /* Don't put @ at the end of the username, if the realm is empty */
	    _plug_strdup(sparams->utils, username, &full_username, NULL);
	} else {
	    full_username = (char *) sparams->utils->malloc(strlen(username) +
					strlen(text->realm) + 2);
	    full_username[0] = '\0';
	    sprintf (full_username, "%s@%s", username, text->realm);
	}
	internal_username = full_username;
    } else {
	internal_username = username;
    }

    canon_flags = SASL_CU_AUTHID;
    if (!authorization_id || !*authorization_id) {
	canon_flags |= SASL_CU_AUTHZID;
    }

    result = sparams->canon_user(sparams->utils->conn,
				 internal_username,
				 0,
				 canon_flags,
				 oparams);
    if (result != SASL_OK) {
	SETERROR(sparams->utils, "unable to canonify user and get auxprops");
	goto FreeAllMem;
    }
    
    if (authorization_id != NULL && *authorization_id != '\0') {
	result = sparams->canon_user(sparams->utils->conn,
				     authorization_id, 0, SASL_CU_AUTHZID,
				     oparams);
    }
    if (result != SASL_OK) {
	SETERROR(sparams->utils, "unable to canonify authorization ID");
	goto FreeAllMem;
    }
    
    result = sparams->utils->prop_getnames(sparams->propctx, password_request,
					   auxprop_values);
    if (result < 0 ||
        ((!auxprop_values[0].name || !auxprop_values[0].values)
#if defined(OBSOLETE_DIGEST_ATTR)
         && (!auxprop_values[1].name || !auxprop_values[1].values)
#endif
         )) {
	/* We didn't find this username */
	sparams->utils->seterror(sparams->utils->conn, 0,
				 "no secret in database");
	result = sparams->transition ? SASL_TRANS : SASL_NOUSER;
	goto FreeAllMem;
    }
    
    if (auxprop_values[0].name && auxprop_values[0].values) {
	len = strlen(auxprop_values[0].values[0]);
	if (len == 0) {
	    sparams->utils->seterror(sparams->utils->conn,0,
				     "empty secret");
	    result = SASL_FAIL;
	    goto FreeAllMem;
	}
	
	sec = sparams->utils->malloc(sizeof(sasl_secret_t) + len);
	if (!sec) {
	    SETERROR(sparams->utils, "unable to allocate secret");
	    result = SASL_FAIL;
	    goto FreeAllMem;
	}
	
	sec->len = (unsigned) len;
	strncpy((char *) sec->data, auxprop_values[0].values[0], len + 1); 
	
	/*
	 * Verifying response obtained from client
	 * 
	 * H_URP = H({ username-value,":",realm-value,":",passwd}) sec->data
	 * contains H_URP
	 */
	
	/* Calculate the secret from the plaintext password */
	{
	    /*
	     * Secret = { H( { username-value, ":", realm-value, ":", passwd } ) }
	     *
	     * (used to build A1)
	     */
	    
	    Try_8859_1 = DigestCalcSecret(sparams->utils,
					  (unsigned char *) username,
					  (unsigned char *) realm,
					  sec->data,
					  sec->len,
					  FALSE,
					  Secret);
	    Secret[HASHLEN] = '\0';
	}
	if (Try_8859_1) {
	    /*
	     * Secret = { H( { username-value, ":", realm-value, ":", passwd } ) }
	     *
	     * (used to build A1)
	     */
	    
	    DigestCalcSecret(sparams->utils,
			     (unsigned char *) username,
			     (unsigned char *) realm,
			     sec->data,
			     sec->len,
			     TRUE,
			     SecretBogus);
	    SecretBogus[HASHLEN] = '\0';
	}
	
	/* We're done with sec now. Let's get rid of it */
	_plug_free_secret(sparams->utils, &sec);
#if defined(OBSOLETE_DIGEST_ATTR)
    } else if (auxprop_values[1].name && auxprop_values[1].values) {
        /* NB: This will most likely fail for clients that
	   choose to ignore server-advertised realm */
	memcpy(Secret, auxprop_values[1].values[0], HASHLEN);
	Secret[HASHLEN] = '\0';
#endif
    } else {
	sparams->utils->seterror(sparams->utils->conn, 0,
				 "Have neither type of secret");
	return SASL_FAIL;
    } 
    
    /* erase the plaintext password */
    sparams->utils->prop_erase(sparams->propctx, password_request[0]);

    /* defaulting qop to "auth" if not specified */
    if (qop == NULL) {
	_plug_strdup(sparams->utils, "auth", &qop, NULL);      
    }

    if (oparams->mech_ssf > 1) {
	/* Remember the old cipher free function (if any).
	   It will be called later, once we are absolutely
	   sure that authentication was successful. */
	old_cipher_free = text->cipher_free;
	/* free the old cipher context first */
    }
    
    /* check which layer/cipher to use */
    if ((!strcasecmp(qop, "auth-conf")) && (cipher != NULL)) {
	/* see what cipher was requested */
	struct digest_cipher *cptr;
	
	cptr = available_ciphers;
	while (cptr->name) {
	    /* find the cipher requested & make sure it's one we're happy
	       with by policy */
	    if (!strcasecmp(cipher, cptr->name) && 
		stext->requiressf <= cptr->ssf &&
		stext->limitssf >= cptr->ssf) {
		/* found it! */
		break;
	    }
	    cptr++;
	}
	
	if (cptr->name) {
	    text->cipher_enc = cptr->cipher_enc;
	    text->cipher_dec = cptr->cipher_dec;
	    text->cipher_init = cptr->cipher_init;
	    text->cipher_free = cptr->cipher_free;
	    oparams->mech_ssf = cptr->ssf;
	    n = cptr->n;
	} else {
	    /* erg? client requested something we didn't advertise! */
	    sparams->utils->log(sparams->utils->conn, SASL_LOG_WARN,
				"protocol violation: client requested invalid cipher");
	    SETERROR(sparams->utils, "client requested invalid cipher");
	    /* Mark that we attempted security layer negotiation */
	    oparams->mech_ssf = 2;
	    result = SASL_FAIL;
	    goto FreeAllMem;
	}
	
	oparams->encode=&digestmd5_encode;
	oparams->decode=&digestmd5_decode;
    } else if (!strcasecmp(qop, "auth-int") &&
	       stext->requiressf <= 1 && stext->limitssf >= 1) {
	oparams->encode = &digestmd5_encode;
	oparams->decode = &digestmd5_decode;
	oparams->mech_ssf = 1;
    } else if (!strcasecmp(qop, "auth") && stext->requiressf == 0) {
	oparams->encode = NULL;
	oparams->decode = NULL;
	oparams->mech_ssf = 0;
    } else {
	SETERROR(sparams->utils,
		 "protocol violation: client requested invalid qop");
	result = SASL_FAIL;
	goto FreeAllMem;
    }
    
    serverresponse = create_response(text,
				     sparams->utils,
				     nonce,
				     noncecount,
				     cnonce,
				     qop,
				     request,
				     Secret,
				     authorization_id,
				     &text->response_value);
    
    if (serverresponse == NULL) {
	SETERROR(sparams->utils, "internal error: unable to create response");
	result = SASL_NOMEM;
	goto FreeAllMem;
    }
    
    /* if ok verified */
    if (strcmp(serverresponse, response) != 0) {
	if (Try_8859_1) {
            sparams->utils->free(serverresponse);
	    serverresponse = create_response(text,
					     sparams->utils,
					     nonce,
					     noncecount,
					     cnonce,
					     qop,
					     request,
					     SecretBogus,
					     authorization_id,
					     &text->response_value);
	    
	    if (serverresponse == NULL) {
		SETERROR(sparams->utils, "internal error: unable to create response");
		result = SASL_NOMEM;
		goto FreeAllMem;
	    }
	    
	    /* if ok verified */
	    if (strcmp(serverresponse, response) != 0) {
		SETERROR(sparams->utils,
			 "client response doesn't match what we generated (tried bogus)");
		result = SASL_BADAUTH;
		
		goto FreeAllMem;
	    }
	    
	} else {	    
	    SETERROR(sparams->utils,
		     "client response doesn't match what we generated");
	    result = SASL_BADAUTH;
	    
	    goto FreeAllMem;
	}
    }

    /* see if our nonce expired */
    if (!text->nonce ||
	(noncecount != text->nonce_count) ||
	(text->reauth->timeout &&
	 time(0) - stext->timestamp > text->reauth->timeout)) {
	if (!text->nonce) SETERROR(sparams->utils, "no cached server nonce");
	else if (noncecount != text->nonce_count)
	    SETERROR(sparams->utils, "incorrect nonce-count");
	else SETERROR(sparams->utils, "server nonce expired");
	stext->stale = 1;
	result = SASL_BADAUTH;

	goto FreeAllMem;
    }

    /*
     * nothing more to do; authenticated set oparams information
     */
    oparams->doneflag = 1;
    oparams->maxoutbuf = client_maxbuf - 4;
    if (oparams->mech_ssf > 1) {
	/* MAC block (privacy) */
	oparams->maxoutbuf -= 25;
    } else if(oparams->mech_ssf == 1) {
	/* MAC block (integrity) */
	oparams->maxoutbuf -= 16;
    }
    
    oparams->param_version = 0;
    
    text->seqnum = 0;		/* for integrity/privacy */
    text->rec_seqnum = 0;	/* for integrity/privacy */
    text->utils = sparams->utils;

    /* Free the old security layer, if any */
    if (old_cipher_free) old_cipher_free(text);

    /* used by layers */
    _plug_decode_init(&text->decode_context, text->utils,
		      sparams->props.maxbufsize ? sparams->props.maxbufsize :
		      DEFAULT_BUFSIZE);

    if (oparams->mech_ssf > 0) {
	unsigned char enckey[16];
	unsigned char deckey[16];
	
	create_layer_keys(text, sparams->utils,text->HA1,n,enckey,deckey);
	
	/* initialize cipher if need be */
	if (text->cipher_init) {
	    if (text->cipher_init(text, enckey, deckey) != SASL_OK) {
		sparams->utils->seterror(sparams->utils->conn, 0,
					 "couldn't init cipher");
	    }
	}
    }
    
    /*
     * The server receives and validates the "digest-response". The server
     * checks that the nonce-count is "00000001". If it supports subsequent
     * authentication, it saves the value of the nonce and the nonce-count.
     */
    
    /*
     * The "username-value", "realm-value" and "passwd" are encoded according
     * to the value of the "charset" directive. If "charset=UTF-8" is
     * present, and all the characters of either "username-value" or "passwd"
     * are in the ISO 8859-1 character set, then it must be converted to
     * UTF-8 before being hashed. A sample implementation of this conversion
     * is in section 8.
     */
    
    /* add to challenge */
    {
	unsigned resplen = 0;

	if (add_to_challenge(sparams->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "rspauth", (unsigned char *) text->response_value,
			     text->http_mode ? TRUE : FALSE) != SASL_OK) {
	    SETERROR(sparams->utils, "internal error: add_to_challenge failed");
	    result = SASL_FAIL;
	    goto FreeAllMem;
	}

	if (text->http_mode) {
	    /* per RFC 2617 */
	    char ncvalue[10];

	    if (add_to_challenge(sparams->utils,
				 &text->out_buf, &text->out_buf_len, &resplen,
				 "cnonce", cnonce, TRUE) != SASL_OK) {
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	    snprintf(ncvalue, sizeof(ncvalue), "%08x", text->nonce_count);
	    if (add_to_challenge(sparams->utils,
				 &text->out_buf, &text->out_buf_len, &resplen,
				 "nc", (unsigned char *) ncvalue, FALSE) != SASL_OK) {
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	    if (add_to_challenge(sparams->utils,
				 &text->out_buf, &text->out_buf_len, &resplen,
				 "qop", (unsigned char *) qop, TRUE) != SASL_OK) {
		result = SASL_FAIL;
		goto FreeAllMem;
	    }
	}

	/* self check */
	if (strlen(text->out_buf) > 2048) {
	    result = SASL_FAIL;
	    goto FreeAllMem;
	}
    }
    
    *serveroutlen = (unsigned) strlen(text->out_buf);
    *serverout = text->out_buf;
	
    result = SASL_OK;

  FreeAllMem:
    if (clientinlen > 0 &&
	text->reauth->timeout &&
	sparams->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */

	/* Look for an entry for the nonce value */
	unsigned val = hash((char *) nonce) % text->reauth->size;

	switch (result) {
	case SASL_OK:
	    /* successful auth, setup for future reauth */
	    if (text->nonce_count == 1) {
		/* successful initial auth, create new entry */
		clear_reauth_entry(&text->reauth->e[val], SERVER, sparams->utils);
		text->reauth->e[val].authid = username; username = NULL;
		text->reauth->e[val].realm = text->realm; text->realm = NULL;
		text->reauth->e[val].nonce = text->nonce; text->nonce = NULL;
		text->reauth->e[val].cnonce = cnonce; cnonce = NULL;
	    }
	    if (text->nonce_count < text->reauth->e[val].nonce_count) {
		/* paranoia.  prevent replay attacks */
		clear_reauth_entry(&text->reauth->e[val], SERVER, sparams->utils);
	    }
	    else {
		text->reauth->e[val].nonce_count = ++text->nonce_count;
		text->reauth->e[val].u.s.timestamp = time(0);
	    }
	    break;
	default:
	    if (text->nonce_count > 1) {
		/* failed reauth, clear entry */
		clear_reauth_entry(&text->reauth->e[val], SERVER, sparams->utils);
	    }
	    else {
		/* failed initial auth, leave existing cache */
	    }
	}
	sparams->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
    }

    /* free everything */
    if (in_start) sparams->utils->free (in_start);
    
    if (full_username != NULL) 
	sparams->utils->free (full_username);
    if (username != NULL)
	sparams->utils->free (username);
    if (authorization_id != NULL)
	sparams->utils->free (authorization_id);
    if (realm != NULL)
	sparams->utils->free (realm);
    if (nonce != NULL)
	sparams->utils->free (nonce);
    if (cnonce != NULL)
	sparams->utils->free (cnonce);
    if (response != NULL)
	sparams->utils->free (response);
    if (cipher != NULL)
	sparams->utils->free (cipher);
    if (serverresponse != NULL)
	sparams->utils->free(serverresponse);
    if (charset != NULL)
	sparams->utils->free (charset);
    if (digesturi != NULL)
	sparams->utils->free (digesturi);
    if (qop!=NULL)
	sparams->utils->free (qop);  
    if (sec)
	_plug_free_secret(sparams->utils, &sec);
    
    return result;
}

static int digestmd5_server_mech_step(void *conn_context,
				      sasl_server_params_t *sparams,
				      const char *clientin,
				      unsigned clientinlen,
				      const char **serverout,
				      unsigned *serveroutlen,
				      sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) conn_context;
    server_context_t *stext = (server_context_t *) conn_context;
    
    *serverout = NULL;
    *serveroutlen = 0;
    
    if (clientinlen > 4096) return SASL_BADPROT;

    if (text == NULL) {
	return SASL_BADPROT;
    }

    switch (text->state) {
	
    case 1:
	/* setup SSF limits */
	if (!text->http_mode &&		/* HTTP Digest doesn't need buffer */
	    !sparams->props.maxbufsize) {
	    stext->limitssf = 0;
	    stext->requiressf = 0;
	} else {
	    if (sparams->props.max_ssf < sparams->external_ssf) {
		stext->limitssf = 0;
	    } else {
		stext->limitssf =
		    sparams->props.max_ssf - sparams->external_ssf;
	    }
	    if (sparams->props.min_ssf < sparams->external_ssf) {
		stext->requiressf = 0;
	    } else {
		stext->requiressf =
		    sparams->props.min_ssf - sparams->external_ssf;
	    }
	}

        if (clientin && text->reauth->timeout) {
	    /* here's where we attempt fast reauth if possible */
	    if (digestmd5_server_mech_step2(stext, sparams,
					    clientin, clientinlen,
					    serverout, serveroutlen,
					    oparams) == SASL_OK) {
		return SASL_OK;
	    }

	    sparams->utils->log(NULL, SASL_LOG_WARN,
				"DIGEST-MD5 reauth failed\n");

	    /* re-initialize everything for a fresh start */
	    memset(oparams, 0, sizeof(sasl_out_params_t));
	    if (text->nonce) sparams->utils->free(text->nonce);
	    if (text->realm) sparams->utils->free(text->realm);
	    text->realm = NULL;
	    text->nonce = NULL;

	    /* fall through and issue challenge */
	}

	return digestmd5_server_mech_step1(stext, sparams,
					   clientin, clientinlen,
					   serverout, serveroutlen, oparams);
	
    case 2:
	return digestmd5_server_mech_step2(stext, sparams,
					   clientin, clientinlen,
					   serverout, serveroutlen, oparams);
	
    default:
	sparams->utils->log(NULL, SASL_LOG_ERR,
			    "Invalid DIGEST-MD5 server step %d\n", text->state);
	return SASL_FAIL;
    }
    
    return SASL_FAIL; /* should never get here */
}

static void digestmd5_server_mech_dispose(void *conn_context,
					  const sasl_utils_t *utils)
{
    server_context_t *stext = (server_context_t *) conn_context;
    
    if (!stext || !utils) return;
    
    digestmd5_common_mech_dispose(conn_context, utils);
}

static sasl_server_plug_t digestmd5_server_plugins[] =
{
    {
	"DIGEST-MD5",			/* mech_name */
#ifdef WITH_RC4
	128,				/* max_ssf */
#elif defined(WITH_DES)
	112,
#else 
	1,
#endif
	SASL_SEC_NOPLAINTEXT
	| SASL_SEC_NOANONYMOUS
	| SASL_SEC_MUTUAL_AUTH,		/* security_flags */
	SASL_FEAT_ALLOWS_PROXY
	| SASL_FEAT_SUPPORTS_HTTP,	/* features */
	&server_glob_context,		/* glob_context */
	&digestmd5_server_mech_new,	/* mech_new */
	&digestmd5_server_mech_step,	/* mech_step */
	&digestmd5_server_mech_dispose,	/* mech_dispose */
	&digestmd5_common_mech_free,	/* mech_free */
	NULL,				/* setpass */
	NULL,				/* user_query */
	NULL,				/* idle */
	NULL,				/* mech avail */
	NULL				/* spare */
    }
};

int digestmd5_server_plug_init(sasl_utils_t *utils,
			       int maxversion,
			       int *out_version,
			       sasl_server_plug_t **pluglist,
			       int *plugcount) 
{
    reauth_cache_t *reauth_cache;
    const char *timeout = NULL;
    unsigned int len;

    if (maxversion < SASL_SERVER_PLUG_VERSION) {
	return SASL_BADVERS;
    }

    /* reauth cache */
    reauth_cache = utils->malloc(sizeof(reauth_cache_t));
    if (reauth_cache == NULL) {
	return SASL_NOMEM;
    }
    memset(reauth_cache, 0, sizeof(reauth_cache_t));
    reauth_cache->i_am = SERVER;

    /* fetch and canonify the reauth_timeout */
    utils->getopt(utils->getopt_context, "DIGEST-MD5", "reauth_timeout",
		  &timeout, &len);
    if (timeout) {
	reauth_cache->timeout = (time_t) 60 * strtol(timeout, NULL, 10);
    }
    if (reauth_cache->timeout < 0) {
	reauth_cache->timeout = 0;
    }

    if (reauth_cache->timeout) {
	/* mutex */
	reauth_cache->mutex = utils->mutex_alloc();
	if (!reauth_cache->mutex) {
	    utils->free(reauth_cache);
	    return SASL_FAIL;
	}

	/* entries */
	reauth_cache->size = 100;
	reauth_cache->e = utils->malloc(reauth_cache->size *
					sizeof(reauth_entry_t));
	if (reauth_cache->e == NULL) {
	    utils->mutex_free(reauth_cache->mutex);
	    utils->free(reauth_cache);
	    return SASL_NOMEM;
	}
	memset(reauth_cache->e, 0, reauth_cache->size * sizeof(reauth_entry_t));
    }

    ((digest_glob_context_t *) digestmd5_server_plugins[0].glob_context)->reauth = reauth_cache;

    *out_version = SASL_SERVER_PLUG_VERSION;
    *pluglist = digestmd5_server_plugins;
    *plugcount = 1;
    
    return SASL_OK;
}

/*****************************  Client Section  *****************************/

typedef struct client_context {
    context_t common;

    sasl_secret_t *password;	/* user password */
    unsigned int free_password; /* set if we need to free password */

    int protection;
    struct digest_cipher *cipher;
    unsigned long server_maxbuf;

    /* for HTTP mode (RFC 2617) only */
    char *algorithm;
    unsigned char *opaque;
} client_context_t;

static digest_glob_context_t client_glob_context;

/* calculate H(A1) as per spec */
static void DigestCalcHA1(context_t * text,
			  const sasl_utils_t * utils,
			  char *pszAlg,
			  unsigned char *pszUserName,
			  unsigned char *pszRealm,
			  sasl_secret_t * pszPassword,
			  unsigned char *pszAuthorization_id,
			  unsigned char *pszNonce,
			  unsigned char *pszCNonce,
			  HASHHEX SessionKey)
{
    MD5_CTX         Md5Ctx;
    HASH            HA1;
    
    DigestCalcSecret(utils,
		     pszUserName,
		     pszRealm,
		     (unsigned char *) pszPassword->data,
		     pszPassword->len,
		     FALSE,
		     HA1);
    
    if (!text->http_mode ||				    /* per RFC 2831 */
	(pszAlg && strcasecmp(pszAlg, "md5-sess") == 0)) {  /* per RFC 2617 */
	/* calculate the session key */
	utils->MD5Init(&Md5Ctx);
	if (text->http_mode) {
	    /* per RFC 2617 Errata ID 1649 */
	    HASHHEX HA1Hex;
    
	    CvtHex(HA1, HA1Hex);
	    utils->MD5Update(&Md5Ctx, HA1Hex, HASHHEXLEN);
	}
	else {
	    /* per RFC 2831 */
	    utils->MD5Update(&Md5Ctx, HA1, HASHLEN);
	}
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, pszNonce, (unsigned) strlen((char *) pszNonce));
	utils->MD5Update(&Md5Ctx, COLON, 1);
	utils->MD5Update(&Md5Ctx, pszCNonce, (unsigned) strlen((char *) pszCNonce));
	if (pszAuthorization_id != NULL) {
	    utils->MD5Update(&Md5Ctx, COLON, 1);
	    utils->MD5Update(&Md5Ctx, pszAuthorization_id, 
			     (unsigned) strlen((char *) pszAuthorization_id));
	}
	utils->MD5Final(HA1, &Md5Ctx);
    }
    
    CvtHex(HA1, SessionKey);
    
    /* xxx rc-* use different n */
    
    /* save HA1 because we'll need it for the privacy and integrity keys */
    memcpy(text->HA1, HA1, sizeof(HASH));
    
}

static char *calculate_response(context_t * text,
				const sasl_utils_t * utils,
				char *algorithm,
				unsigned char *username,
				unsigned char *realm,
				unsigned char *nonce,
				unsigned int ncvalue,
				unsigned char *cnonce,
				char *qop,
				const sasl_http_request_t *request,
				sasl_secret_t * passwd,
				unsigned char *authorization_id,
				char **response_value)
{
    HASHHEX         SessionKey;
    HASH            EntityHash;
    HASHHEX         HEntity;
    HASHHEX         Response;
    char           *result;
    
    /* Verifing that all parameters was defined */
    if(!username || !cnonce || !nonce || !ncvalue || !request || !passwd) {
	PARAMERROR( utils );
	return NULL;
    }
    
    if (realm == NULL) {
	/* a NULL realm is equivalent to the empty string */
	realm = (unsigned char *) "";
    }
    
    if (qop == NULL) {
	/* default to a qop of just authentication */
	qop = "auth";
    }
    
    DigestCalcHA1(text,
		  utils,
		  algorithm,
		  username,
		  realm,
		  passwd,
		  authorization_id,
		  nonce,
		  cnonce,
		  SessionKey);
    
    if (text->http_mode) {
	/* per RFC 2617 */
	MD5_CTX Md5Ctx;

	utils->MD5Init(&Md5Ctx);
	utils->MD5Update(&Md5Ctx, request->entity, request->elen);
	utils->MD5Final(EntityHash, &Md5Ctx);
    }
    else {
	/* per RFC 2831 */
	memset(EntityHash, 0, HASHLEN);
    }
    CvtHex(EntityHash, HEntity);

    DigestCalcResponse(utils,
		       SessionKey,/* HEX(H(A1)) */
		       nonce,	/* nonce from server */
		       ncvalue,	/* 8 hex digits */
		       cnonce,	/* client nonce */
		       (unsigned char *) qop,	/* qop-value: "", "auth",
						 * "auth-int" */
		       (unsigned char *) request->uri,	/* requested URL */
		       (unsigned char *) request->method,
		       HEntity,	/* H(entity body) if qop="auth-int" */
		       Response	/* request-digest or response-digest */
	);
    
    result = utils->malloc(HASHHEXLEN + 1);
    memcpy(result, Response, HASHHEXLEN);
    result[HASHHEXLEN] = 0;
    
    if (response_value != NULL) {
	char * new_response_value;

	DigestCalcResponse(utils,
			   SessionKey,	/* HEX(H(A1)) */
			   nonce,	/* nonce from server */
			   ncvalue,	/* 8 hex digits */
			   cnonce,	/* client nonce */
			   (unsigned char *) qop,	/* qop-value: "", "auth",
							 * "auth-int" */
			   (unsigned char *) request->uri,	/* requested URL */
			   NULL,
			   HEntity,	/* H(entity body) if qop="auth-int" */
			   Response	/* request-digest or response-digest */
	    );
	
	new_response_value = utils->realloc(*response_value, HASHHEXLEN + 1);
	if (new_response_value == NULL) {
	    free (*response_value);
	    *response_value = NULL;
	    return NULL;
	}
	*response_value = new_response_value;
	
	memcpy(*response_value, Response, HASHHEXLEN);
	(*response_value)[HASHHEXLEN] = 0;
	
    }
    
    return result;
}

static int make_client_response(context_t *text,
				sasl_client_params_t *params,
				sasl_out_params_t *oparams)
{
    client_context_t *ctext = (client_context_t *) text;
    char *qop = NULL;
    unsigned nbits = 0;
    char  *digesturi = NULL;
    bool            IsUTF8 = FALSE;
    char           ncvalue[10];
    char           maxbufstr[64];
    char           *response = NULL;
    unsigned        resplen = 0;
    int result = SASL_OK;
    cipher_free_t  *old_cipher_free = NULL;
    sasl_http_request_t rfc2831_request;
    const sasl_http_request_t *request;

    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 make_client_response()");

    if (oparams->mech_ssf > 1) {
	/* Remember the old cipher free function (if any).
	   It will be called later, once we are absolutely
	   sure that authentication was successful. */
	old_cipher_free = text->cipher_free;
	/* free the old cipher context first */
    }

    switch (ctext->protection) {
    case DIGEST_PRIVACY:
	qop = "auth-conf";
	oparams->encode = &digestmd5_encode; 
	oparams->decode = &digestmd5_decode;
	oparams->mech_ssf = ctext->cipher->ssf;

	nbits = ctext->cipher->n;
	text->cipher_enc = ctext->cipher->cipher_enc;
	text->cipher_dec = ctext->cipher->cipher_dec;
	text->cipher_free = ctext->cipher->cipher_free;
	text->cipher_init = ctext->cipher->cipher_init;
	break;
    case DIGEST_INTEGRITY:
	qop = "auth-int";
	oparams->encode = &digestmd5_encode;
	oparams->decode = &digestmd5_decode;
	oparams->mech_ssf = 1;
	break;
    case DIGEST_NOLAYER:
    default:
	qop = "auth";
	oparams->encode = NULL;
	oparams->decode = NULL;
	oparams->mech_ssf = 0;
    }

    if (text->http_mode) {
	/* per RFC 2617 (HTTP Request as set by calling application) */
	request = params->http_request;
    }
    else {
	/* per RFC 2831 */
	digesturi = params->utils->malloc(strlen(params->service) + 1 +
					  strlen(params->serverFQDN) + 1 +
					  1);
	if (digesturi == NULL) {
	    result = SASL_NOMEM;
	    goto FreeAllocatedMem;
	}

	/* allocated exactly this. safe */
	strcpy(digesturi, params->service);
	strcat(digesturi, "/");
	strcat(digesturi, params->serverFQDN);
	/*
	 * strcat (digesturi, "/"); strcat (digesturi, params->serverFQDN);
	 */

	rfc2831_request.method = "AUTHENTICATE";
	rfc2831_request.uri = digesturi;
	rfc2831_request.entity = NULL;
	rfc2831_request.elen = 0;
	rfc2831_request.non_persist = 0;
	request = &rfc2831_request;
    }

    /* response */
    response =
	calculate_response(text,
			   params->utils,
			   ctext->algorithm,
			   (unsigned char *) oparams->authid,
			   (unsigned char *) text->realm,
			   text->nonce,
			   text->nonce_count,
			   text->cnonce,
			   qop,
			   request,
			   ctext->password,
			   strcmp(oparams->user, oparams->authid) ?
			   (unsigned char *) oparams->user : NULL,
			   &text->response_value);
    
    
    resplen = 0;
    if (text->out_buf) params->utils->free(text->out_buf);
    text->out_buf = NULL;
    text->out_buf_len = 0;
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "username", (unsigned char *) oparams->authid,
			 TRUE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }

    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "realm", (unsigned char *) text->realm,
			 TRUE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    if (strcmp(oparams->user, oparams->authid)) {
	if (add_to_challenge(params->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "authzid", (unsigned char *) oparams->user, TRUE) != SASL_OK) {
	    result = SASL_FAIL;
	    goto FreeAllocatedMem;
	}
    }
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "nonce", text->nonce, TRUE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "cnonce", text->cnonce, TRUE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    snprintf(ncvalue, sizeof(ncvalue), "%08x", text->nonce_count);
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "nc", (unsigned char *) ncvalue, FALSE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "qop", (unsigned char *) qop, FALSE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    if (ctext->cipher != NULL) {
	if (add_to_challenge(params->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "cipher", 
			     (unsigned char *) ctext->cipher->name,
			     FALSE) != SASL_OK) {
	    result = SASL_FAIL;
	    goto FreeAllocatedMem;
	}
    }

    if (params->props.maxbufsize) {
	snprintf(maxbufstr, sizeof(maxbufstr), "%d", params->props.maxbufsize);
	if (add_to_challenge(params->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "maxbuf", (unsigned char *) maxbufstr, 
			     FALSE) != SASL_OK) {
	    SETERROR(params->utils,
		     "internal error: add_to_challenge maxbuf failed");
	    goto FreeAllocatedMem;
	}
    }
    
    if (IsUTF8) {
	if (add_to_challenge(params->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "charset", (unsigned char *) "utf-8",
			     FALSE) != SASL_OK) {
	    result = SASL_FAIL;
	    goto FreeAllocatedMem;
	}
    }
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 text->http_mode ? "uri"	     /* per RFC 2617 */
			 : "digest-uri",   		     /* per RFC 2831 */
			 (unsigned char *) request->uri,
			 TRUE) != SASL_OK) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    if (text->http_mode) {
	/* per RFC 2617: algorithm & opaque MUST be sent back to server */
	if (add_to_challenge(params->utils,
			     &text->out_buf, &text->out_buf_len, &resplen,
			     "algorithm", (unsigned char *) ctext->algorithm,
			     FALSE) != SASL_OK) {
	    result = SASL_FAIL;
	    goto FreeAllocatedMem;
	}
	if (ctext->opaque) {
	    if (add_to_challenge(params->utils,
				 &text->out_buf, &text->out_buf_len, &resplen,
				 "opaque", ctext->opaque, TRUE) != SASL_OK) {
		result = SASL_FAIL;
		goto FreeAllocatedMem;
	    }
	}
    }
    if (add_to_challenge(params->utils,
			 &text->out_buf, &text->out_buf_len, &resplen,
			 "response", (unsigned char *) response,
			 FALSE) != SASL_OK) {
	
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }
    
    /* self check */
    if (strlen(text->out_buf) > 2048) {
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }

    /* set oparams */
    oparams->maxoutbuf = ctext->server_maxbuf;
    if(oparams->mech_ssf > 1) {
	/* MAC block (privacy) */
	oparams->maxoutbuf -= 25;
    } else if(oparams->mech_ssf == 1) {
	/* MAC block (integrity) */
	oparams->maxoutbuf -= 16;
    }
    
    text->seqnum = 0;	/* for integrity/privacy */
    text->rec_seqnum = 0;	/* for integrity/privacy */
    text->utils = params->utils;

    /* Free the old security layer, if any */
    if (old_cipher_free) old_cipher_free(text);

    /* used by layers */
    _plug_decode_init(&text->decode_context, text->utils,
		      params->props.maxbufsize ? params->props.maxbufsize :
		      DEFAULT_BUFSIZE);
    
    if (oparams->mech_ssf > 0) {
	unsigned char enckey[16];
	unsigned char deckey[16];
	
	create_layer_keys(text, params->utils, text->HA1, nbits,
			  enckey, deckey);
	
	/* initialize cipher if need be */
	if (text->cipher_init) {
	    text->cipher_init(text, enckey, deckey);
	}
    }
    
    result = SASL_OK;

  FreeAllocatedMem:
    if (digesturi) params->utils->free(digesturi);
    if (response) params->utils->free(response);

    return result;
}

static int parse_server_challenge(client_context_t *ctext,
				  sasl_client_params_t *params,
				  const char *serverin, unsigned serverinlen,
				  char ***outrealms, int *noutrealm)
{
    context_t *text = (context_t *) ctext;
    int result = SASL_OK;
    char *in_start = NULL;
    char *in = NULL;
    char **realms = NULL;
    int nrealm = 0;
    sasl_ssf_t limit, musthave = 0;
    sasl_ssf_t external;
    int protection = 0;
    int saw_qop = 0;
    int ciphers = 0;
    int maxbuf_count = 0;
    int algorithm_count = 0;
    int opaque_count = 0;

    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 parse_server_challenge()");

    if (!serverin || !serverinlen) {
	params->utils->seterror(params->utils->conn, 0,
				"no server challenge");
	return SASL_FAIL;
    }

    in_start = in = params->utils->malloc(serverinlen + 1);
    if (in == NULL) return SASL_NOMEM;
    
    memcpy(in, serverin, serverinlen);
    in[serverinlen] = 0;
    
    ctext->server_maxbuf = 65536; /* Default value for maxbuf */

    /* create a new cnonce */
    text->cnonce = create_nonce(params->utils);
    if (text->cnonce == NULL) {
	params->utils->seterror(params->utils->conn, 0,
				"failed to create cnonce");
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }

    /* parse the challenge */
    while (in[0] != '\0') {
	char *name, *value;
	
	get_pair(&in, &name, &value);
	
	/* if parse error */
	if (name == NULL) {
	    params->utils->seterror(params->utils->conn, 0, "Parse error");
	    result = SASL_BADAUTH;
	    goto FreeAllocatedMem;
	}
	
	if (*name == '\0') {
	    break;
	}

	if (strcasecmp(name, "realm") == 0) {
	    nrealm++;
	    
	    if(!realms)
		realms = params->utils->malloc(sizeof(char *) * (nrealm + 1));
	    else
		realms = params->utils->realloc(realms, 
						sizeof(char *) * (nrealm + 1));
	    
	    if (realms == NULL) {
		result = SASL_NOMEM;
		goto FreeAllocatedMem;
	    }
	    
	    _plug_strdup(params->utils, value, &realms[nrealm-1], NULL);
	    realms[nrealm] = NULL;
	} else if (strcasecmp(name, "nonce") == 0) {
	    _plug_strdup(params->utils, value, (char **) &text->nonce,
			 NULL);
	    text->nonce_count = 1;
	} else if (strcasecmp(name, "qop") == 0) {
	    saw_qop = 1;
	    while (value && *value) {
		char *comma;
		char *end_val;

SKIP_SPACES_IN_QOP:
		/* skipping spaces: */
		value = skip_lws(value);
		if (*value == '\0') {
		    break;
		}

		/* check for an extreme case when there is no data: LWSP ',' */
		if (*value == ',') {
		    value++;
		    goto SKIP_SPACES_IN_QOP;
		}

		comma = strchr(value, ',');

		if (comma != NULL) {
		    *comma++ = '\0';
		}

		/* skip LWSP at the end of the value (if any), skip_r_lws returns pointer to
		   the first LWSP character, NUL (if there were none) or NULL if the value
		   is entirely from LWSP characters */
		end_val = skip_r_lws (value);
		if (end_val == NULL) {
		    value = comma;
		    continue;
		} else {
		    /* strip LWSP */
		    *end_val = '\0';
		}

		if (strcasecmp(value, "auth-conf") == 0) {
		    protection |= DIGEST_PRIVACY;
		} else if (strcasecmp(value, "auth-int") == 0) {
		    protection |= DIGEST_INTEGRITY;
		} else if (strcasecmp(value, "auth") == 0) {
		    protection |= DIGEST_NOLAYER;
		} else {
		    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
				       "Server supports unknown layer: %s\n",
				       value);
		}
		
		value = comma;
	    }
	} else if (strcasecmp(name, "cipher") == 0) {
	    while (value && *value) {
		struct digest_cipher *cipher = available_ciphers;
		char *comma;
		char *end_val;

SKIP_SPACES_IN_CIPHER:
		/* skipping spaces: */
		value = skip_lws(value);
		if (*value == '\0') {
		    break;
		}

		/* check for an extreme case when there is no data: LWSP ',' */
		if (*value == ',') {
		    value++;
		    goto SKIP_SPACES_IN_CIPHER;
		}

		comma = strchr(value, ',');

		if (comma != NULL) {
		    *comma++ = '\0';
		}

		/* skip LWSP at the end of the value, skip_r_lws returns pointer to
		   the first LWSP character or NULL */
		end_val = skip_r_lws (value);
		if (end_val == NULL) {
		    value = comma;
		    continue;
		} else {
		    /* strip LWSP */
		    *end_val = '\0';
		}

		/* do we support this cipher? */
		while (cipher->name) {
		    if (!strcasecmp(value, cipher->name)) break;
		    cipher++;
		}
		if (cipher->name) {
		    ciphers |= cipher->flag;
		} else {
		    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
				       "Server supports unknown cipher: %s\n",
				       value);
		}
		
		value = comma;
	    }
	} else if (strcasecmp(name, "stale") == 0 && ctext->password) {
	    /* clear any cached password */
	    if (ctext->free_password)
		_plug_free_secret(params->utils, &ctext->password);
	    ctext->password = NULL;
	} else if (strcasecmp(name, "maxbuf") == 0) {
	    /* maxbuf A number indicating the size of the largest
	     * buffer the server is able to receive when using
	     * "auth-int". If this directive is missing, the default
	     * value is 65536. This directive may appear at most once;
	     * if multiple instances are present, the client should
	     * abort the authentication exchange.  
	     */
	    maxbuf_count++;
	    
	    if (maxbuf_count != 1) {
		result = SASL_BADAUTH;
		params->utils->seterror(params->utils->conn, 0,
					"At least two maxbuf directives found. Authentication aborted");
		goto FreeAllocatedMem;
	    } 

	    if (str2ul32 (value, &ctext->server_maxbuf) == FALSE) {
		result = SASL_BADAUTH;
		params->utils->seterror(params->utils->conn, 0,
					"Invalid maxbuf parameter received from server (%s)", value);
		goto FreeAllocatedMem;
	    }
	    
	    if (ctext->server_maxbuf <= 16) {
		result = SASL_BADAUTH;
		params->utils->seterror(params->utils->conn, 0,
					"Invalid maxbuf parameter received from server (too small: %s)", value);
		goto FreeAllocatedMem;
	    }

	    if (ctext->server_maxbuf > MAX_SASL_BUFSIZE) {
		result = SASL_BADAUTH;
		params->utils->seterror(params->utils->conn, 0,
					"Invalid maxbuf parameter received from server (too big: %s)", value);
		goto FreeAllocatedMem;
	    }
	} else if (strcasecmp(name, "charset") == 0) {
	    if (strcasecmp(value, "utf-8") != 0) {
		result = SASL_BADAUTH;
		params->utils->seterror(params->utils->conn, 0,
					"Charset must be UTF-8");
		goto FreeAllocatedMem;
	    }
	} else if (strcasecmp(name,"algorithm")==0) {
	    if (text->http_mode && strcasecmp(value, "md5") == 0) {
		/* per RFC 2617: need to support both "md5" and "md5-sess" */
	    }
	    else if (strcasecmp(value, "md5-sess") != 0)
		{
		    params->utils->seterror(params->utils->conn, 0,
					    "'algorithm' isn't 'md5-sess'");
		    result = SASL_FAIL;
		    goto FreeAllocatedMem;
		}

	    if (text->http_mode) {
		/* per RFC 2617: algorithm MUST be saved */
		_plug_strdup(params->utils, value, (char **) &ctext->algorithm,
			     NULL);
	    }
	    algorithm_count++;
	    if (algorithm_count > 1)
		{
		    params->utils->seterror(params->utils->conn, 0,
					    "Must see 'algorithm' only once");
		    result = SASL_FAIL;
		    goto FreeAllocatedMem;
		}
	} else if (strcasecmp(name,"opaque")==0) {
	    /* per RFC 2831: opaque MUST be ignored if received */
	    if (text->http_mode) {
		/* per RFC 2617: opaque MUST be saved */
		_plug_strdup(params->utils, value, (char **) &ctext->opaque,
			     NULL);
		opaque_count++;
		if (opaque_count > 1)
		    {
			params->utils->seterror(params->utils->conn, 0,
						"Must see 'opaque' only once");
			result = SASL_FAIL;
			goto FreeAllocatedMem;
		    }
	    }
	} else {
	    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
			       "DIGEST-MD5 unrecognized pair %s/%s: ignoring",
			       name, value);
	}
    }
    
    if (protection == 0) {
	/* From RFC 2831[bis]:
	   This directive is optional; if not present it defaults to "auth". */
	if (saw_qop == 0) {
	    protection = DIGEST_NOLAYER;
	} else {
	    result = SASL_BADAUTH;
	    params->utils->seterror(params->utils->conn, 0,
				    "Server doesn't support any known qop level");
	    goto FreeAllocatedMem;
	}
    }

    if (algorithm_count != 1) {
	params->utils->seterror(params->utils->conn, 0,
				"Must see 'algorithm' once. Didn't see at all");
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }

    /* make sure we have everything we require */
    if (text->nonce == NULL) {
	params->utils->seterror(params->utils->conn, 0,
				"Don't have nonce.");
	result = SASL_FAIL;
	goto FreeAllocatedMem;
    }

    /* get requested ssf */
    external = params->external_ssf;
    
    /* what do we _need_?  how much is too much? */
    if (!text->http_mode &&    	       	   /* HTTP Digest doesn't need buffer */
	params->props.maxbufsize == 0) {
	musthave = 0;
	limit = 0;
    } else {
	if (params->props.max_ssf > external) {
	    limit = params->props.max_ssf - external;
	} else {
	    limit = 0;
	}
	if (params->props.min_ssf > external) {
	    musthave = params->props.min_ssf - external;
	} else {
	    musthave = 0;
	}
    }
    
    /* we now go searching for an option that gives us at least "musthave"
       and at most "limit" bits of ssf. */
    if ((limit > 1) && (protection & DIGEST_PRIVACY)) {
	struct digest_cipher *cipher;
	
	/* let's find an encryption scheme that we like */
	cipher = available_ciphers;
	while (cipher->name) {
	    /* examine each cipher we support, see if it meets our security
	       requirements, and see if the server supports it.
	       choose the best one of these */
	    if ((limit >= cipher->ssf) && (musthave <= cipher->ssf) &&
		(ciphers & cipher->flag) &&
		(!ctext->cipher || (cipher->ssf > ctext->cipher->ssf))) {
		ctext->cipher = cipher;
	    }
	    cipher++;
	}
	
	if (ctext->cipher) {
	    /* we found a cipher we like */
	    ctext->protection = DIGEST_PRIVACY;
	} else {
	    /* we didn't find any ciphers we like */
	    params->utils->seterror(params->utils->conn, 0,
				    "No good privacy layers");
	}
    }
    
    if (ctext->cipher == NULL) {
	/* we failed to find an encryption layer we liked;
	   can we use integrity or nothing? */
	
	if ((limit >= 1) && (musthave <= 1) 
	    && (protection & DIGEST_INTEGRITY)) {
	    /* integrity */
	    ctext->protection = DIGEST_INTEGRITY;
	} else if (musthave <= 0) {
	    /* no layer */
	    ctext->protection = DIGEST_NOLAYER;

	    /* See if server supports not having a layer */
	    if ((protection & DIGEST_NOLAYER) != DIGEST_NOLAYER) {
		params->utils->seterror(params->utils->conn, 0, 
					"Server doesn't support \"no layer\"");
		result = SASL_FAIL;
		goto FreeAllocatedMem;
	    }
	} else {
	    params->utils->seterror(params->utils->conn, 0,
				    "Can't find an acceptable layer");
	    result = SASL_TOOWEAK;
	    goto FreeAllocatedMem;
	}
    }

    *outrealms = realms;
    *noutrealm = nrealm;

  FreeAllocatedMem:
    if (in_start) params->utils->free(in_start);

    if (result != SASL_OK && realms) {
	int lup;
	
	/* need to free all the realms */
	for (lup = 0;lup < nrealm; lup++)
	    params->utils->free(realms[lup]);
	
	params->utils->free(realms);
    }

    return result;
}

static int ask_user_info(client_context_t *ctext,
			 sasl_client_params_t *params,
			 char **realms, int nrealm,
			 sasl_interact_t **prompt_need,
			 sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) ctext;
    int result = SASL_OK;
    const char *authid = NULL, *userid = NULL, *realm = NULL;
    char *realm_chal = NULL;
    int user_result = SASL_OK;
    int auth_result = SASL_OK;
    int pass_result = SASL_OK;
    int realm_result = SASL_FAIL;
    int i;
    size_t len;

    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 ask_user_info()");

    /* try to get the authid */
    if (oparams->authid == NULL) {
	auth_result = _plug_get_authid(params->utils, &authid, prompt_need);
	
	if ((auth_result != SASL_OK) && (auth_result != SASL_INTERACT)) {
	    return auth_result;
	}
    }
    
    /* try to get the userid */
    if (oparams->user == NULL) {
	user_result = _plug_get_userid(params->utils, &userid, prompt_need);
	
	if ((user_result != SASL_OK) && (user_result != SASL_INTERACT)) {
	    return user_result;
	}
    }
    
    /* try to get the password */
    if (ctext->password == NULL) {
	pass_result = _plug_get_password(params->utils, &ctext->password,
					 &ctext->free_password, prompt_need);
	if ((pass_result != SASL_OK) && (pass_result != SASL_INTERACT)) {
	    return pass_result;
	}
    }

    /* try to get the realm */
    if (text->realm == NULL) {
	if (realms) {
	    if(nrealm == 1) {
		/* only one choice */
		realm = realms[0];
		realm_result = SASL_OK;
	    } else {
		/* ask the user */
		realm_result = _plug_get_realm(params->utils,
					       (const char **) realms,
					       (const char **) &realm,
					       prompt_need);
	    }
	}

	/* fake the realm if we must */
	if ((realm_result != SASL_OK) && (realm_result != SASL_INTERACT)) {
	    if (params->serverFQDN) {
		realm = params->serverFQDN;
	    } else {
		return realm_result;
	    }
	}    
    }
    
    /* free prompts we got */
    if (prompt_need && *prompt_need) {
	params->utils->free(*prompt_need);
	*prompt_need = NULL;
    }
    
    /* if there are prompts not filled in */
    if ((user_result == SASL_INTERACT) || (auth_result == SASL_INTERACT) ||
	(pass_result == SASL_INTERACT) || (realm_result == SASL_INTERACT)) {

	/* make our default realm */
	if (realm_result == SASL_INTERACT) {
	    if (realms) {
		len = strlen(REALM_CHAL_PREFIX);
		for (i = 0; i < nrealm; i++) {
		    len += strlen(realms[i]) + 4 /* " {}," */;
		}
		realm_chal = params->utils->malloc(len + 1);
		strcpy (realm_chal, REALM_CHAL_PREFIX);
		for (i = 0; i < nrealm; i++) {
		    strcat (realm_chal, " {");
		    strcat (realm_chal, realms[i]);
		    strcat (realm_chal, "},");
		}
		/* Replace the terminating comma with dot */
		realm_chal[len-1] = '.';

	    } else if (params->serverFQDN) {
		realm_chal = params->utils->malloc(3+strlen(params->serverFQDN));
		if (realm_chal) {
		    sprintf(realm_chal, "{%s}", params->serverFQDN);
		} else {
		    return SASL_NOMEM;
		}
	    }
	}

	/* make the prompt list */
	result =
	    _plug_make_prompts(params->utils, prompt_need,
			       user_result == SASL_INTERACT ?
			       "Please enter your authorization name" : NULL,
			       NULL,
			       auth_result == SASL_INTERACT ?
			       "Please enter your authentication name" : NULL,
			       NULL,
			       pass_result == SASL_INTERACT ?
			       "Please enter your password" : NULL, NULL,
			       NULL, NULL, NULL,
			       realm_chal ? realm_chal : "{}",
			       realm_result == SASL_INTERACT ?
			       "Please enter your realm" : NULL,
			       params->serverFQDN ? params->serverFQDN : NULL);
	
	if (result == SASL_OK) return SASL_INTERACT;

	return result;
    }
    
    if (oparams->authid == NULL) {
	if (!userid || !*userid) {
	    result = params->canon_user(params->utils->conn, authid, 0,
					SASL_CU_AUTHID | SASL_CU_AUTHZID,
					oparams);
	}
	else {
	    result = params->canon_user(params->utils->conn,
					authid, 0, SASL_CU_AUTHID, oparams);
	    if (result != SASL_OK) return result;

	    result = params->canon_user(params->utils->conn,
					userid, 0, SASL_CU_AUTHZID, oparams);
	}
	if (result != SASL_OK) return result;
    }

    /* Get an allocated version of the realm into the structure */
    if (realm && text->realm == NULL) {
	_plug_strdup(params->utils, realm, (char **) &text->realm, NULL);
    }

    return result;
}

static int digestmd5_client_mech_new(void *glob_context,
				     sasl_client_params_t * params,
				     void **conn_context)
{
    context_t *text;
    
    if ((params->flags & SASL_NEED_HTTP) && !params->http_request) {
	SETERROR(params->utils,
		 "DIGEST-MD5 unavailable due to lack of HTTP request");
	return SASL_BADPARAM;
    }

    /* holds state are in -- allocate client size */
    text = params->utils->malloc(sizeof(client_context_t));
    if (text == NULL)
	return SASL_NOMEM;
    memset((client_context_t *)text, 0, sizeof(client_context_t));
    
    text->state = 1;
    text->i_am = CLIENT;
    text->http_mode = (params->flags & SASL_NEED_HTTP);
    text->reauth = ((digest_glob_context_t *) glob_context)->reauth;
    
    *conn_context = text;

    return SASL_OK;
}

static int
digestmd5_client_mech_step1(client_context_t *ctext,
			    sasl_client_params_t *params,
			    const char *serverin __attribute__((unused)), 
			    unsigned serverinlen __attribute__((unused)), 
			    sasl_interact_t **prompt_need,
			    const char **clientout,
			    unsigned *clientoutlen,
			    sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) ctext;
    int result = SASL_FAIL;
    unsigned val;

    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 client step 1");

    result = ask_user_info(ctext, params, NULL, 0, prompt_need, oparams);
    if (result != SASL_OK) return result;

    /* check if we have cached info for this user on this server */
    val = hash(params->serverFQDN) % text->reauth->size;
    if (params->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */
	if (text->reauth->e[val].u.c.serverFQDN &&
	    !strcasecmp(text->reauth->e[val].u.c.serverFQDN,
			params->serverFQDN) &&
	    !strcmp(text->reauth->e[val].authid, oparams->authid)) {

	    /* we have info, so use it */
	    if (text->realm) params->utils->free(text->realm);
	    _plug_strdup(params->utils, text->reauth->e[val].realm,
			 &text->realm, NULL);
	    _plug_strdup(params->utils, (char *) text->reauth->e[val].nonce,
			 (char **) &text->nonce, NULL);
	    text->nonce_count = ++text->reauth->e[val].nonce_count;
	    _plug_strdup(params->utils, (char *) text->reauth->e[val].cnonce,
			 (char **) &text->cnonce, NULL);
	    if (text->http_mode) {
		/* per RFC 2617: algorithm & opaque MUST be sent back to server */
		_plug_strdup(params->utils,
			     (char *) text->reauth->e[val].u.c.algorithm,
			     (char **) &ctext->algorithm, NULL);
		if (text->reauth->e[val].u.c.opaque) {
		    _plug_strdup(params->utils,
				 (char *) text->reauth->e[val].u.c.opaque,
				 (char **) &ctext->opaque, NULL);
		}
	    }
	    ctext->protection = text->reauth->e[val].u.c.protection;
	    ctext->cipher = text->reauth->e[val].u.c.cipher;
	    ctext->server_maxbuf = text->reauth->e[val].u.c.server_maxbuf;
	}
	params->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
    }

    if (!text->nonce) {
	/* we don't have any reauth info, so just return
	 * that there is no initial client send */
	text->state = 2;
	return SASL_CONTINUE;
    }

    /*
     * (username | realm | nonce | cnonce | nonce-count | qop digest-uri |
     * response | maxbuf | charset | auth-param )
     */
    
    result = make_client_response(text, params, oparams);
    if (result != SASL_OK) return result;

    *clientoutlen = (unsigned) strlen(text->out_buf);
    *clientout = text->out_buf;

    /* check for next state (2 or 3) is done in digestmd5_client_mech_step() */
    return SASL_CONTINUE;
}

static int digestmd5_client_mech_step2(client_context_t *ctext,
				       sasl_client_params_t *params,
				       const char *serverin,
				       unsigned serverinlen,
				       sasl_interact_t **prompt_need,
				       const char **clientout,
				       unsigned *clientoutlen,
				       sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) ctext;
    int result = SASL_FAIL;
    char **realms = NULL;
    int nrealm = 0;

    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 client step 2");

    if (params->props.min_ssf > params->props.max_ssf) {
	return SASL_BADPARAM;
    }

    /* don't bother parsing the challenge more than once */
    if (text->nonce == NULL) {
	result = parse_server_challenge(ctext, params, serverin, serverinlen,
					&realms, &nrealm);
	if (result != SASL_OK) goto FreeAllocatedMem;
    
	if (nrealm == 1) {
	    /* only one choice! */
	    if (text->realm) params->utils->free(text->realm);
	    text->realm = realms[0];

	    /* free realms */
	    params->utils->free(realms);
	    realms = NULL;
	} else {
	    /* Save realms for later use */
	    text->realms = realms;
	    text->realm_cnt = nrealm;
	}
    } else {
	/* Restore the list of realms */
	realms = text->realms;
	nrealm = text->realm_cnt;
    }

    result = ask_user_info(ctext, params, realms, nrealm,
			   prompt_need, oparams);
    if (result != SASL_OK) goto FreeAllocatedMem;

    /*
     * (username | realm | nonce | cnonce | nonce-count | qop | digest-uri |
     *  response | maxbuf | charset | auth-param )
     */
    
    result = make_client_response(text, params, oparams);
    if (result != SASL_OK) goto FreeAllocatedMem;

    *clientoutlen = (unsigned) strlen(text->out_buf);
    *clientout = text->out_buf;

    text->state = 3;
    
    result = SASL_CONTINUE;
    
  FreeAllocatedMem:
    return result;
}

static int
digestmd5_client_mech_step3(client_context_t *ctext,
			    sasl_client_params_t *params,
			    const char *serverin,
			    unsigned serverinlen,
			    sasl_interact_t **prompt_need __attribute__((unused)),
			    const char **clientout __attribute__((unused)),
			    unsigned *clientoutlen __attribute__((unused)),
			    sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) ctext;
    char           *in = NULL;
    char           *in_start;
    int result = SASL_FAIL;
    
    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
		       "DIGEST-MD5 client step 3");

    /* Verify that server is really what he claims to be */
    in_start = in = params->utils->malloc(serverinlen + 1);
    if (in == NULL) return SASL_NOMEM;

    memcpy(in, serverin, serverinlen);
    in[serverinlen] = 0;
    
    /* parse the response */
    while (in[0] != '\0') {
	char *name, *value;
	get_pair(&in, &name, &value);
	
	if (name == NULL) {
	    params->utils->seterror(params->utils->conn, 0,
				    "DIGEST-MD5 Received Garbage");
	    result = SASL_BADAUTH;
	    break;
	}
	
	if (*name == '\0') {
	    break;
	}

	if (strcasecmp(name, "rspauth") == 0) {
	    
	    if (strcmp(text->response_value, value) != 0) {
		params->utils->seterror(params->utils->conn, 0,
					"DIGEST-MD5: This server wants us to believe that he knows shared secret");
		result = SASL_BADSERV;
	    } else {
		oparams->doneflag = 1;
		oparams->param_version = 0;
		
		result = SASL_OK;
	    }
	    break;
	} else {
	    params->utils->log(params->utils->conn, SASL_LOG_DEBUG,
			       "DIGEST-MD5 unrecognized pair %s/%s: ignoring",
			       name, value);
	}
    }
    
    params->utils->free(in_start);

    if (params->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */
	unsigned val = hash(params->serverFQDN) % text->reauth->size;
	switch (result) {
	case SASL_OK:
	    if (text->nonce_count == 1) {
		/* successful initial auth, setup for future reauth */
		clear_reauth_entry(&text->reauth->e[val], CLIENT, params->utils);
		_plug_strdup(params->utils, oparams->authid,
			     &text->reauth->e[val].authid, NULL);
		text->reauth->e[val].realm = text->realm; text->realm = NULL;
		text->reauth->e[val].nonce = text->nonce; text->nonce = NULL;
		text->reauth->e[val].nonce_count = text->nonce_count;
		text->reauth->e[val].cnonce = text->cnonce; text->cnonce = NULL;
		_plug_strdup(params->utils, params->serverFQDN,
			     &text->reauth->e[val].u.c.serverFQDN, NULL);
		if (text->http_mode) {
		    /* per RFC 2617: algorithm & opaque MUST be saved */
		    text->reauth->e[val].u.c.algorithm = ctext->algorithm;
		    ctext->algorithm = NULL;
		    text->reauth->e[val].u.c.opaque = ctext->opaque;
		    ctext->opaque = NULL;
		}
		text->reauth->e[val].u.c.protection = ctext->protection;
		text->reauth->e[val].u.c.cipher = ctext->cipher;
		text->reauth->e[val].u.c.server_maxbuf = ctext->server_maxbuf;
	    }
	    else {
		/* reauth, we already incremented nonce_count */
	    }
	    break;
	default:
	    if (text->nonce_count > 1) {
		/* failed reauth, clear cache */
		clear_reauth_entry(&text->reauth->e[val], CLIENT, params->utils);
	    }
	    else {
		/* failed initial auth, leave existing cache */
	    }
	}
	params->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
    }

    return result;
}

static int digestmd5_client_mech_step(void *conn_context,
				      sasl_client_params_t *params,
				      const char *serverin,
				      unsigned serverinlen,
				      sasl_interact_t **prompt_need,
				      const char **clientout,
				      unsigned *clientoutlen,
				      sasl_out_params_t *oparams)
{
    context_t *text = (context_t *) conn_context;
    client_context_t *ctext = (client_context_t *) conn_context;
    unsigned val = hash(params->serverFQDN) % text->reauth->size;
    
    if (serverinlen > 2048) return SASL_BADPROT;
    
    *clientout = NULL;
    *clientoutlen = 0;

    switch (text->state) {

    case 1:
	if (!serverin) {
	    /* here's where we attempt fast reauth if possible */
	    int reauth = 0;

	    /* check if we have saved info for this server */
	    if (params->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */
		reauth = text->reauth->e[val].u.c.serverFQDN &&
		    !strcasecmp(text->reauth->e[val].u.c.serverFQDN,
				params->serverFQDN);
		params->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
	    }
	    if (reauth) {
		return digestmd5_client_mech_step1(ctext, params,
						   serverin, serverinlen,
						   prompt_need,
						   clientout, clientoutlen,
						   oparams);
	    }
	    else {
		/* we don't have any reauth info, so just return
		 * that there is no initial client send */
		text->state = 2;
		return SASL_CONTINUE;
	    }
	}
	else if (!strncasecmp(serverin, "rspauth=", 8)) {
	    /* server accepted fast reauth */
	    text->state = 3;
	    goto step3;
	}

	/* fall through and respond to challenge */
	text->state = 2;

	/* cleanup after a failed reauth attempt */
	if (params->utils->mutex_lock(text->reauth->mutex) == SASL_OK) { /* LOCK */
	    clear_reauth_entry(&text->reauth->e[val], CLIENT, params->utils);

	    params->utils->mutex_unlock(text->reauth->mutex); /* UNLOCK */
	}

	if (text->realm) params->utils->free(text->realm);
	if (text->nonce) params->utils->free(text->nonce);
	if (text->cnonce) params->utils->free(text->cnonce);
	text->realm = NULL;
	text->nonce = text->cnonce = NULL;
	ctext->cipher = NULL;

        GCC_FALLTHROUGH
    
    case 2:
	return digestmd5_client_mech_step2(ctext, params,
					   serverin, serverinlen,
					   prompt_need,
					   clientout, clientoutlen,
					   oparams);

    case 3:
    step3:
	return digestmd5_client_mech_step3(ctext, params,
					   serverin, serverinlen,
					   prompt_need,
					   clientout, clientoutlen,
					   oparams);

    default:
	params->utils->log(NULL, SASL_LOG_ERR,
			   "Invalid DIGEST-MD5 client step %d\n", text->state);
	return SASL_FAIL;
    }
    
    return SASL_FAIL; /* should never get here */
}

static void digestmd5_client_mech_dispose(void *conn_context,
					  const sasl_utils_t *utils)
{
    client_context_t *ctext = (client_context_t *) conn_context;
    
    if (!ctext || !utils) return;
    
    utils->log(utils->conn, SASL_LOG_DEBUG,
	       "DIGEST-MD5 client mech dispose");

    if (ctext->free_password) _plug_free_secret(utils, &ctext->password);
    if (ctext->algorithm) utils->free(ctext->algorithm);
    if (ctext->opaque) utils->free(ctext->opaque);

    digestmd5_common_mech_dispose(conn_context, utils);
}

static sasl_client_plug_t digestmd5_client_plugins[] =
{
    {
	"DIGEST-MD5",
#ifdef WITH_RC4				/* mech_name */
	128,				/* max ssf */
#elif defined(WITH_DES)
	112,
#else
	1,
#endif
	SASL_SEC_NOPLAINTEXT
	| SASL_SEC_NOANONYMOUS
	| SASL_SEC_MUTUAL_AUTH,		/* security_flags */
	SASL_FEAT_NEEDSERVERFQDN
	| SASL_FEAT_ALLOWS_PROXY
	| SASL_FEAT_SUPPORTS_HTTP,	/* features */
	NULL,				/* required_prompts */
	&client_glob_context,		/* glob_context */
	&digestmd5_client_mech_new,	/* mech_new */
	&digestmd5_client_mech_step,	/* mech_step */
	&digestmd5_client_mech_dispose,	/* mech_dispose */
	&digestmd5_common_mech_free,	/* mech_free */
	NULL,				/* idle */
	NULL,				/* spare1 */
	NULL				/* spare2 */
    }
};

int digestmd5_client_plug_init(sasl_utils_t *utils,
			       int maxversion,
			       int *out_version,
			       sasl_client_plug_t **pluglist,
			       int *plugcount)
{
    reauth_cache_t *reauth_cache;

    if (maxversion < SASL_CLIENT_PLUG_VERSION)
	return SASL_BADVERS;
    
    /* reauth cache */
    reauth_cache = utils->malloc(sizeof(reauth_cache_t));
    if (reauth_cache == NULL)
	return SASL_NOMEM;
    memset(reauth_cache, 0, sizeof(reauth_cache_t));
    reauth_cache->i_am = CLIENT;
    
    /* mutex */
    reauth_cache->mutex = utils->mutex_alloc();
    if (!reauth_cache->mutex)
	return SASL_FAIL;

    /* entries */
    reauth_cache->size = 10;
    reauth_cache->e = utils->malloc(reauth_cache->size *
				    sizeof(reauth_entry_t));
    if (reauth_cache->e == NULL)
	return SASL_NOMEM;
    memset(reauth_cache->e, 0, reauth_cache->size * sizeof(reauth_entry_t));

    ((digest_glob_context_t *) digestmd5_client_plugins[0].glob_context)->reauth = reauth_cache;

    *out_version = SASL_CLIENT_PLUG_VERSION;
    *pluglist = digestmd5_client_plugins;
    *plugcount = 1;
    
    return SASL_OK;
}