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

/* Functions that relate to the TLS handshake procedure.
 */

#include "gnutls_int.h"
#include "gnutls_errors.h"
#include "gnutls_dh.h"
#include "debug.h"
#include "algorithms.h"
#include "gnutls_compress.h"
#include "gnutls_cipher.h"
#include "gnutls_buffers.h"
#include "gnutls_mbuffers.h"
#include "gnutls_kx.h"
#include "gnutls_handshake.h"
#include "gnutls_num.h"
#include "gnutls_hash_int.h"
#include "gnutls_db.h"
#include "gnutls_extensions.h"
#include "gnutls_supplemental.h"
#include "gnutls_auth.h"
#include "gnutls_v2_compat.h"
#include <auth/cert.h>
#include "gnutls_constate.h"
#include <gnutls_record.h>
#include <gnutls_state.h>
#include <ext/srp.h>
#include <ext/session_ticket.h>
#include <ext/status_request.h>
#include <ext/safe_renegotiation.h>
#include <gnutls_rsa_export.h>  /* for gnutls_get_rsa_params() */
#include <auth/anon.h>          /* for gnutls_anon_server_credentials_t */
#include <auth/psk.h>           /* for gnutls_psk_server_credentials_t */
#include <random.h>
#include <gnutls_dtls.h>

#ifdef HANDSHAKE_DEBUG
#define ERR(x, y) _gnutls_handshake_log("HSK[%p]: %s (%d)\n", session, x,y)
#else
#define ERR(x, y)
#endif

#define TRUE 1
#define FALSE 0

static int _gnutls_server_select_comp_method (gnutls_session_t session,
                                              uint8_t * data, int datalen);
static int
_gnutls_remove_unwanted_ciphersuites (gnutls_session_t session,
                                      uint8_t * cipher_suites,
                                      int cipher_suites_size,
                                      gnutls_pk_algorithm_t *pk_algos,
                                      size_t pk_algos_size);
static int _gnutls_handshake_client (gnutls_session_t session);
static int _gnutls_handshake_server (gnutls_session_t session);

static int
_gnutls_recv_handshake_final (gnutls_session_t session, int init);
static int
_gnutls_send_handshake_final (gnutls_session_t session, int init);

/* Empties but does not free the buffer
 */
static inline void
_gnutls_handshake_hash_buffer_empty (gnutls_session_t session)
{

  _gnutls_buffers_log ("BUF[HSK]: Emptied buffer\n");

  session->internals.handshake_hash_buffer_prev_len = 0;
  session->internals.handshake_hash_buffer.length = 0;
  return;
}

static int
_gnutls_handshake_hash_add_recvd (gnutls_session_t session,
                                  gnutls_handshake_description_t recv_type,
                                  uint8_t * header, uint16_t header_size,
                                  uint8_t * dataptr, uint32_t datalen);

static int
_gnutls_handshake_hash_add_sent (gnutls_session_t session,
                                 gnutls_handshake_description_t type,
                                 uint8_t * dataptr, uint32_t datalen);

static int
_gnutls_recv_hello_verify_request (gnutls_session_t session,
				   uint8_t * data, int datalen);


/* Clears the handshake hash buffers and handles.
 */
void
_gnutls_handshake_hash_buffers_clear (gnutls_session_t session)
{
  session->internals.handshake_hash_buffer_prev_len = 0;
  _gnutls_buffer_clear(&session->internals.handshake_hash_buffer);
}

/* this will copy the required values for resuming to
 * internals, and to security_parameters.
 * this will keep as less data to security_parameters.
 */
static void
resume_copy_required_values (gnutls_session_t session)
{
  /* get the new random values */
  memcpy (session->internals.resumed_security_parameters.server_random,
          session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
  memcpy (session->internals.resumed_security_parameters.client_random,
          session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);

  /* keep the ciphersuite and compression 
   * That is because the client must see these in our
   * hello message.
   */
  memcpy (session->security_parameters.cipher_suite,
          session->internals.resumed_security_parameters.cipher_suite, 2);
  session->security_parameters.compression_method = session->internals.resumed_security_parameters.compression_method;

  _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
                                  session->
                                  internals.resumed_security_parameters.cipher_suite);
  _gnutls_epoch_set_compression (session, EPOCH_NEXT,
                                 session->
                                 internals.resumed_security_parameters.compression_method);

  /* or write_compression_algorithm
   * they are the same
   */

  session->security_parameters.entity =
    session->internals.resumed_security_parameters.entity;

  _gnutls_set_current_version (session,
                               session->internals.resumed_security_parameters.
                               version);

  session->security_parameters.cert_type =
    session->internals.resumed_security_parameters.cert_type;

  memcpy (session->security_parameters.session_id,
          session->internals.resumed_security_parameters.session_id,
          sizeof (session->security_parameters.session_id));
  session->security_parameters.session_id_size =
    session->internals.resumed_security_parameters.session_id_size;

}


/* this function will produce GNUTLS_RANDOM_SIZE==32 bytes of random data
 * and put it to dst.
 */
static int
_gnutls_tls_create_random (uint8_t * dst)
{
  uint32_t tim;
  int ret;

  /* Use weak random numbers for the most of the
   * buffer except for the first 4 that are the
   * system's time.
   */

  tim = gnutls_time (NULL);
  /* generate server random value */
  _gnutls_write_uint32 (tim, dst);

  ret = _gnutls_rnd (GNUTLS_RND_NONCE, &dst[4], GNUTLS_RANDOM_SIZE - 4);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  return 0;
}

int
_gnutls_set_client_random (gnutls_session_t session, uint8_t * rnd)
{
int ret;

  if (rnd != NULL)
    memcpy (session->security_parameters.client_random, rnd,
            GNUTLS_RANDOM_SIZE);
  else
    {
      /* no random given, we generate. */
      if (session->internals.sc_random_set != 0)
        {
          memcpy (session->security_parameters.client_random, 
                  session->internals.resumed_security_parameters.client_random,
                  GNUTLS_RANDOM_SIZE);
        }
      else
        {
          ret = _gnutls_tls_create_random (session->security_parameters.client_random);
          if (ret < 0)
            return gnutls_assert_val(ret);
         }
    }
  return 0;
}

int
_gnutls_set_server_random (gnutls_session_t session, uint8_t * rnd)
{
int ret;

  if (rnd != NULL)
    memcpy (session->security_parameters.server_random, rnd,
            GNUTLS_RANDOM_SIZE);
  else
    {
      /* no random given, we generate. */
      if (session->internals.sc_random_set != 0)
        {
          memcpy (session->security_parameters.server_random, 
                  session->internals.resumed_security_parameters.server_random,
                  GNUTLS_RANDOM_SIZE);
        }
      else
        {
          ret = _gnutls_tls_create_random (session->security_parameters.server_random);
          if (ret < 0)
            return gnutls_assert_val(ret);
         }
    }
  return 0;
}

/* Calculate The SSL3 Finished message
 */
#define SSL3_CLIENT_MSG "CLNT"
#define SSL3_SERVER_MSG "SRVR"
#define SSL_MSG_LEN 4
static int
_gnutls_ssl3_finished (gnutls_session_t session, int type, uint8_t * ret, int sending)
{
  digest_hd_st td_md5;
  digest_hd_st td_sha;
  const char *mesg;
  int rc, len;

  if (sending)
    len = session->internals.handshake_hash_buffer.length;
  else
    len = session->internals.handshake_hash_buffer_prev_len;

  rc = _gnutls_hash_init (&td_sha, GNUTLS_DIG_SHA1);
  if (rc < 0)
    return gnutls_assert_val(rc);

  rc = _gnutls_hash_init (&td_md5, GNUTLS_DIG_MD5);
  if (rc < 0)
    {
      _gnutls_hash_deinit (&td_sha, NULL);
      return gnutls_assert_val(rc);
    }

  _gnutls_hash(&td_sha, session->internals.handshake_hash_buffer.data, len);
  _gnutls_hash(&td_md5, session->internals.handshake_hash_buffer.data, len);

  if (type == GNUTLS_SERVER)
    mesg = SSL3_SERVER_MSG;
  else
    mesg = SSL3_CLIENT_MSG;

  _gnutls_hash (&td_md5, mesg, SSL_MSG_LEN);
  _gnutls_hash (&td_sha, mesg, SSL_MSG_LEN);

  rc = _gnutls_mac_deinit_ssl3_handshake (&td_md5, ret,
                                     session->
                                     security_parameters.master_secret,
                                     GNUTLS_MASTER_SIZE);
  if (rc < 0)
    {
      _gnutls_hash_deinit (&td_md5, NULL);
      _gnutls_hash_deinit (&td_sha, NULL);
      return gnutls_assert_val(rc);
    }

  rc = _gnutls_mac_deinit_ssl3_handshake (&td_sha, &ret[16],
                                     session->
                                     security_parameters.master_secret,
                                     GNUTLS_MASTER_SIZE);
  if (rc < 0)
    {
      _gnutls_hash_deinit (&td_sha, NULL);
      return gnutls_assert_val(rc);
    }

  return 0;
}

/* Hash the handshake messages as required by TLS 1.0
 */
#define SERVER_MSG "server finished"
#define CLIENT_MSG "client finished"
#define TLS_MSG_LEN 15
static int
_gnutls_finished (gnutls_session_t session, int type, void *ret, int sending)
{
  const int siz = TLS_MSG_LEN;
  uint8_t concat[MAX_HASH_SIZE + 16 /*MD5 */ ];
  size_t hash_len;
  const char *mesg;
  int rc, len;

  if (sending)
    len = session->internals.handshake_hash_buffer.length;
  else
    len = session->internals.handshake_hash_buffer_prev_len;

  if (!_gnutls_version_has_selectable_prf (gnutls_protocol_get_version(session)))
    {
      rc = _gnutls_hash_fast( GNUTLS_DIG_SHA1, session->internals.handshake_hash_buffer.data, len, &concat[16]);
      if (rc < 0)
        return gnutls_assert_val(rc);

      rc = _gnutls_hash_fast( GNUTLS_DIG_MD5, session->internals.handshake_hash_buffer.data, len, concat);
      if (rc < 0)
        return gnutls_assert_val(rc);
       
      hash_len = 20 + 16;
    }
  else 
    {
      int algorithm = _gnutls_cipher_suite_get_prf(session->security_parameters.cipher_suite);

      rc = _gnutls_hash_fast( algorithm, session->internals.handshake_hash_buffer.data, len, concat);
      if (rc < 0)
        return gnutls_assert_val(rc);

      hash_len = _gnutls_hash_get_algo_len (algorithm);
    }

  if (type == GNUTLS_SERVER)
    {
      mesg = SERVER_MSG;
    }
  else
    {
      mesg = CLIENT_MSG;
    }

  return _gnutls_PRF (session, session->security_parameters.master_secret,
                      GNUTLS_MASTER_SIZE, mesg, siz, concat, hash_len, 12, ret);
}


/* returns the 0 on success or a negative error code.
 */
int
_gnutls_negotiate_version (gnutls_session_t session,
                           gnutls_protocol_t adv_version)
{
  int ret;

  /* if we do not support that version  */
  if (_gnutls_version_is_supported (session, adv_version) == 0)
    {
      /* If he requested something we do not support
       * then we send him the highest we support.
       */
      ret = _gnutls_version_max (session);
      if (ret == GNUTLS_VERSION_UNKNOWN)
        {
          /* this check is not really needed.
           */
          gnutls_assert ();
          return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
        }
    }
  else
    {
      ret = adv_version;
    }

  _gnutls_set_current_version (session, ret);

  return ret;
}

int
_gnutls_user_hello_func (gnutls_session_t session,
                         gnutls_protocol_t adv_version)
{
  int ret;

  if (session->internals.user_hello_func != NULL)
    {
      ret = session->internals.user_hello_func (session);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }
      /* Here we need to renegotiate the version since the callee might
       * have disabled some TLS versions.
       */
      ret = _gnutls_negotiate_version (session, adv_version);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }
    }
  return 0;
}

/* Read a client hello packet. 
 * A client hello must be a known version client hello
 * or version 2.0 client hello (only for compatibility
 * since SSL version 2.0 is not supported).
 */
static int
_gnutls_read_client_hello (gnutls_session_t session, uint8_t * data,
                           int datalen)
{
  uint8_t session_id_len;
  int pos = 0, ret;
  uint16_t suite_size, comp_size;
  gnutls_protocol_t adv_version;
  int neg_version;
  int len = datalen;
  uint8_t *suite_ptr, *comp_ptr, *session_id;

  DECR_LEN (len, 2);

  _gnutls_handshake_log ("HSK[%p]: Client's version: %d.%d\n", session,
                         data[pos], data[pos + 1]);

  adv_version = _gnutls_version_get (data[pos], data[pos + 1]);
  set_adv_version (session, data[pos], data[pos + 1]);
  pos += 2;

  neg_version = _gnutls_negotiate_version (session, adv_version);
  if (neg_version < 0)
    {
      gnutls_assert ();
      return neg_version;
    }

  /* Read client random value.
   */
  DECR_LEN (len, GNUTLS_RANDOM_SIZE);
  ret = _gnutls_set_client_random (session, &data[pos]);
  if (ret < 0)
    return gnutls_assert_val(ret);

  pos += GNUTLS_RANDOM_SIZE;

  ret = _gnutls_set_server_random (session, NULL);
  if (ret < 0)
    return gnutls_assert_val(ret);

  session->security_parameters.timestamp = gnutls_time (NULL);

  DECR_LEN (len, 1);
  session_id_len = data[pos++];

  /* RESUME SESSION 
   */
  if (session_id_len > TLS_MAX_SESSION_ID_SIZE)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }
  DECR_LEN (len, session_id_len);
  session_id = &data[pos];
  pos += session_id_len;

  if (IS_DTLS(session))
   {
     int cookie_size;

     DECR_LEN (len, 1);
     cookie_size = data[pos++];
     DECR_LEN (len, cookie_size);
     pos+=cookie_size;
   }

  ret = _gnutls_server_restore_session (session, session_id, session_id_len);
  
  if (session_id_len > 0) session->internals.resumption_requested = 1;

  if (ret == 0)
    {                           /* resumed using default TLS resumption! */
      /* Parse only the safe renegotiation extension
       * We don't want to parse any other extensions since
       * we don't want new extension values to overwrite the
       * resumed ones.
       */

      /* move forward to extensions */
      DECR_LEN (len, 2);
      suite_size = _gnutls_read_uint16 (&data[pos]);
      pos += 2;

      DECR_LEN (len, suite_size);
      pos += suite_size;

      DECR_LEN (len, 1);
      comp_size = data[pos++];  /* z is the number of compression methods */
      DECR_LEN (len, comp_size);
      pos += comp_size;

      ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
                                      &data[pos], len);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

      resume_copy_required_values (session);
      session->internals.resumed = RESUME_TRUE;

      return _gnutls_user_hello_func (session, adv_version);
    }
  else
    {
      _gnutls_generate_session_id (session->security_parameters.session_id,
                                   &session->
                                   security_parameters.session_id_size);

      session->internals.resumed = RESUME_FALSE;
    }

  /* Remember ciphersuites for later
   */
  DECR_LEN (len, 2);
  suite_size = _gnutls_read_uint16 (&data[pos]);
  pos += 2;

  DECR_LEN (len, suite_size);
  suite_ptr = &data[pos];
  pos += suite_size;

  /* Point to the compression methods
   */
  DECR_LEN (len, 1);
  comp_size = data[pos++];      /* z is the number of compression methods */

  DECR_LEN (len, comp_size);
  comp_ptr = &data[pos];
  pos += comp_size;

  /* Parse the extensions (if any)
   *
   * Unconditionally try to parse extensions; safe renegotiation uses them in
   * sslv3 and higher, even though sslv3 doesn't officially support them.
   */
  ret = _gnutls_parse_extensions (session, GNUTLS_EXT_APPLICATION,
                                  &data[pos], len);
  /* len is the rest of the parsed length */
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret = _gnutls_user_hello_func (session, adv_version);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
                                  &data[pos], len);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret = _gnutls_parse_extensions (session, GNUTLS_EXT_TLS, &data[pos], len);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  /* resumed by session_ticket extension */
  if (session->internals.resumed != RESUME_FALSE)
    {
      /* to indicate the client that the current session is resumed */
      memcpy (session->internals.resumed_security_parameters.session_id,
              session_id, session_id_len);
      session->internals.resumed_security_parameters.session_id_size =
        session_id_len;

      session->internals.resumed_security_parameters.max_record_recv_size =
        session->security_parameters.max_record_recv_size;
      session->internals.resumed_security_parameters.max_record_send_size =
        session->security_parameters.max_record_send_size;

      resume_copy_required_values (session);

      return _gnutls_user_hello_func (session, adv_version);
    }

  /* select an appropriate cipher suite
   */
  ret = _gnutls_server_select_suite (session, suite_ptr, suite_size);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  /* select appropriate compression method */
  ret = _gnutls_server_select_comp_method (session, comp_ptr, comp_size);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  return 0;
}

/* This is to be called after sending CHANGE CIPHER SPEC packet
 * and initializing encryption. This is the first encrypted message
 * we send.
 */
static int
_gnutls_send_finished (gnutls_session_t session, int again)
{
  mbuffer_st *bufel;
  uint8_t *data;
  int ret;
  size_t vdata_size = 0;

  if (again == 0)
    {
      bufel = _gnutls_handshake_alloc (session, MAX_VERIFY_DATA_SIZE, MAX_VERIFY_DATA_SIZE);
      if (bufel == NULL)
        {
          gnutls_assert ();
          return GNUTLS_E_MEMORY_ERROR;
        }
      data = _mbuffer_get_udata_ptr (bufel);

      if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
        {
          ret =
            _gnutls_ssl3_finished (session,
                                   session->security_parameters.entity, data, 1);
          _mbuffer_set_udata_size (bufel, 36);
        }
      else
        {                       /* TLS 1.0+ */
          ret = _gnutls_finished (session,
                                  session->security_parameters.entity, data, 1);
          _mbuffer_set_udata_size (bufel, 12);
        }

      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

      vdata_size = _mbuffer_get_udata_size (bufel);

      ret = _gnutls_ext_sr_finished (session, data, vdata_size, 0);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

      if ((session->internals.resumed == RESUME_FALSE
           && session->security_parameters.entity == GNUTLS_CLIENT)
          || (session->internals.resumed != RESUME_FALSE
              && session->security_parameters.entity == GNUTLS_SERVER))
        {
          /* if we are a client not resuming - or we are a server resuming */
          _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (send)\n",
                                 session);
          memcpy (session->internals.cb_tls_unique, data, vdata_size);
          session->internals.cb_tls_unique_len = vdata_size;
        }

      ret =
        _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_FINISHED);
    }
  else
    {
      ret = _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_FINISHED);
    }

  return ret;
}

/* This is to be called after sending our finished message. If everything
 * went fine we have negotiated a secure connection 
 */
static int
_gnutls_recv_finished (gnutls_session_t session)
{
  uint8_t data[MAX_VERIFY_DATA_SIZE], *vrfy;
  gnutls_buffer_st buf;
  int data_size;
  int ret;
  int vrfy_size;

  ret =
    _gnutls_recv_handshake (session, GNUTLS_HANDSHAKE_FINISHED, 
                            0, &buf);
  if (ret < 0)
    {
      ERR ("recv finished int", ret);
      gnutls_assert ();
      return ret;
    }

  vrfy = buf.data;
  vrfy_size = buf.length;

  if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
    {
      data_size = 36;
    }
  else
    {
      data_size = 12;
    }

  if (vrfy_size != data_size)
    {
      gnutls_assert ();
      ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
      goto cleanup;
    }

  if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
    {
      ret =
        _gnutls_ssl3_finished (session,
                               (session->security_parameters.entity + 1) % 2,
                               data, 0);
    }
  else
    {                           /* TLS 1.0 */
      ret =
        _gnutls_finished (session,
                          (session->security_parameters.entity +
                           1) % 2, data, 0);
    }

  if (ret < 0)
    {
      gnutls_assert ();
      goto cleanup;
    }

  if (memcmp (vrfy, data, data_size) != 0)
    {
      gnutls_assert ();
      ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
      goto cleanup;
    }

  ret = _gnutls_ext_sr_finished (session, data, data_size, 1);
  if (ret < 0)
    {
      gnutls_assert ();
      goto cleanup;
    }

  if ((session->internals.resumed != RESUME_FALSE
       && session->security_parameters.entity == GNUTLS_CLIENT)
      || (session->internals.resumed == RESUME_FALSE
          && session->security_parameters.entity == GNUTLS_SERVER))
    {
      /* if we are a client resuming - or we are a server not resuming */
      _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (recv)\n",
                             session);
      memcpy (session->internals.cb_tls_unique, data, data_size);
      session->internals.cb_tls_unique_len = data_size;
    }


  session->internals.initial_negotiation_completed = 1;

cleanup:
  _gnutls_buffer_clear(&buf);

  return ret;
}

/* returns PK_RSA if the given cipher suite list only supports,
 * RSA algorithms, PK_DSA if DSS, and PK_ANY for both or PK_NONE for none.
 */
static int
server_find_pk_algos_in_ciphersuites (const uint8_t *
                                              data, unsigned int datalen,
                                              gnutls_pk_algorithm_t * algos,
                                              size_t* algos_size)
{
  unsigned int j, x;
  gnutls_kx_algorithm_t kx;
  gnutls_pk_algorithm_t pk;
  unsigned found;
  unsigned int max = *algos_size;

  if (datalen % 2 != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }

  *algos_size = 0;
  for (j = 0; j < datalen; j += 2)
    {
      kx = _gnutls_cipher_suite_get_kx_algo (&data[j]);
      if (_gnutls_map_kx_get_cred (kx, 1) == GNUTLS_CRD_CERTIFICATE)
        {
          pk = _gnutls_map_pk_get_pk (kx);
          found = 0;
          for (x=0;x<*algos_size;x++)
            {
              if (algos[x] == pk) 
                {
                  found = 1;
                  break;
                }
            }
          
          if (found == 0)
            {
              algos[(*algos_size)++] = _gnutls_map_pk_get_pk (kx);
              if ((*algos_size) >= max)
                return 0;
            }
        }
    }

  return 0;
}

/* This selects the best supported ciphersuite from the given ones. Then
 * it adds the suite to the session and performs some checks.
 */
int
_gnutls_server_select_suite (gnutls_session_t session, uint8_t * data,
                             unsigned int datalen)
{
  int ret;
  unsigned int i, j, cipher_suites_size;
  size_t pk_algos_size;
  uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
  int retval, err;
  gnutls_pk_algorithm_t pk_algos[MAX_ALGOS];        /* will hold the pk algorithms
                                         * supported by the peer.
                                         */

  /* First, check for safe renegotiation SCSV.
   */
  if (session->internals.priorities.sr != SR_DISABLED)
    {
      unsigned int offset;

      for (offset = 0; offset < datalen; offset += 2)
        {
          /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */
          if (data[offset] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&
              data[offset + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR)
            {
              _gnutls_handshake_log
                ("HSK[%p]: Received safe renegotiation CS\n", session);
              retval = _gnutls_ext_sr_recv_cs (session);
              if (retval < 0)
                {
                  gnutls_assert ();
                  return retval;
                }
              break;
            }
        }
    }

  pk_algos_size = MAX_ALGOS;
  ret = server_find_pk_algos_in_ciphersuites (data, datalen, pk_algos, &pk_algos_size);
  if (ret < 0)
    return gnutls_assert_val(ret);

  ret = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites));
  if (ret < 0)
    return gnutls_assert_val(ret);

  cipher_suites_size = ret;

  /* Here we remove any ciphersuite that does not conform
   * the certificate requested, or to the
   * authentication requested (e.g. SRP).
   */
  ret = _gnutls_remove_unwanted_ciphersuites (session, cipher_suites, cipher_suites_size, pk_algos, pk_algos_size);
  if (ret <= 0)
    {
      gnutls_assert ();
      if (ret < 0)
        return ret;
      else
        return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
    }
    
  cipher_suites_size = ret;

  /* Data length should be zero mod 2 since
   * every ciphersuite is 2 bytes. (this check is needed
   * see below).
   */
  if (datalen % 2 != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }

  memset (session->security_parameters.cipher_suite, 0, 2);

  retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;

  _gnutls_handshake_log ("HSK[%p]: Requested cipher suites[size: %d]: \n", session, (int)datalen);

  if (session->internals.priorities.server_precedence == 0)
    {
      for (j = 0; j < datalen; j += 2)
        {
          _gnutls_handshake_log ("\t0x%.2x, 0x%.2x %s\n", data[j], data[j+1], _gnutls_cipher_suite_get_name (&data[j]));
          for (i = 0; i < cipher_suites_size; i+=2)
            {
              if (memcmp (&cipher_suites[i], &data[j], 2) == 0)
                {
                  _gnutls_handshake_log
                    ("HSK[%p]: Selected cipher suite: %s\n", session,
                    _gnutls_cipher_suite_get_name (&data[j]));
                  memcpy (session->security_parameters.cipher_suite,
                      &cipher_suites[i], 2);
                  _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
                                                  session->
                                                  security_parameters.cipher_suite);


                  retval = 0;
                  goto finish;
                }
            }
        }
    }
  else /* server selects */
    {
      for (i = 0; i < cipher_suites_size; i+=2)
        {
          for (j = 0; j < datalen; j += 2)
            {
              if (memcmp (&cipher_suites[i], &data[j], 2) == 0)
                {
                  _gnutls_handshake_log
                    ("HSK[%p]: Selected cipher suite: %s\n", session,
                    _gnutls_cipher_suite_get_name (&data[j]));
                  memcpy (session->security_parameters.cipher_suite,
                      &cipher_suites[i], 2);
                  _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
                                                  session->
                                                  security_parameters.cipher_suite);


                  retval = 0;
                  goto finish;
                }
            }
        }
    }
finish:

  if (retval != 0)
    {
      gnutls_assert ();
      return retval;
    }

  /* check if the credentials (username, public key etc.) are ok
   */
  if (_gnutls_get_kx_cred
      (session,
       _gnutls_cipher_suite_get_kx_algo (session->
                                         security_parameters.cipher_suite),
       &err) == NULL && err != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
    }


  /* set the mod_auth_st to the appropriate struct
   * according to the KX algorithm. This is needed since all the
   * handshake functions are read from there;
   */
  session->internals.auth_struct =
    _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
                            (session->
                             security_parameters.cipher_suite));
  if (session->internals.auth_struct == NULL)
    {

      _gnutls_handshake_log
        ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
         session);
      gnutls_assert ();
      return GNUTLS_E_INTERNAL_ERROR;
    }

  return 0;

}


/* This selects the best supported compression method from the ones provided 
 */
static int
_gnutls_server_select_comp_method (gnutls_session_t session,
                                   uint8_t * data, int datalen)
{
  int x, i, j;
  uint8_t comps[MAX_ALGOS];

  x = _gnutls_supported_compression_methods (session, comps, MAX_ALGOS);
  if (x < 0)
    {
      gnutls_assert ();
      return x;
    }

  if (session->internals.priorities.server_precedence == 0)
    {
      for (j = 0; j < datalen; j++)
        {
          for (i = 0; i < x; i++)
            {
              if (comps[i] == data[j])
                {
                  gnutls_compression_method_t method =
                    _gnutls_compression_get_id (comps[i]);

                  _gnutls_epoch_set_compression (session, EPOCH_NEXT, method);
                  session->security_parameters.compression_method = method;

                  _gnutls_handshake_log
                    ("HSK[%p]: Selected Compression Method: %s\n", session,
                    gnutls_compression_get_name (method));
                  return 0;
                }
            }
        }
    }
  else
    {
      for (i = 0; i < x; i++)
        {
          for (j = 0; j < datalen; j++)
            {
              if (comps[i] == data[j])
                {
                  gnutls_compression_method_t method =
                    _gnutls_compression_get_id (comps[i]);

                  _gnutls_epoch_set_compression (session, EPOCH_NEXT, method);
                  session->security_parameters.compression_method = method;

                  _gnutls_handshake_log
                    ("HSK[%p]: Selected Compression Method: %s\n", session,
                    gnutls_compression_get_name (method));
                  return 0;
                }
            }
        }
    }

  /* we were not able to find a compatible compression
   * algorithm
   */
  gnutls_assert ();
  return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;

}

/* This function sends an empty handshake packet. (like hello request).
 * If the previous _gnutls_send_empty_handshake() returned
 * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
 * (until it returns ok), with NULL parameters.
 */
static int
_gnutls_send_empty_handshake (gnutls_session_t session,
                              gnutls_handshake_description_t type, int again)
{
  mbuffer_st *bufel;

  if (again == 0)
    {
      bufel = _gnutls_handshake_alloc (session, 0, 0);
      if (bufel == NULL)
        {
          gnutls_assert ();
          return GNUTLS_E_MEMORY_ERROR;
        }
    }
  else
    bufel = NULL;

  return _gnutls_send_handshake (session, bufel, type);
}




/* This function sends a handshake message of type 'type' containing the
 * data specified here. If the previous _gnutls_send_handshake() returned
 * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
 * (until it returns ok), with NULL parameters.
 */
int
_gnutls_send_handshake (gnutls_session_t session, mbuffer_st * bufel,
                        gnutls_handshake_description_t type)
{
  int ret;
  uint8_t *data;
  uint32_t datasize, i_datasize;
  int pos = 0;

  if (bufel == NULL)
    {
      /* we are resuming a previously interrupted
       * send.
       */
      ret = _gnutls_handshake_io_write_flush (session);
      return ret;

    }

  /* first run */
  data = _mbuffer_get_uhead_ptr (bufel);
  i_datasize = _mbuffer_get_udata_size(bufel);
  datasize = i_datasize + _mbuffer_get_uhead_size (bufel);

  data[pos++] = (uint8_t) type;
  _gnutls_write_uint24 (_mbuffer_get_udata_size (bufel), &data[pos]);
  pos += 3;

  /* Add DTLS handshake fragment headers.  The message will be
   * fragmented later by the fragmentation sub-layer. All fields must
   * be set properly for HMAC. The HMAC requires we pretend that the
   * message was sent in a single fragment. */
  if (IS_DTLS(session))
    {
      _gnutls_write_uint16 (session->internals.dtls.hsk_write_seq++, &data[pos]);
      pos += 2;

      /* Fragment offset */
      _gnutls_write_uint24 (0, &data[pos]);
      pos += 3;

      /* Fragment length */
      _gnutls_write_uint24 (i_datasize, &data[pos]);
      /* pos += 3; */
    }

  _gnutls_handshake_log ("HSK[%p]: %s was queued [%ld bytes]\n",
                         session, _gnutls_handshake2str (type),
                         (long) datasize);

  /* Here we keep the handshake messages in order to hash them...
   */
  if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
    if ((ret =
         _gnutls_handshake_hash_add_sent (session, type, data, datasize)) < 0)
      {
        gnutls_assert ();
        _mbuffer_xfree(&bufel);
        return ret;
      }

  session->internals.last_handshake_out = type;

  ret = _gnutls_handshake_io_cache_int (session, type, bufel);
  if (ret < 0)
    {
      _mbuffer_xfree(&bufel);
      gnutls_assert();
      return ret;
    }

  switch (type)
    {
    case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:     /* this one is followed by ServerHelloDone
                                                * or ClientKeyExchange always.
                                                */
    case GNUTLS_HANDSHAKE_CERTIFICATE_STATUS:
    case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE: /* as above */
    case GNUTLS_HANDSHAKE_SERVER_HELLO:        /* as above */
    case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST: /* as above */
    case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:  /* followed by ChangeCipherSpec */

      /* now for client Certificate, ClientKeyExchange and
       * CertificateVerify are always followed by ChangeCipherSpec
       */
    case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
    case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
      ret = 0;
      break;
    default:
      /* send cached messages */
      ret = _gnutls_handshake_io_write_flush (session);
      break;
    }

  return ret;
}

#define CHECK_SIZE(ll) \
  if ((session->internals.max_handshake_data_buffer_size > 0) && \
      (((ll) + session->internals.handshake_hash_buffer.length) > \
       session->internals.max_handshake_data_buffer_size)) \
    return gnutls_assert_val(GNUTLS_E_HANDSHAKE_TOO_LARGE)

/* This function add the handshake headers and the
 * handshake data to the handshake hash buffers. Needed
 * for the finished messages calculations.
 */
static int
_gnutls_handshake_hash_add_recvd (gnutls_session_t session,
                                  gnutls_handshake_description_t recv_type,
                                  uint8_t * header, uint16_t header_size,
                                  uint8_t * dataptr, uint32_t datalen)
{
  int ret;

  if ((gnutls_protocol_get_version (session) != GNUTLS_DTLS0_9 &&
       recv_type == GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST) ||
      recv_type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
    return 0;

  CHECK_SIZE(header_size + datalen);

  session->internals.handshake_hash_buffer_prev_len = session->internals.handshake_hash_buffer.length;

  if (gnutls_protocol_get_version (session) != GNUTLS_DTLS0_9)
    {
      ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
        header, header_size);
      if (ret < 0)
        return gnutls_assert_val(ret);
  }
  if (datalen > 0)
    {
      ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
                                       dataptr, datalen);
      if (ret < 0)
        return gnutls_assert_val(ret);
    }

  return 0;
}

/* This function will store the handshake message we sent.
 */
static int
_gnutls_handshake_hash_add_sent (gnutls_session_t session,
                                 gnutls_handshake_description_t type,
                                 uint8_t * dataptr, uint32_t datalen)
{
  int ret;

  /* We don't check for GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST because it
   * is not sent via that channel.
   */
  if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
    {
      CHECK_SIZE(datalen);

      if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9) 
        {
	  /* Old DTLS doesn't include the header in the MAC */
	  if (datalen < 12) 
	    {
	      gnutls_assert ();
	      return GNUTLS_E_INTERNAL_ERROR;
	    }
	  dataptr += 12;
	  datalen -= 12;
	  
	  if (datalen == 0)
	  	return 0;
        }

      ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
                                       dataptr, datalen);
      if (ret < 0)
        return gnutls_assert_val(ret);

      return 0;
    }

  return 0;
}


/* This function will receive handshake messages of the given types,
 * and will pass the message to the right place in order to be processed.
 * E.g. for the SERVER_HELLO message (if it is expected), it will be
 * passed to _gnutls_recv_hello().
 */
int
_gnutls_recv_handshake (gnutls_session_t session, 
                        gnutls_handshake_description_t type,
                        unsigned int optional, gnutls_buffer_st* buf)
{
  int ret;
  handshake_buffer_st hsk;

  ret =
    _gnutls_handshake_io_recv_int (session, type, &hsk, optional);
  if (ret < 0)
    {
      if (optional != 0 && ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET)
        {
          if (buf) _gnutls_buffer_init(buf);
          return 0;
        }

      return gnutls_assert_val_fatal(ret);
    }

  session->internals.last_handshake_in = hsk.htype;

  ret = _gnutls_handshake_hash_add_recvd (session, hsk.htype,
                                              hsk.header, hsk.header_size,
                                              hsk.data.data, hsk.data.length);
  if (ret < 0)
    {
      gnutls_assert ();
      goto cleanup;
    }

  switch (hsk.htype)
    {
    case GNUTLS_HANDSHAKE_CLIENT_HELLO_V2:
    case GNUTLS_HANDSHAKE_CLIENT_HELLO:
    case GNUTLS_HANDSHAKE_SERVER_HELLO:
      if (hsk.htype == GNUTLS_HANDSHAKE_CLIENT_HELLO_V2)
        ret = _gnutls_read_client_hello_v2 (session, hsk.data.data, hsk.data.length);
      else
        ret = _gnutls_recv_hello (session, hsk.data.data, hsk.data.length);

      if (ret < 0)
        {
          gnutls_assert();
          goto cleanup;
        }

      goto cleanup; /* caller doesn't need dataptr */

      break;
    case GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST:
      ret = _gnutls_recv_hello_verify_request (session, hsk.data.data, hsk.data.length);
      if (ret < 0)
        {
          gnutls_assert();
          goto cleanup;
        }
      else
        /* Signal our caller we have received a verification cookie
           and ClientHello needs to be sent again. */
        ret = 1;
	
      goto cleanup; /* caller doesn't need dataptr */

      break;
    case GNUTLS_HANDSHAKE_SERVER_HELLO_DONE:
      if (hsk.data.length == 0)
        ret = 0;
      else
        {
          gnutls_assert();
          ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
          goto cleanup;
        }
      break;
    case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:
    case GNUTLS_HANDSHAKE_CERTIFICATE_STATUS:
    case GNUTLS_HANDSHAKE_FINISHED:
    case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE:
    case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
    case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:
    case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
    case GNUTLS_HANDSHAKE_SUPPLEMENTAL:
    case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:
      ret = hsk.data.length;
      break;
    default:
      gnutls_assert ();
      /* we shouldn't actually arrive here in any case .
       * unexpected messages should be catched after _gnutls_handshake_io_recv_int()
       */
      ret = GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
      goto cleanup;
    }

  if (buf)
    {
      *buf = hsk.data;
      return ret;
    }

cleanup:
  _gnutls_handshake_buffer_clear (&hsk);
  return ret;
}

/* This function checks if the given cipher suite is supported, and sets it
 * to the session;
 */
static int
_gnutls_client_set_ciphersuite (gnutls_session_t session, uint8_t suite[2])
{
  uint8_t z;
  uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
  int cipher_suite_size;
  int i, err;

  z = 1;
  cipher_suite_size = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites));
  if (cipher_suite_size < 0)
    {
      gnutls_assert ();
      return cipher_suite_size;
    }

  for (i = 0; i < cipher_suite_size; i+=2)
    {
      if (memcmp (&cipher_suites[i], suite, 2) == 0)
        {
          z = 0;
          break;
        }
    }

  if (z != 0)
    {
      gnutls_assert ();
      _gnutls_handshake_log("HSK[%p]: unsupported cipher suite %.2X.%.2X\n", session,
                        (unsigned int)suite[0], (unsigned int)suite[1]);
      return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
    }

  memcpy (session->security_parameters.cipher_suite, suite, 2);
  _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
                                  session->
                                  security_parameters.cipher_suite);

  _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session,
                         _gnutls_cipher_suite_get_name
                         (session->
                          security_parameters.cipher_suite));


  /* check if the credentials (username, public key etc.) are ok.
   * Actually checks if they exist.
   */
  if (!session->internals.premaster_set &&
      _gnutls_get_kx_cred
      (session,
       _gnutls_cipher_suite_get_kx_algo
       (session->security_parameters.cipher_suite), &err) == NULL
      && err != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
    }


  /* set the mod_auth_st to the appropriate struct
   * according to the KX algorithm. This is needed since all the
   * handshake functions are read from there;
   */
  session->internals.auth_struct =
    _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
                            (session->
                             security_parameters.cipher_suite));

  if (session->internals.auth_struct == NULL)
    {

      _gnutls_handshake_log
        ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
         session);
      gnutls_assert ();
      return GNUTLS_E_INTERNAL_ERROR;
    }


  return 0;
}

/* This function sets the given comp method to the session.
 */
static int
_gnutls_client_set_comp_method (gnutls_session_t session, uint8_t comp_method)
{
  int comp_methods_num;
  uint8_t compression_methods[MAX_ALGOS];
  int id = _gnutls_compression_get_id(comp_method);
  int i;

  _gnutls_handshake_log ("HSK[%p]: Selected compression method: %s (%d)\n", session,
                         gnutls_compression_get_name(id), (int)comp_method);

  comp_methods_num = _gnutls_supported_compression_methods (session,
                                                            compression_methods, MAX_ALGOS);
  if (comp_methods_num < 0)
    {
      gnutls_assert ();
      return comp_methods_num;
    }

  for (i = 0; i < comp_methods_num; i++)
    {
      if (compression_methods[i] == comp_method)
        {
          comp_methods_num = 0;
          break;
        }
    }

  if (comp_methods_num != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
    }

  session->security_parameters.compression_method = id;
  _gnutls_epoch_set_compression (session, EPOCH_NEXT, id);

  return 0;
}

/* This function returns 0 if we are resuming a session or -1 otherwise.
 * This also sets the variables in the session. Used only while reading a server
 * hello.
 */
static int
_gnutls_client_check_if_resuming (gnutls_session_t session,
                                  uint8_t * session_id, int session_id_len)
{
  char buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];

  _gnutls_handshake_log ("HSK[%p]: SessionID length: %d\n", session,
                         session_id_len);
  _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
                         _gnutls_bin2hex (session_id, session_id_len, buf,
                                          sizeof (buf), NULL));

  if (session_id_len > 0 &&
      session->internals.resumed_security_parameters.session_id_size ==
      session_id_len
      && memcmp (session_id,
                 session->internals.resumed_security_parameters.session_id,
                 session_id_len) == 0)
    {
      /* resume session */
      memcpy (session->internals.resumed_security_parameters.server_random,
              session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
      memcpy (session->internals.resumed_security_parameters.client_random,
              session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);

      memcpy(session->security_parameters.cipher_suite,
			session->internals.resumed_security_parameters.cipher_suite, 2);
      session->security_parameters.compression_method =
		        session->internals.resumed_security_parameters.compression_method;

      _gnutls_epoch_set_cipher_suite
        (session, EPOCH_NEXT,
         session->internals.
         resumed_security_parameters.cipher_suite);
      _gnutls_epoch_set_compression (session, EPOCH_NEXT,
                                     session->
                                     internals.resumed_security_parameters.compression_method);

      session->internals.resumed = RESUME_TRUE; /* we are resuming */

      return 0;
    }
  else
    {
      /* keep the new session id */
      session->internals.resumed = RESUME_FALSE;        /* we are not resuming */
      session->security_parameters.session_id_size = session_id_len;
      memcpy (session->security_parameters.session_id,
              session_id, session_id_len);

      return -1;
    }
}


/* This function reads and parses the server hello handshake message.
 * This function also restores resumed parameters if we are resuming a
 * session.
 */
static int
_gnutls_read_server_hello (gnutls_session_t session,
                           uint8_t * data, int datalen)
{
  uint8_t session_id_len = 0;
  int pos = 0;
  int ret = 0;
  gnutls_protocol_t version;
  int len = datalen;

  if (datalen < 38)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }

  _gnutls_handshake_log ("HSK[%p]: Server's version: %d.%d\n",
                         session, data[pos], data[pos + 1]);

  DECR_LEN (len, 2);
  version = _gnutls_version_get (data[pos], data[pos + 1]);
  if (_gnutls_version_is_supported (session, version) == 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
    }
  else
    {
      _gnutls_set_current_version (session, version);
    }

  pos += 2;

  DECR_LEN (len, GNUTLS_RANDOM_SIZE);
  ret = _gnutls_set_server_random (session, &data[pos]);
  if (ret < 0)
    return gnutls_assert_val(ret);

  pos += GNUTLS_RANDOM_SIZE;


  /* Read session ID
   */
  DECR_LEN (len, 1);
  session_id_len = data[pos++];

  if (len < session_id_len)
    {
      gnutls_assert ();
      return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
    }
  DECR_LEN (len, session_id_len);

  /* check if we are resuming and set the appropriate
   * values;
   */
  if (_gnutls_client_check_if_resuming
      (session, &data[pos], session_id_len) == 0)
    {
      pos += session_id_len + 2 + 1;
      DECR_LEN (len, 2 + 1);

      ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
                                      &data[pos], len);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }
      return 0;
    }

  pos += session_id_len;

  /* Check if the given cipher suite is supported and copy
   * it to the session.
   */

  DECR_LEN (len, 2);
  ret = _gnutls_client_set_ciphersuite (session, &data[pos]);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }
  pos += 2;

  /* move to compression 
   */
  DECR_LEN (len, 1);

  ret = _gnutls_client_set_comp_method (session, data[pos++]);
  if (ret < 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
    }

  /* Parse extensions.
   */
  ret = _gnutls_parse_extensions (session, GNUTLS_EXT_ANY, &data[pos], len);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  return ret;
}


/* This function copies the appropriate ciphersuites to a locally allocated buffer
 * Needed in client hello messages. Returns the new data length. If add_scsv is
 * true, add the special safe renegotiation CS.
 */
static int
_gnutls_copy_ciphersuites (gnutls_session_t session,
                           gnutls_buffer_st * cdata, 
                           int add_scsv)
{
  int ret;
  uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE+2];
  int cipher_suites_size;
  size_t init_length = cdata->length;

  ret = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites)-2);
  if (ret < 0)
    return gnutls_assert_val(ret);

  /* Here we remove any ciphersuite that does not conform
   * the certificate requested, or to the
   * authentication requested (eg SRP).
   */
  ret =
    _gnutls_remove_unwanted_ciphersuites (session, cipher_suites, ret, NULL, 0);
  if (ret < 0)
    return gnutls_assert_val(ret);

  /* If no cipher suites were enabled.
   */
  if (ret == 0)
    return gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);

  cipher_suites_size = ret;
  if (add_scsv)
    {
      cipher_suites[cipher_suites_size] = 0x00;
      cipher_suites[cipher_suites_size+1] = 0xff;
      cipher_suites_size += 2;

      ret = _gnutls_ext_sr_send_cs (session);
      if (ret < 0)
        return gnutls_assert_val(ret);
    }

  ret = _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites, cipher_suites_size);
  if (ret < 0)
    return gnutls_assert_val(ret);

  ret = cdata->length - init_length;

  return ret;
}


/* This function copies the appropriate compression methods, to a locally allocated buffer 
 * Needed in hello messages. Returns the new data length.
 */
static int
_gnutls_copy_comp_methods (gnutls_session_t session,
                           gnutls_buffer_st * cdata)
{
  int ret;
  uint8_t compression_methods[MAX_ALGOS], comp_num;
  size_t init_length = cdata->length;

  ret = _gnutls_supported_compression_methods (session, compression_methods, MAX_ALGOS);
  if (ret < 0)
    return gnutls_assert_val(ret);

  comp_num = ret;

  /* put the number of compression methods */
  ret = _gnutls_buffer_append_prefix(cdata, 8, comp_num);
  if (ret < 0)
    return gnutls_assert_val(ret);

  ret = _gnutls_buffer_append_data(cdata, compression_methods, comp_num);
  if (ret < 0)
    return gnutls_assert_val(ret);

  ret = cdata->length - init_length;

  return ret;
}

/* This should be sufficient by now. It should hold all the extensions
 * plus the headers in a hello message.
 */
#define MAX_EXT_DATA_LENGTH 32*1024

/* This function sends the client hello handshake message.
 */
static int
_gnutls_send_client_hello (gnutls_session_t session, int again)
{
  mbuffer_st *bufel = NULL;
  uint8_t *data = NULL;
  int pos = 0, type;
  int datalen = 0, ret = 0;
  gnutls_protocol_t hver;
  gnutls_buffer_st extdata;
  int rehandshake = 0;
  uint8_t session_id_len =
    session->internals.resumed_security_parameters.session_id_size;
  uint8_t cookie_len;

  _gnutls_buffer_init(&extdata);

  /* note that rehandshake is different than resuming
   */
  if (session->security_parameters.session_id_size)
    rehandshake = 1;

  if (again == 0)
    {
      if(IS_DTLS(session))
        {
          cookie_len = session->internals.dtls.cookie_len + 1;
        }
      else
	{
	  cookie_len = 0;
	}

      datalen = 2 + (session_id_len + 1) + GNUTLS_RANDOM_SIZE + cookie_len;
      /* 2 for version, (4 for unix time + 28 for random bytes==GNUTLS_RANDOM_SIZE) 
       */

      bufel = _gnutls_handshake_alloc (session, datalen, datalen+MAX_EXT_DATA_LENGTH);
      if (bufel == NULL)
        {
          gnutls_assert ();
          return GNUTLS_E_MEMORY_ERROR;
        }
      data = _mbuffer_get_udata_ptr (bufel);

      /* if we are resuming a session then we set the
       * version number to the previously established.
       */
      if (session_id_len == 0)
        {
          if (rehandshake)      /* already negotiated version thus version_max == negotiated version */
            hver = session->security_parameters.version;
          else                  /* new handshake. just get the max */
            hver = _gnutls_version_max (session);
        }
      else
        {
          /* we are resuming a session */
          hver = session->internals.resumed_security_parameters.version;
        }

      if (hver == GNUTLS_VERSION_UNKNOWN || hver == 0)
        {
          gnutls_assert ();
          gnutls_free (bufel);
          return GNUTLS_E_INTERNAL_ERROR;
        }

      data[pos++] = _gnutls_version_get_major (hver);
      data[pos++] = _gnutls_version_get_minor (hver);

      /* Set the version we advertized as maximum 
       * (RSA uses it).
       */
      _gnutls_set_adv_version (session, hver);
      _gnutls_set_current_version (session, hver);

      if (session->internals.priorities.ssl3_record_version != 0)
        {
          /* Advertize the SSL 3.0 record packet version in
           * record packets during the handshake.
           * That is to avoid confusing implementations
           * that do not support TLS 1.2 and don't know
           * how 3,3 version of record packets look like.
           */
          if (!IS_DTLS(session))
            _gnutls_record_set_default_version (session, 3, 0);
          else if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9)
            _gnutls_record_set_default_version (session, 1, 0);
          else
            _gnutls_record_set_default_version (session, 254, 255);
        }

      /* In order to know when this session was initiated.
       */
      session->security_parameters.timestamp = gnutls_time (NULL);

      /* Generate random data 
       */
      if (!IS_DTLS (session)
        || session->internals.dtls.hsk_hello_verify_requests == 0)
        {
          ret = _gnutls_set_client_random (session, NULL);
          if (ret < 0)
            return gnutls_assert_val(ret);

          memcpy (&data[pos], session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
        }
      else
        memcpy (&data[pos], session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);

      pos += GNUTLS_RANDOM_SIZE;

      /* Copy the Session ID 
       */
      data[pos++] = session_id_len;

      if (session_id_len > 0)
        {
          memcpy (&data[pos],
                  session->internals.resumed_security_parameters.session_id,
                  session_id_len);
          pos += session_id_len;
        }

      /* Copy the DTLS cookie
       */
      if (IS_DTLS(session))
        {
          data[pos++] = session->internals.dtls.cookie_len;
          memcpy(&data[pos], session->internals.dtls.cookie, session->internals.dtls.cookie_len);
          /* pos += session->internals.dtls.cookie_len; */
        }

      /* Copy the ciphersuites.
       *
       * If using SSLv3 Send TLS_RENEGO_PROTECTION_REQUEST SCSV for MITM
       * prevention on initial negotiation (but not renegotiation; that's
       * handled with the RI extension below).
       */
      if (!session->internals.initial_negotiation_completed &&
          session->security_parameters.entity == GNUTLS_CLIENT &&
          (gnutls_protocol_get_version (session) == GNUTLS_SSL3 || 
          session->internals.priorities.no_extensions != 0))
        {
          ret =
            _gnutls_copy_ciphersuites (session, &extdata, TRUE);
          _gnutls_extension_list_add (session,
                                      GNUTLS_EXTENSION_SAFE_RENEGOTIATION);
        }
      else
        ret = _gnutls_copy_ciphersuites (session, &extdata, FALSE);

      if (ret < 0)
        {
          gnutls_assert();
          goto cleanup;
        }

      /* Copy the compression methods.
       */
      ret = _gnutls_copy_comp_methods (session, &extdata);
      if (ret < 0)
        {
          gnutls_assert();
          goto cleanup;
        }

      /* Generate and copy TLS extensions.
       */
      if (session->internals.priorities.no_extensions == 0)
        {
          if (_gnutls_version_has_extensions (hver))
            type = GNUTLS_EXT_ANY;
          else
            {
              if (session->internals.initial_negotiation_completed != 0)
                type = GNUTLS_EXT_MANDATORY;
              else
                type = GNUTLS_EXT_NONE;
            }

          ret = _gnutls_gen_extensions (session, &extdata, type);
          if (ret < 0)
            {
              gnutls_assert();
              goto cleanup;
            }

        }

      ret = _mbuffer_append_data (bufel, extdata.data, extdata.length);
      if (ret < 0)
        {
          gnutls_assert ();
          goto cleanup;
        }
    }

  _gnutls_buffer_clear(&extdata);

  return
    _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_CLIENT_HELLO);

cleanup:
  _mbuffer_xfree(&bufel);
  _gnutls_buffer_clear(&extdata);
  return ret;
}

static int
_gnutls_send_server_hello (gnutls_session_t session, int again)
{
  mbuffer_st *bufel = NULL;
  uint8_t *data = NULL;
  gnutls_buffer_st extdata;
  int pos = 0;
  int datalen, ret = 0;
  uint8_t comp;
  uint8_t session_id_len = session->security_parameters.session_id_size;
  char buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];

  _gnutls_buffer_init(&extdata);

  if (again == 0)
    {
      datalen = 2 + session_id_len + 1 + GNUTLS_RANDOM_SIZE + 3;
      ret =
        _gnutls_gen_extensions (session, &extdata, 
                                (session->internals.resumed==RESUME_TRUE)?
                                GNUTLS_EXT_MANDATORY:GNUTLS_EXT_ANY);
      if (ret < 0)
        {
          gnutls_assert ();
          goto fail;
        }

      bufel = _gnutls_handshake_alloc (session, datalen + extdata.length, datalen + extdata.length);
      if (bufel == NULL)
        {
          gnutls_assert ();
          ret = GNUTLS_E_MEMORY_ERROR;
          goto fail;
        }
      data = _mbuffer_get_udata_ptr (bufel);

      data[pos++] =
        _gnutls_version_get_major (session->security_parameters.version);
      data[pos++] =
        _gnutls_version_get_minor (session->security_parameters.version);

      memcpy (&data[pos],
              session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
      pos += GNUTLS_RANDOM_SIZE;

      data[pos++] = session_id_len;
      if (session_id_len > 0)
        {
          memcpy (&data[pos], session->security_parameters.session_id,
                  session_id_len);
        }
      pos += session_id_len;

      _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
                             _gnutls_bin2hex (session->security_parameters.
                                              session_id, session_id_len, buf,
                                              sizeof (buf), NULL));

      memcpy (&data[pos],
              session->security_parameters.cipher_suite, 2);
      pos += 2;

      comp = _gnutls_compression_get_num ( session->security_parameters.compression_method);
      data[pos++] = comp;

      if (extdata.length > 0)
        {
          memcpy (&data[pos], extdata.data, extdata.length);
        }
    }

  ret =
    _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_SERVER_HELLO);

fail:
  _gnutls_buffer_clear(&extdata);
  return ret;
}

int
_gnutls_send_hello (gnutls_session_t session, int again)
{
  int ret;

  if (session->security_parameters.entity == GNUTLS_CLIENT)
    {
      ret = _gnutls_send_client_hello (session, again);

    }
  else
    {                           /* SERVER */
      ret = _gnutls_send_server_hello (session, again);
    }

  return ret;
}

/* RECEIVE A HELLO MESSAGE. This should be called from gnutls_recv_handshake_int only if a
 * hello message is expected. It uses the security_parameters.cipher_suite
 * and internals.compression_method.
 */
int
_gnutls_recv_hello (gnutls_session_t session, uint8_t * data, int datalen)
{
  int ret;

  if (session->security_parameters.entity == GNUTLS_CLIENT)
    {
      ret = _gnutls_read_server_hello (session, data, datalen);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }
    }
  else
    {                           /* Server side reading a client hello */

      ret = _gnutls_read_client_hello (session, data, datalen);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }
    }

  ret = _gnutls_ext_sr_verify (session);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  return 0;
}

static int
_gnutls_recv_hello_verify_request (gnutls_session_t session,
				   uint8_t * data, int datalen)
{
  ssize_t len = datalen;
  size_t pos = 0;
  uint8_t cookie_len;
  unsigned int nb_verifs;

  if (!IS_DTLS (session)
      || session->security_parameters.entity == GNUTLS_SERVER)
    {
      gnutls_assert ();
      return GNUTLS_E_INTERNAL_ERROR;
    }

  nb_verifs = ++session->internals.dtls.hsk_hello_verify_requests;
  if (nb_verifs >= MAX_HANDSHAKE_HELLO_VERIFY_REQUESTS)
    {
      /* The server is either buggy, malicious or changing cookie
	 secrets _way_ too fast. */
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET;
    }

  /* TODO: determine if we need to do anything with the server version field */
  DECR_LEN (len, 2);
  pos += 2;

  DECR_LEN (len, 1);
  cookie_len = data[pos];
  pos++;

  if (cookie_len > DTLS_MAX_COOKIE_SIZE)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }

  DECR_LEN (len, cookie_len);

  session->internals.dtls.cookie_len = cookie_len;
  memcpy (session->internals.dtls.cookie, &data[pos], cookie_len);

  if (len != 0)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }

  /* reset handshake hash buffers */
  _gnutls_handshake_hash_buffer_empty (session);

  return 0;
}

/* The packets in gnutls_handshake (it's more broad than original TLS handshake)
 *
 *     Client                                               Server
 *
 *     ClientHello                  -------->
 *                                  <--------         ServerHello
 *
 *                                                    Certificate*
 *                                              ServerKeyExchange*
 *                                  <--------   CertificateRequest*
 *
 *                                  <--------      ServerHelloDone
 *     Certificate*
 *     ClientKeyExchange
 *     CertificateVerify*
 *     [ChangeCipherSpec]
 *     Finished                     -------->
 *                                                NewSessionTicket
 *                                              [ChangeCipherSpec]
 *                                  <--------             Finished
 *
 * (*): means optional packet.
 */

/* Handshake when resumming session:
 *      Client                                                Server
 *
 *      ClientHello                   -------->
 *                                                      ServerHello
 *                                               [ChangeCipherSpec]
 *                                   <--------             Finished
 *     [ChangeCipherSpec]
 *     Finished                      -------->
 * 
 */

/**
 * gnutls_rehandshake:
 * @session: is a #gnutls_session_t structure.
 *
 * This function will renegotiate security parameters with the
 * client.  This should only be called in case of a server.
 *
 * This message informs the peer that we want to renegotiate
 * parameters (perform a handshake).
 *
 * If this function succeeds (returns 0), you must call the
 * gnutls_handshake() function in order to negotiate the new
 * parameters.
 *
 * Since TLS is full duplex some application data might have been
 * sent during peer's processing of this message. In that case
 * one should call gnutls_record_recv() until GNUTLS_E_REHANDSHAKE
 * is returned to clear any pending data. Care must be taken if
 * rehandshake is mandatory to terminate if it does not start after
 * some threshold.
 *
 * If the client does not wish to renegotiate parameters he will
 * should with an alert message, thus the return code will be
 * %GNUTLS_E_WARNING_ALERT_RECEIVED and the alert will be
 * %GNUTLS_A_NO_RENEGOTIATION.  A client may also choose to ignore
 * this message.
 *
 * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
 **/
int
gnutls_rehandshake (gnutls_session_t session)
{
  int ret;

  /* only server sends that handshake packet */
  if (session->security_parameters.entity == GNUTLS_CLIENT)
    return GNUTLS_E_INVALID_REQUEST;

  _dtls_async_timer_delete(session);

  ret =
    _gnutls_send_empty_handshake (session, GNUTLS_HANDSHAKE_HELLO_REQUEST,
                                  AGAIN (STATE50));
  STATE = STATE50;

  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }
  STATE = STATE0;

  return 0;
}

inline static int
_gnutls_abort_handshake (gnutls_session_t session, int ret)
{
  if (((ret == GNUTLS_E_WARNING_ALERT_RECEIVED) &&
       (gnutls_alert_get (session) == GNUTLS_A_NO_RENEGOTIATION))
      || ret == GNUTLS_E_GOT_APPLICATION_DATA)
    return 0;

  /* this doesn't matter */
  return GNUTLS_E_INTERNAL_ERROR;
}



static int
_gnutls_send_supplemental (gnutls_session_t session, int again)
{
  mbuffer_st *bufel;
  int ret = 0;

  _gnutls_debug_log ("EXT[%p]: Sending supplemental data\n", session);

  if (again)
    ret =
      _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_SUPPLEMENTAL);
  else
    {
      gnutls_buffer_st buf;
      _gnutls_buffer_init (&buf);

      ret = _gnutls_gen_supplemental (session, &buf);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

      bufel = _gnutls_handshake_alloc(session, buf.length, buf.length);
      if (bufel == NULL)
        {
          gnutls_assert ();
          return GNUTLS_E_MEMORY_ERROR;
        }

      _mbuffer_set_udata (bufel, buf.data, buf.length);
      _gnutls_buffer_clear (&buf);

      ret = _gnutls_send_handshake (session, bufel,
                                    GNUTLS_HANDSHAKE_SUPPLEMENTAL);
    }

  return ret;
}

static int
_gnutls_recv_supplemental (gnutls_session_t session)
{
  gnutls_buffer_st buf;
  int ret;

  _gnutls_debug_log ("EXT[%p]: Expecting supplemental data\n", session);

  ret = _gnutls_recv_handshake (session, GNUTLS_HANDSHAKE_SUPPLEMENTAL,
                                1, &buf);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret = _gnutls_parse_supplemental (session, buf.data, buf.length);
  if (ret < 0)
    {
      gnutls_assert ();
      goto cleanup;
    }

cleanup:
  _gnutls_buffer_clear(&buf);

  return ret;
}

/**
 * gnutls_handshake:
 * @session: is a #gnutls_session_t structure.
 *
 * This function does the handshake of the TLS/SSL protocol, and
 * initializes the TLS connection.
 *
 * This function will fail if any problem is encountered, and will
 * return a negative error code. In case of a client, if the client
 * has asked to resume a session, but the server couldn't, then a
 * full handshake will be performed.
 *
 * The non-fatal errors such as %GNUTLS_E_AGAIN and
 * %GNUTLS_E_INTERRUPTED interrupt the handshake procedure, which
 * should be resumed later.  Call this function again, until it
 * returns 0; cf.  gnutls_record_get_direction() and
 * gnutls_error_is_fatal().
 *
 * If this function is called by a server after a rehandshake request
 * then %GNUTLS_E_GOT_APPLICATION_DATA or
 * %GNUTLS_E_WARNING_ALERT_RECEIVED may be returned.  Note that these
 * are non fatal errors, only in the specific case of a rehandshake.
 * Their meaning is that the client rejected the rehandshake request or
 * in the case of %GNUTLS_E_GOT_APPLICATION_DATA it might also mean that
 * some data were pending.
 *
 * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
 **/
int
gnutls_handshake (gnutls_session_t session)
{
  int ret;
  record_parameters_st *params;
  
  /* sanity check. Verify that there are priorities setup.
   */
  if (session->internals.priorities.protocol.algorithms == 0)
    return gnutls_assert_val(GNUTLS_E_NO_PRIORITIES_WERE_SET);

  if (STATE == STATE0) 
    {
      /* first call */
      gettime(&session->internals.dtls.handshake_start_time);
    }

  if (session->internals.handshake_timeout_ms && 
      session->internals.handshake_endtime == 0)
    session->internals.handshake_endtime = gnutls_time(0) + 
      session->internals.handshake_timeout_ms / 1000;

  ret = _gnutls_epoch_get (session, session->security_parameters.epoch_next,
                           &params);
  if (ret < 0)
    {
      /* We assume the epoch is not allocated if _gnutls_epoch_get fails. */
      ret =
        _gnutls_epoch_alloc (session, session->security_parameters.epoch_next,
                             NULL);
      if (ret < 0)
        return gnutls_assert_val(ret);
    }

  if (session->security_parameters.entity == GNUTLS_CLIENT)
    {
      do
	{
	  ret = _gnutls_handshake_client (session);
	} while (ret == 1);
    }
  else
    {
      ret = _gnutls_handshake_server (session);
    }
  if (ret < 0)
    {
      /* In the case of a rehandshake abort
       * we should reset the handshake's internal state.
       */
      if (_gnutls_abort_handshake (session, ret) == 0)
        STATE = STATE0;

      return ret;
    }

  /* clear handshake buffer */
  _gnutls_handshake_hash_buffers_clear (session);

  if (IS_DTLS(session)==0)
    {
      _gnutls_handshake_io_buffer_clear (session);
    }
  else
    {
      _dtls_async_timer_init(session);
    }

  _gnutls_handshake_internal_state_clear (session);

  session->security_parameters.epoch_next++;

  ret = _gnutls_ext_after_handshake(session);
  if (ret < 0)
    return gnutls_assert_val(ret);

  return 0;
}

/**
 * gnutls_handshake_set_timeout:
 * @session: is a #gnutls_session_t structure.
 * @ms: is a timeout value in milliseconds
 *
 * This function sets the timeout for the handshake process
 * to the provided value. Use an @ms value of zero to disable
 * timeout.
 *
 * Note that in order for the timeout to be enforced
 * gnutls_transport_set_pull_timeout_function() must be set
 * (it is set by default in most systems).
 *
 **/
void
gnutls_handshake_set_timeout (gnutls_session_t session, unsigned int ms)
{
  if (ms == GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT)
    ms = 40*1000;
  session->internals.handshake_timeout_ms = ms;
}


#define IMED_RET( str, ret, allow_alert) do { \
	if (ret < 0) { \
		/* EAGAIN and INTERRUPTED are always non-fatal */ \
		if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) \
			return ret; \
                /* a warning alert might interrupt handshake */ \
		if (allow_alert != 0 && ret==GNUTLS_E_WARNING_ALERT_RECEIVED) return ret; \
		gnutls_assert(); \
		ERR( str, ret); \
		_gnutls_handshake_hash_buffers_clear(session); \
		return ret; \
	} } while (0)


/* Runs the certificate verification callback.
 * side is either GNUTLS_CLIENT or GNUTLS_SERVER.
 */
static int run_verify_callback(gnutls_session_t session, unsigned int side)
{
  gnutls_certificate_credentials_t cred;
  int ret, type;

  cred =
    (gnutls_certificate_credentials_t) _gnutls_get_cred (session,
                                                         GNUTLS_CRD_CERTIFICATE,
                                                         NULL);

  if (side == GNUTLS_CLIENT)
    type = gnutls_auth_server_get_type(session);
  else
    type = gnutls_auth_client_get_type(session);

  if (type != GNUTLS_CRD_CERTIFICATE)
    return 0;

  if (cred != NULL && cred->verify_callback != NULL && 
  	(session->security_parameters.entity == GNUTLS_CLIENT || 
  		session->internals.send_cert_req != GNUTLS_CERT_IGNORE))
    {
      ret = cred->verify_callback (session);
      if (ret < -1)
        return ret;
      else if (ret != 0)
        return GNUTLS_E_CERTIFICATE_ERROR;
    }
  
  return 0;
}

/*
 * _gnutls_handshake_client 
 * This function performs the client side of the handshake of the TLS/SSL protocol.
 */
static int
_gnutls_handshake_client (gnutls_session_t session)
{
  int ret = 0;

#ifdef HANDSHAKE_DEBUG
  char buf[64];

  if (session->internals.resumed_security_parameters.session_id_size > 0)
    _gnutls_handshake_log ("HSK[%p]: Ask to resume: %s\n", session,
                           _gnutls_bin2hex (session->
                                            internals.resumed_security_parameters.session_id,
                                            session->
                                            internals.resumed_security_parameters.session_id_size,
                                            buf, sizeof (buf), NULL));
#endif

  switch (STATE)
    {
    case STATE0:
    case STATE1:
      ret = _gnutls_send_hello (session, AGAIN (STATE1));
      STATE = STATE1;
      IMED_RET ("send hello", ret, 1);

    case STATE2:
      if (IS_DTLS (session))
        {
          ret =
            _gnutls_recv_handshake (session, 
                  GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST,
                  1, NULL);
          STATE = STATE2;
          IMED_RET ("recv hello verify", ret, 1);

          if (ret == 1)
            {
              STATE = STATE0;
              return 1;
            }
        }
    case STATE3:
      /* receive the server hello */
      ret =
        _gnutls_recv_handshake (session,
                                GNUTLS_HANDSHAKE_SERVER_HELLO,
                                0, NULL);
      STATE = STATE3;
      IMED_RET ("recv hello", ret, 1);

    case STATE4:
      if (session->security_parameters.do_recv_supplemental)
        {
          ret = _gnutls_recv_supplemental (session);
          STATE = STATE4;
          IMED_RET ("recv supplemental", ret, 1);
        }

    case STATE5:
      /* RECV CERTIFICATE */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_server_certificate (session);
      STATE = STATE5;
      IMED_RET ("recv server certificate", ret, 1);

    case STATE6:
      /* RECV CERTIFICATE STATUS */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_server_certificate_status (session);
      STATE = STATE6;
      IMED_RET ("recv server certificate", ret, 1);

    case STATE7:
      ret = run_verify_callback(session, GNUTLS_CLIENT);
      STATE = STATE7;
      if (ret < 0)
        return gnutls_assert_val(ret);
    case STATE8:
      /* receive the server key exchange */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_server_kx_message (session);
      STATE = STATE8;
      IMED_RET ("recv server kx message", ret, 1);

    case STATE9:
      /* receive the server certificate request - if any 
       */

      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_server_crt_request (session);
      STATE = STATE9;
      IMED_RET ("recv server certificate request message", ret, 1);

    case STATE10:
      /* receive the server hello done */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret =
          _gnutls_recv_handshake (session,
                                  GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
                                  0, NULL);
      STATE = STATE10;
      IMED_RET ("recv server hello done", ret, 1);

    case STATE11:
      if (session->security_parameters.do_send_supplemental)
        {
          ret = _gnutls_send_supplemental (session, AGAIN (STATE11));
          STATE = STATE11;
          IMED_RET ("send supplemental", ret, 0);
        }

    case STATE12:
      /* send our certificate - if any and if requested
       */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_send_client_certificate (session, AGAIN (STATE12));
      STATE = STATE12;
      IMED_RET ("send client certificate", ret, 0);

    case STATE13:
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_send_client_kx_message (session, AGAIN (STATE13));
      STATE = STATE13;
      IMED_RET ("send client kx", ret, 0);

    case STATE14:
      /* send client certificate verify */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret =
          _gnutls_send_client_certificate_verify (session, AGAIN (STATE14));
      STATE = STATE14;
      IMED_RET ("send client certificate verify", ret, 1);

    case STATE15:
      STATE = STATE15;
      if (session->internals.resumed == RESUME_FALSE)
        {
          ret = _gnutls_send_handshake_final (session, TRUE);
          IMED_RET ("send handshake final 2", ret, 1);
        }
      else
        {
          ret = _gnutls_recv_new_session_ticket (session);
          IMED_RET ("recv handshake new session ticket", ret, 1);
        }

    case STATE16:
      STATE = STATE16;
      if (session->internals.resumed == RESUME_FALSE)
        {
          ret = _gnutls_recv_new_session_ticket (session);
          IMED_RET ("recv handshake new session ticket", ret, 1);
        }
      else
        {
          ret = _gnutls_recv_handshake_final (session, TRUE);
          IMED_RET ("recv handshake final", ret, 1);
        }

    case STATE17:
      STATE = STATE17;
      if (session->internals.resumed == RESUME_FALSE)
        {
          ret = _gnutls_recv_handshake_final (session, FALSE);
          IMED_RET ("recv handshake final 2", ret, 1);
        }
      else
        {
          ret = _gnutls_send_handshake_final (session, FALSE);
          IMED_RET ("send handshake final", ret, 1);
        }

      STATE = STATE0;
    default:
      break;
    }

  return 0;
}



/* This function is to be called if the handshake was successfully 
 * completed. This sends a Change Cipher Spec packet to the peer.
 */
static ssize_t
send_change_cipher_spec (gnutls_session_t session, int again)
{
  uint8_t* data;
  mbuffer_st * bufel;
  int ret;
  
  if (again == 0)
    {
      bufel = _gnutls_handshake_alloc (session, 1, 1);
      if (bufel == NULL)
        return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);

      if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9)
        _mbuffer_set_uhead_size(bufel, 3);
      else
        _mbuffer_set_uhead_size(bufel, 1);
      _mbuffer_set_udata_size(bufel, 0);

      data = _mbuffer_get_uhead_ptr (bufel);
      
      data[0] = 1;
      if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9)
        {
          _gnutls_write_uint16 (session->internals.dtls.hsk_write_seq, &data[1]);
          session->internals.dtls.hsk_write_seq++;
        }

      ret = _gnutls_handshake_io_cache_int (session, GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC, bufel);
      if (ret < 0)
        {
          _mbuffer_xfree(&bufel);
          return gnutls_assert_val(ret);
        }

      _gnutls_handshake_log ("REC[%p]: Sent ChangeCipherSpec\n", session);
    }

    return 0;
}

/* This function sends the final handshake packets and initializes connection 
 */
static int
_gnutls_send_handshake_final (gnutls_session_t session, int init)
{
  int ret = 0;

  /* Send the CHANGE CIPHER SPEC PACKET */

  switch (FINAL_STATE)
    {
    case STATE0:
    case STATE1:
      ret = send_change_cipher_spec (session, FAGAIN (STATE1));
      FINAL_STATE = STATE0;

      if (ret < 0)
        {
          ERR ("send ChangeCipherSpec", ret);
          gnutls_assert ();
          return ret;
        }
      /* Initialize the connection session (start encryption) - in case of client 
       */
      if (init == TRUE)
        {
          ret = _gnutls_connection_state_init (session);
          if (ret < 0)
            {
              gnutls_assert ();
              return ret;
            }
        }

      ret = _gnutls_write_connection_state_init (session);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

    case STATE2:
      /* send the finished message */
      ret = _gnutls_send_finished (session, FAGAIN (STATE2));
      FINAL_STATE = STATE2;
      if (ret < 0)
        {
          ERR ("send Finished", ret);
          gnutls_assert ();
          return ret;
        }

      FINAL_STATE = STATE0;
    default:
      break;
    }

  return 0;
}

/* This function receives the final handshake packets 
 * And executes the appropriate function to initialize the
 * read session.
 */
static int
_gnutls_recv_handshake_final (gnutls_session_t session, int init)
{
  int ret = 0;
  uint8_t ch;
  unsigned int ccs_len = 1;
  unsigned int tleft;
  
  ret = handshake_remaining_time(session);
  if (ret < 0)
    return gnutls_assert_val(ret);
  tleft = ret;

  switch (FINAL_STATE)
    {
    case STATE0:
    case STATE30:
      FINAL_STATE = STATE30;

      /* This is the last flight and peer cannot be sure
       * we have received it unless we notify him. So we
       * wait for a message and retransmit if needed. */
      if (IS_DTLS(session) && !_dtls_is_async(session) && 
          (gnutls_record_check_pending (session) +
          record_check_unprocessed (session)) == 0)
        {
          ret = _dtls_wait_and_retransmit(session);
          if (ret < 0)
            return gnutls_assert_val(ret);
        }

      if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9)
        ccs_len = 3;

      ret = _gnutls_recv_int (session, GNUTLS_CHANGE_CIPHER_SPEC, -1, &ch, ccs_len, NULL, 
                              tleft);
      if (ret <= 0)
        {
          ERR ("recv ChangeCipherSpec", ret);
          gnutls_assert ();
          return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
        }

      if (gnutls_protocol_get_version (session) == GNUTLS_DTLS0_9)
        session->internals.dtls.hsk_read_seq++;

      /* Initialize the connection session (start encryption) - in case of server */
      if (init == TRUE)
        {
          ret = _gnutls_connection_state_init (session);
          if (ret < 0)
            {
              gnutls_assert ();
              return ret;
            }
        }

      ret = _gnutls_read_connection_state_init (session);
      if (ret < 0)
        {
          gnutls_assert ();
          return ret;
        }

    case STATE31:
      FINAL_STATE = STATE31;

       if (IS_DTLS(session) && !_dtls_is_async(session) && 
           (gnutls_record_check_pending( session) +
           record_check_unprocessed (session)) == 0)
         {
           ret = _dtls_wait_and_retransmit(session);
           if (ret < 0)
             return gnutls_assert_val(ret);
         }

      ret = _gnutls_recv_finished (session);
      if (ret < 0)
        {
          ERR ("recv finished", ret);
          gnutls_assert ();
          return ret;
        }
      FINAL_STATE = STATE0;
    default:
      break;
    }


  return 0;
}

/*
 * _gnutls_handshake_server
 * This function does the server stuff of the handshake protocol.
 */
static int
_gnutls_handshake_server (gnutls_session_t session)
{
  int ret = 0;

  switch (STATE)
    {
    case STATE0:
    case STATE1:
      ret =
        _gnutls_recv_handshake (session,
                                GNUTLS_HANDSHAKE_CLIENT_HELLO,
                                0, NULL);
      STATE = STATE1;
      IMED_RET ("recv hello", ret, 1);

    case STATE2:
      ret = _gnutls_send_hello (session, AGAIN (STATE2));
      STATE = STATE2;
      IMED_RET ("send hello", ret, 1);

    case STATE70:
      if (session->security_parameters.do_send_supplemental)
        {
          ret = _gnutls_send_supplemental (session, AGAIN (STATE70));
          STATE = STATE70;
          IMED_RET ("send supplemental data", ret, 0);
        }

      /* SEND CERTIFICATE + KEYEXCHANGE + CERTIFICATE_REQUEST */
    case STATE3:
      /* NOTE: these should not be send if we are resuming */

      if (session->internals.resumed == RESUME_FALSE)
        ret = _gnutls_send_server_certificate (session, AGAIN (STATE3));
      STATE = STATE3;
      IMED_RET ("send server certificate", ret, 0);

    case STATE4:
      if (session->internals.resumed == RESUME_FALSE)
        ret = _gnutls_send_server_certificate_status (session, AGAIN (STATE4));
      STATE = STATE4;
      IMED_RET ("send server certificate status", ret, 0);

    case STATE5:
      /* send server key exchange (A) */
      if (session->internals.resumed == RESUME_FALSE)
        ret = _gnutls_send_server_kx_message (session, AGAIN (STATE5));
      STATE = STATE5;
      IMED_RET ("send server kx", ret, 0);

    case STATE6:
      /* Send certificate request - if requested to */
      if (session->internals.resumed == RESUME_FALSE)
        ret =
          _gnutls_send_server_crt_request (session, AGAIN (STATE6));
      STATE = STATE6;
      IMED_RET ("send server cert request", ret, 0);

    case STATE7:
      /* send the server hello done */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret =
          _gnutls_send_empty_handshake (session,
                                        GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
                                        AGAIN (STATE7));
      STATE = STATE7;
      IMED_RET ("send server hello done", ret, 1);

    case STATE71:
      if (session->security_parameters.do_recv_supplemental)
        {
          ret = _gnutls_recv_supplemental (session);
          STATE = STATE71;
          IMED_RET ("recv client supplemental", ret, 1);
        }

      /* RECV CERTIFICATE + KEYEXCHANGE + CERTIFICATE_VERIFY */
    case STATE8:
      /* receive the client certificate message */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_client_certificate (session);
      STATE = STATE8;
      IMED_RET ("recv client certificate", ret, 1);

    case STATE9:
      ret = run_verify_callback(session, GNUTLS_SERVER);
      STATE = STATE9;
      if (ret < 0)
        return gnutls_assert_val(ret);

    case STATE10:
      /* receive the client key exchange message */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_client_kx_message (session);
      STATE = STATE10;
      IMED_RET ("recv client kx", ret, 1);

    case STATE11:
      /* receive the client certificate verify message */
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        ret = _gnutls_recv_client_certificate_verify_message (session);
      STATE = STATE11;
      IMED_RET ("recv client certificate verify", ret, 1);

    case STATE12:
      STATE = STATE12;
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        {
          ret = _gnutls_recv_handshake_final (session, TRUE);
          IMED_RET ("recv handshake final", ret, 1);
        }
      else
        {
          ret = _gnutls_send_handshake_final (session, TRUE);
          IMED_RET ("send handshake final 2", ret, 1);
        }

    case STATE13:
        ret = _gnutls_send_new_session_ticket (session, AGAIN (STATE13));
        STATE = STATE13;
        IMED_RET ("send handshake new session ticket", ret, 0);

    case STATE14:
      STATE = STATE14;
      if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
        {
          ret = _gnutls_send_handshake_final (session, FALSE);
          IMED_RET ("send handshake final", ret, 1);

          if (session->security_parameters.entity == GNUTLS_SERVER && session->internals.ticket_sent == 0)
            {
              /* if no ticket, save session data */
              _gnutls_server_register_current_session (session);
            }
        }
      else
        {
          ret = _gnutls_recv_handshake_final (session, FALSE);
          IMED_RET ("recv handshake final 2", ret, 1);
        }

      STATE = STATE0;
    default:
      break;
    }
   

  return 0;
}

int
_gnutls_generate_session_id (uint8_t * session_id, uint8_t * len)
{
  int ret;

  *len = TLS_MAX_SESSION_ID_SIZE;

  ret = _gnutls_rnd (GNUTLS_RND_NONCE, session_id, TLS_MAX_SESSION_ID_SIZE);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  return 0;
}

int
_gnutls_recv_hello_request (gnutls_session_t session, void *data,
                            uint32_t data_size)
{
  uint8_t type;

  if (session->security_parameters.entity == GNUTLS_SERVER)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET;
    }
  if (data_size < 1)
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
    }
  type = ((uint8_t *) data)[0];
  if (type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
    {
      if (IS_DTLS(session))
        session->internals.dtls.hsk_read_seq++;
      return GNUTLS_E_REHANDSHAKE;
    }
  else
    {
      gnutls_assert ();
      return GNUTLS_E_UNEXPECTED_PACKET;
    }
}

/* Returns 1 if the given KX has not the corresponding parameters
 * (DH or RSA) set up. Otherwise returns 0.
 */
inline static int
check_server_params (gnutls_session_t session,
                     gnutls_kx_algorithm_t kx,
                     gnutls_kx_algorithm_t * alg, int alg_size)
{
  int cred_type;
  gnutls_dh_params_t dh_params = NULL;
  gnutls_rsa_params_t rsa_params = NULL;
  int j;

  cred_type = _gnutls_map_kx_get_cred (kx, 1);

  /* Read the Diffie-Hellman parameters, if any.
   */
  if (cred_type == GNUTLS_CRD_CERTIFICATE)
    {
      int delete;
      gnutls_certificate_credentials_t x509_cred =
        (gnutls_certificate_credentials_t) _gnutls_get_cred (session,
                                                             cred_type, NULL);

      if (x509_cred != NULL)
        {
          dh_params =
            _gnutls_get_dh_params (x509_cred->dh_params,
                                   x509_cred->params_func, session);
#ifdef ENABLE_RSA_EXPORT
          rsa_params =
            _gnutls_certificate_get_rsa_params (x509_cred->rsa_params,
                                                x509_cred->params_func,
                                                session);
#endif
        }

      /* Check also if the certificate supports the
       * KX method.
       */
      delete = 1;
      for (j = 0; j < alg_size; j++)
        {
          if (alg[j] == kx)
            {
              delete = 0;
              break;
            }
        }

      if (delete == 1)
        return 1;

#ifdef ENABLE_ANON
    }
  else if (cred_type == GNUTLS_CRD_ANON)
    {
      gnutls_anon_server_credentials_t anon_cred =
        (gnutls_anon_server_credentials_t) _gnutls_get_cred (session,
                                                             cred_type, NULL);

      if (anon_cred != NULL)
        {
          dh_params =
            _gnutls_get_dh_params (anon_cred->dh_params,
                                   anon_cred->params_func, session);
        }
#endif
#ifdef ENABLE_PSK
    }
  else if (cred_type == GNUTLS_CRD_PSK)
    {
      gnutls_psk_server_credentials_t psk_cred =
        (gnutls_psk_server_credentials_t) _gnutls_get_cred (session,
                                                            cred_type, NULL);

      if (psk_cred != NULL)
        {
          dh_params =
            _gnutls_get_dh_params (psk_cred->dh_params, psk_cred->params_func,
                                   session);
        }
#endif
    }
  else
    return 0;                   /* no need for params */


#ifdef ENABLE_RSA_EXPORT
  /* If the key exchange method needs RSA or DH params,
   * but they are not set then remove it.
   */
  if (_gnutls_kx_needs_rsa_params (kx) != 0)
    {
      /* needs rsa params. */
      if (_gnutls_rsa_params_to_mpi (rsa_params) == NULL)
        {
          gnutls_assert ();
          return 1;
        }
    }
#endif

  if (_gnutls_kx_needs_dh_params (kx) != 0)
    {
      /* needs DH params. */
      if (_gnutls_dh_params_to_mpi (dh_params) == NULL)
        {
          gnutls_assert ();
          return 1;
        }
    }

  return 0;
}

/* This function will remove algorithms that are not supported by
 * the requested authentication method. We remove an algorithm if
 * we have a certificate with keyUsage bits set.
 *
 * This does a more high level check than  gnutls_supported_ciphersuites(),
 * by checking certificates etc.
 */
static int
_gnutls_remove_unwanted_ciphersuites (gnutls_session_t session,
                                      uint8_t * cipher_suites,
                                      int cipher_suites_size,
                                      gnutls_pk_algorithm_t *pk_algos,
                                      size_t pk_algos_size)
{

  int ret = 0;
  int i, new_suites_size;
  gnutls_certificate_credentials_t cert_cred;
  gnutls_kx_algorithm_t kx;
  int server = session->security_parameters.entity == GNUTLS_SERVER ? 1 : 0;
  gnutls_kx_algorithm_t alg[MAX_ALGOS];
  int alg_size = MAX_ALGOS;

  /* if we should use a specific certificate, 
   * we should remove all algorithms that are not supported
   * by that certificate and are on the same authentication
   * method (CERTIFICATE).
   */
  cert_cred =
    (gnutls_certificate_credentials_t) _gnutls_get_cred (session,
                                                         GNUTLS_CRD_CERTIFICATE,
                                                         NULL);

  /* If there are certificate credentials, find an appropriate certificate
   * or disable them;
   */
  if (session->security_parameters.entity == GNUTLS_SERVER
      && cert_cred != NULL && pk_algos_size > 0)
    {
      ret = _gnutls_server_select_cert (session, pk_algos, pk_algos_size);
      if (ret < 0)
        {
          gnutls_assert ();
          _gnutls_debug_log ("Could not find an appropriate certificate: %s\n",
                             gnutls_strerror (ret));
        }
    }

  /* get all the key exchange algorithms that are 
   * supported by the X509 certificate parameters.
   */
  if ((ret =
       _gnutls_selected_cert_supported_kx (session, alg, &alg_size)) < 0)
    {
      gnutls_assert ();
      return ret;
    }

  new_suites_size = 0;

  /* now removes ciphersuites based on the KX algorithm
   */
  for (i = 0; i < cipher_suites_size; i+=2)
    {
      int delete = 0;

      /* finds the key exchange algorithm in
       * the ciphersuite
       */
      kx = _gnutls_cipher_suite_get_kx_algo (&cipher_suites[i]);

      /* if it is defined but had no credentials 
       */
      if (!session->internals.premaster_set &&
          _gnutls_get_kx_cred (session, kx, NULL) == NULL)
        {
          delete = 1;
        }
      else
        {
          delete = 0;

          if (server)
            delete = check_server_params (session, kx, alg, alg_size);
        }
       
      /* If we have not agreed to a common curve with the peer don't bother
       * negotiating ECDH.
       */
      if (server != 0 && _gnutls_kx_is_ecc(kx))
        {
          if (_gnutls_session_ecc_curve_get(session) == GNUTLS_ECC_CURVE_INVALID)
            {
              delete = 1;
            }
        }

      /* These two SRP kx's are marked to require a CRD_CERTIFICATE,
         (see cred_mappings in gnutls_algorithms.c), but it also
         requires a SRP credential.  Don't use SRP kx unless we have a
         SRP credential too.  */
      if (kx == GNUTLS_KX_SRP_RSA || kx == GNUTLS_KX_SRP_DSS)
        {
          if (!_gnutls_get_cred (session, GNUTLS_CRD_SRP, NULL))
            {
              delete = 1;
            }
        }

      if (delete == 0)
        {

          _gnutls_handshake_log ("HSK[%p]: Keeping ciphersuite: %s (%.2X.%.2X)\n",
                                 session,
                                 _gnutls_cipher_suite_get_name (&cipher_suites[i]),
                                 cipher_suites[i], cipher_suites[i+1]);

          if (i != new_suites_size)
            memmove( &cipher_suites[new_suites_size], &cipher_suites[i], 2);
          new_suites_size+=2;
        }
      else
        {
          _gnutls_handshake_log ("HSK[%p]: Removing ciphersuite: %s\n",
                                 session,
                                 _gnutls_cipher_suite_get_name (&cipher_suites[i]));

        }
    }

  ret = new_suites_size;

  return ret;

}

/**
 * gnutls_handshake_set_max_packet_length:
 * @session: is a #gnutls_session_t structure.
 * @max: is the maximum number.
 *
 * This function will set the maximum size of all handshake messages.
 * Handshakes over this size are rejected with
 * %GNUTLS_E_HANDSHAKE_TOO_LARGE error code.  The default value is
 * 48kb which is typically large enough.  Set this to 0 if you do not
 * want to set an upper limit.
 *
 * The reason for restricting the handshake message sizes are to
 * limit Denial of Service attacks.
 **/
void
gnutls_handshake_set_max_packet_length (gnutls_session_t session, size_t max)
{
  session->internals.max_handshake_data_buffer_size = max;
}

void
_gnutls_set_adv_version (gnutls_session_t session, gnutls_protocol_t ver)
{
  set_adv_version (session, _gnutls_version_get_major (ver),
                   _gnutls_version_get_minor (ver));
}

gnutls_protocol_t
_gnutls_get_adv_version (gnutls_session_t session)
{
  return _gnutls_version_get (_gnutls_get_adv_version_major (session),
                              _gnutls_get_adv_version_minor (session));
}

/**
 * gnutls_handshake_get_last_in:
 * @session: is a #gnutls_session_t structure.
 *
 * This function is only useful to check where the last performed
 * handshake failed.  If the previous handshake succeed or was not
 * performed at all then no meaningful value will be returned.
 *
 * Check %gnutls_handshake_description_t in gnutls.h for the
 * available handshake descriptions.
 *
 * Returns: the last handshake message type received, a
 * %gnutls_handshake_description_t.
 **/
gnutls_handshake_description_t
gnutls_handshake_get_last_in (gnutls_session_t session)
{
  return session->internals.last_handshake_in;
}

/**
 * gnutls_handshake_get_last_out:
 * @session: is a #gnutls_session_t structure.
 *
 * This function is only useful to check where the last performed
 * handshake failed.  If the previous handshake succeed or was not
 * performed at all then no meaningful value will be returned.
 *
 * Check %gnutls_handshake_description_t in gnutls.h for the
 * available handshake descriptions.
 *
 * Returns: the last handshake message type sent, a
 * %gnutls_handshake_description_t.
 **/
gnutls_handshake_description_t
gnutls_handshake_get_last_out (gnutls_session_t session)
{
  return session->internals.last_handshake_out;
}