summaryrefslogtreecommitdiff
path: root/appl/lib/crypt/ssl3.b
blob: 918198517138b2ca049b2020d17417e4f47a05da (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
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
#
# SSL 3.0 protocol 
#
implement SSL3;

include "sys.m";				
	sys					: Sys;

include "keyring.m";				
	keyring					: Keyring;
	IPint, DigestState			: import keyring;

include "security.m";				
	random					: Random;
	ssl					: SSL;

include "daytime.m";				
	daytime					: Daytime;

include "asn1.m";
	asn1					: ASN1;

include "pkcs.m";
	pkcs					: PKCS;
	DHParams, DHPublicKey, DHPrivateKey, 
	RSAParams, RSAKey, 
	DSSPrivateKey, DSSPublicKey		: import PKCS;

include "x509.m";
	x509					: X509;
	Signed,	Certificate, SubjectPKInfo	: import x509;

include "sslsession.m";
	sslsession				: SSLsession;
	Session					: import sslsession;

include "ssl3.m";

#
# debug mode
#
SSL_DEBUG					: con 0;
logfd						: ref Sys->FD;

#
# version {major, minor}
#
SSL_VERSION_2_0					:= array [] of {byte 0, byte 16r02};
SSL_VERSION_3_0					:= array [] of {byte 16r03, byte 0};


# SSL Record Protocol

SSL_CHANGE_CIPHER_SPEC 				: con 20;
	SSL_ALERT				: con 21;
	SSL_HANDSHAKE 				: con 22;
	SSL_APPLICATION_DATA 			: con 23;
	SSL_V2HANDSHAKE				: con 0; # escape to sslv2

# SSL Application Protocol consists of alert protocol, change cipher spec protocol
# v2 and v3 handshake protocol and application data protocol. The v2 handshake
# protocol is included only for backward compatibility

Protocol: adt {
	pick {
	pAlert =>
		alert				: ref Alert;
	pChangeCipherSpec =>
		change_cipher_spec		: ref ChangeCipherSpec;
	pHandshake =>
		handshake			: ref Handshake;
	pV2Handshake =>
		handshake			: ref V2Handshake;
	pApplicationData =>
		data				: array of byte;
	}

	decode: fn(r: ref Record, ctx: ref Context): (ref Protocol, string);
	encode: fn(p: self ref Protocol, vers: array of byte): (ref Record, string);
	tostring: fn(p: self ref Protocol): string;
};

#
# ssl alert protocol
#
SSL_WARNING	 				: con 1; 
	SSL_FATAL				: con 2;

SSL_CLOSE_NOTIFY				: con 0;
	SSL_UNEXPECTED_MESSAGE			: con 10;
	SSL_BAD_RECORD_MAC			: con 20;
	SSL_DECOMPRESSION_FAILURE		: con 30;
	SSL_HANDSHAKE_FAILURE 			: con 40;
	SSL_NO_CERTIFICATE			: con 41;
	SSL_BAD_CERTIFICATE 			: con 42;
	SSL_UNSUPPORTED_CERTIFICATE 		: con 43;
	SSL_CERTIFICATE_REVOKED			: con 44;
	SSL_CERTIFICATE_EXPIRED			: con 45;
	SSL_CERTIFICATE_UNKNOWN			: con 46;
	SSL_ILLEGAL_PARAMETER 			: con 47;

Alert: adt {
	level 					: int; 
	description 				: int;
	
	tostring: fn(a: self ref Alert): string;
};

#
# ssl change cipher spec protocol
#
ChangeCipherSpec: adt {
	value					: int;
};

#
# ssl handshake protocol
#
SSL_HANDSHAKE_HELLO_REQUEST	 		: con 0; 
	SSL_HANDSHAKE_CLIENT_HELLO 		: con 1; 
	SSL_HANDSHAKE_SERVER_HELLO 		: con 2;
	SSL_HANDSHAKE_CERTIFICATE 		: con 11;
	SSL_HANDSHAKE_SERVER_KEY_EXCHANGE 	: con 12;
	SSL_HANDSHAKE_CERTIFICATE_REQUEST 	: con 13; 
	SSL_HANDSHAKE_SERVER_HELLO_DONE 	: con 14;
	SSL_HANDSHAKE_CERTIFICATE_VERIFY 	: con 15; 
	SSL_HANDSHAKE_CLIENT_KEY_EXCHANGE 	: con 16;
	SSL_HANDSHAKE_FINISHED	 		: con 20; 

Handshake: adt {
	pick {
       	HelloRequest =>				
        ClientHello =>
		version 			: array of byte; # [2]
		random 				: array of byte; # [32]
		session_id 			: array of byte; # <0..32>
		suites	 			: array of byte; # [2] x
		compressions			: array of byte; # [1] x
        ServerHello =>
		version 			: array of byte; # [2]
		random 				: array of byte; # [32]
		session_id 			: array of byte; # <0..32>
		suite	 			: array of byte; # [2]
		compression			: byte; # [1]
	Certificate =>
		cert_list 			: list of array of byte; # X509 cert chain
	ServerKeyExchange =>
		xkey				: array of byte; # exchange_keys
        CertificateRequest =>
		cert_types 			: array of byte;
		dn_list 			: list of array of byte; # DN list
	ServerHelloDone =>
        CertificateVerify =>
		signature			: array of byte;
        ClientKeyExchange =>
		xkey				: array of byte;
       	Finished =>
		md5_hash			: array of byte; # [16] Keyring->MD5dlen
		sha_hash 			: array of byte; # [20] Keyring->SHA1dlen
	}

	decode: fn(buf: array of byte): (ref Handshake, string);
	encode: fn(hm: self ref Handshake): (array of byte, string);
	tostring: fn(hm: self ref Handshake): string;
};

# cipher suites and cipher specs (default, not all supported)
#	- key exchange, signature, encrypt and digest algorithms

SSL3_Suites := array [] of {
	NULL_WITH_NULL_NULL => 			array [] of {byte 0, byte 16r00},

	RSA_WITH_NULL_MD5 => 			array [] of {byte 0, byte 16r01},
	RSA_WITH_NULL_SHA => 			array [] of {byte 0, byte 16r02},
	RSA_EXPORT_WITH_RC4_40_MD5 => 		array [] of {byte 0, byte 16r03},
	RSA_WITH_RC4_128_MD5 => 		array [] of {byte 0, byte 16r04},
	RSA_WITH_RC4_128_SHA => 		array [] of {byte 0, byte 16r05},
	RSA_EXPORT_WITH_RC2_CBC_40_MD5 => 	array [] of {byte 0, byte 16r06},
	RSA_WITH_IDEA_CBC_SHA => 		array [] of {byte 0, byte 16r07},
	RSA_EXPORT_WITH_DES40_CBC_SHA => 	array [] of {byte 0, byte 16r08},
	RSA_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r09},
	RSA_WITH_3DES_EDE_CBC_SHA => 		array [] of {byte 0, byte 16r0A},

	DH_DSS_EXPORT_WITH_DES40_CBC_SHA => 	array [] of {byte 0, byte 16r0B},
	DH_DSS_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r0C},
	DH_DSS_WITH_3DES_EDE_CBC_SHA => 	array [] of {byte 0, byte 16r0D},
	DH_RSA_EXPORT_WITH_DES40_CBC_SHA => 	array [] of {byte 0, byte 16r0E},
	DH_RSA_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r0F},
	DH_RSA_WITH_3DES_EDE_CBC_SHA => 	array [] of {byte 0, byte 16r10},
	DHE_DSS_EXPORT_WITH_DES40_CBC_SHA =>	array [] of {byte 0, byte 16r11},
	DHE_DSS_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r12},
	DHE_DSS_WITH_3DES_EDE_CBC_SHA => 	array [] of {byte 0, byte 16r13},
	DHE_RSA_EXPORT_WITH_DES40_CBC_SHA =>	array [] of {byte 0, byte 16r14},
	DHE_RSA_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r15},
	DHE_RSA_WITH_3DES_EDE_CBC_SHA => 	array [] of {byte 0, byte 16r16},

	DH_anon_EXPORT_WITH_RC4_40_MD5 => 	array [] of {byte 0, byte 16r17},
	DH_anon_WITH_RC4_128_MD5 => 		array [] of {byte 0, byte 16r18},
	DH_anon_EXPORT_WITH_DES40_CBC_SHA =>	array [] of {byte 0, byte 16r19},
	DH_anon_WITH_DES_CBC_SHA => 		array [] of {byte 0, byte 16r1A},
	DH_anon_WITH_3DES_EDE_CBC_SHA => 	array [] of {byte 0, byte 16r1B},

	FORTEZZA_KEA_WITH_NULL_SHA => 		array [] of {byte 0, byte 16r1C},
	FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA =>	array [] of {byte 0, byte 16r1D},
	FORTEZZA_KEA_WITH_RC4_128_SHA => 	array [] of {byte 0, byte 16r1E},
};

#
# key exchange algorithms
#
DHmodlen					: con 512; # default length


#
# certificate types
#
SSL_RSA_sign 					: con 1;
	SSL_DSS_sign 				: con 2;
	SSL_RSA_fixed_DH			: con 3;
	SSL_DSS_fixed_DH			: con 4;
	SSL_RSA_emhemeral_DH 			: con 5;
	SSL_DSS_empemeral_DH 			: con 6;
	SSL_FORTEZZA_MISSI			: con 20;

#
# cipher definitions
#
SSL_EXPORT_TRUE 				: con 0;
	SSL_EXPORT_FALSE 			: con 1;

SSL_NULL_CIPHER,
	SSL_RC4,
	SSL_RC2_CBC,
	SSL_IDEA_CBC,
	SSL_DES_CBC,
	SSL_3DES_EDE_CBC,
	SSL_FORTEZZA_CBC			: con iota;

SSL_STREAM_CIPHER,
	SSL_BLOCK_CIPHER			: con iota;

SSL_NULL_MAC,
	SSL_MD5,
	SSL_SHA					: con iota;

#
# MAC paddings
#
SSL_MAX_MAC_PADDING 				: con 48;
SSL_MAC_PAD1 := array [] of { 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
	byte 16r36, byte 16r36, byte 16r36, byte 16r36, 
	byte 16r36, byte 16r36, byte 16r36, byte 16r36,
};
SSL_MAC_PAD2 := array [] of {
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
	byte 16r5c, byte 16r5c, byte 16r5c, byte 16r5c,
};

#
# finished messages
#
SSL_CLIENT_SENDER := array [] of {
	byte 16r43, byte 16r4C, byte 16r4E, byte 16r54};
SSL_SERVER_SENDER := array [] of {
	byte 16r53, byte 16r52, byte 16r56, byte 16r52};

#
# a default distiguished names
#
RSA_COMMERCIAL_CA_ROOT_SUBJECT_NAME := array [] of {   
	byte 16r30, byte 16r5F, byte 16r31, byte 16r0B, 
	byte 16r30, byte 16r09, byte 16r06, byte 16r03, 
	byte 16r55, byte 16r04, byte 16r06, byte 16r13, 
	byte 16r02, byte 16r55, byte 16r53, byte 16r31, 
	byte 16r20, byte 16r30, byte 16r1E, byte 16r06, 
	byte 16r03, byte 16r55, byte 16r04, byte 16r0A, 
	byte 16r13, byte 16r17, byte 16r52, byte 16r53, 
	byte 16r41, byte 16r20, byte 16r44, byte 16r61, 
	byte 16r74, byte 16r61, byte 16r20, byte 16r53, 
	byte 16r65, byte 16r63, byte 16r75, byte 16r72, 
	byte 16r69, byte 16r74, byte 16r79, byte 16r2C, 
	byte 16r20, byte 16r49, byte 16r6E, byte 16r63, 
	byte 16r2E, byte 16r31, byte 16r2E, byte 16r30, 
	byte 16r2C, byte 16r06, byte 16r03, byte 16r55, 
	byte 16r04, byte 16r0B, byte 16r13, byte 16r25, 
	byte 16r53, byte 16r65, byte 16r63, byte 16r75, 
	byte 16r72, byte 16r65, byte 16r20, byte 16r53, 
	byte 16r65, byte 16r72, byte 16r76, byte 16r65, 
	byte 16r72, byte 16r20, byte 16r43, byte 16r65, 
	byte 16r72, byte 16r74, byte 16r69, byte 16r66, 
	byte 16r69, byte 16r63, byte 16r61, byte 16r74, 
	byte 16r69, byte 16r6F, byte 16r6E, byte 16r20, 
	byte 16r41, byte 16r75, byte 16r74, byte 16r68, 
	byte 16r6F, byte 16r72, byte 16r69, byte 16r74, 
	byte 16r79,
};

# SSL internal status
USE_DEVSSL,
	SSL3_RECORD,
	SSL3_HANDSHAKE,
	SSL2_HANDSHAKE,
	CLIENT_SIDE, 				
	SESSION_RESUMABLE,
	CLIENT_AUTH,
	CERT_REQUEST,
	CERT_SENT,
	CERT_RECEIVED,
	OUT_READY,
	IN_READY				: con  1 << iota;

# SSL internal state
STATE_EXIT,
	STATE_CHANGE_CIPHER_SPEC,
	STATE_HELLO_REQUEST,
	STATE_CLIENT_HELLO,
	STATE_SERVER_HELLO,
	STATE_CLIENT_KEY_EXCHANGE,
	STATE_SERVER_KEY_EXCHANGE,
	STATE_SERVER_HELLO_DONE,
	STATE_CLIENT_CERTIFICATE,
	STATE_SERVER_CERTIFICATE,
	STATE_CERTIFICATE_VERIFY,
	STATE_FINISHED				: con iota;

#
# load necessary modules
#
init(): string
{
	sys = load Sys Sys->PATH;
	if(sys == nil)
		return "ssl3: load sys module failed";
	logfd = sys->fildes(1);

	keyring = load Keyring Keyring->PATH;
	if(keyring == nil)
		return "ssl3: load keyring module failed";

	random = load Random Random->PATH;
	if(random == nil)
		return "ssl3: load random module failed";

	daytime = load Daytime Daytime->PATH;
	if(daytime == nil)
		return "ssl3: load Daytime module failed";

	pkcs = load PKCS PKCS->PATH;
	if(pkcs == nil)
		return "ssl3: load pkcs module failed";
	pkcs->init();

	x509 = load X509 X509->PATH;
	if(x509 == nil)
		return "ssl3: load x509 module failed";
	x509->init();

	ssl = load SSL SSL->PATH;
	if(ssl == nil)
		return "ssl3: load SSL module failed";
	sslsession = load SSLsession SSLsession->PATH;
	if(sslsession == nil)
		return "ssl3: load sslsession module failed";
	e := sslsession->init();
	if(e != nil)
		return "ssl3: sslsession init failed: "+e;

	return "";
}

log(s: string)
{
	a := array of byte (s + "\n");
	sys->write(logfd, a, len a);
}

#
# protocol context
#

Context.new(): ref Context
{
	ctx := ref Context;

	ctx.c = nil;
	ctx.session = nil;
	ctx.local_info = nil;
		
	ctx.sha_state = nil;
	ctx.md5_state = nil;

	ctx.status = 0;
	ctx.state = 0;

	ctx.client_random = array [32] of byte;
	ctx.server_random = array [32] of byte;

	ctx.cw_mac = nil;
	ctx.sw_mac = nil;
	ctx.cw_key = nil;
	ctx.sw_key = nil;
	ctx.cw_IV = nil;
	ctx.sw_IV = nil;

	ctx.in_queue = RecordQueue.new();
	ctx.in_queue.data = ref Record(0, nil, array [1<<15] of byte) :: nil;
	ctx.out_queue = RecordQueue.new();

	# set session resumable as default
	ctx.status |= SESSION_RESUMABLE;

	return ctx;
}

Context.client(ctx: self ref Context, fd: ref Sys->FD, peername: string, ver: int, info: ref Authinfo)
	: (string, int)
{
	if(SSL_DEBUG)
		log(sys->sprint("ssl3: Context.Client peername=%s ver=%d\n", peername, ver));
	if ((ckstr := cksuites(info.suites)) != nil)
		return (ckstr, ver);
	# the order is important
	ctx.local_info = info;
	ctx.state = STATE_HELLO_REQUEST;
	e := ctx.connect(fd);
	if(e != "")
		return (e, ver);
	ctx.session = sslsession->get_session_byname(peername);

	# Request to resume an SSL 3.0 session should use an SSL 3.0 client hello
	if(ctx.session.session_id != nil) {
		if((ctx.session.version[0] == SSL_VERSION_3_0[0]) &&
			(ctx.session.version[1] == SSL_VERSION_3_0[1])) {
			ver = 3;
			ctx.status |= SSL3_HANDSHAKE;
			ctx.status &= ~SSL2_HANDSHAKE;
		}
	}
	e = ctx.set_version(ver);
	if(e != "")
		return (e, ver);
	reset_client_random(ctx);
	ctx.status |= CLIENT_SIDE;
	e = do_protocol(ctx);
	if(e != nil)
		return (e, ver);

	if(ctx.status & SSL3_RECORD)
		ver = 3;
	else
		ver = 2;
	return (nil, ver);
}

Context.server(ctx: self ref Context, fd: ref Sys->FD, info: ref Authinfo, client_auth: int)
	: string
{
	if ((ckstr := cksuites(info.suites)) != nil)
		return ckstr;
	ctx.local_info = info;
	if(client_auth)
		ctx.status |= CLIENT_AUTH;
	ctx.state = STATE_CLIENT_HELLO;
	e := ctx.connect(fd);
	if(e != "")
		return e;
	reset_server_random(ctx);
	e = ctx.set_version(3); # set ssl device to version 3
	if(e != "")
		return e;
	ctx.status &= ~CLIENT_SIDE;
	e = do_protocol(ctx);
	if(e != nil)
		return e;

	return "";
}


Context.use_devssl(ctx: self ref Context)
{
	if(!(ctx.status & IN_READY) && !(ctx.status & OUT_READY))
		ctx.status |= USE_DEVSSL;
}

Context.set_version(ctx: self ref Context, vers: int): string
{
	err := "";

	if(ctx.c == nil) {
		err = "no connection provided";
	}
	else {
		if(SSL_DEBUG)
			log("ssl3: record version = " + string vers);

		if(vers == 2) {
			ctx.status &= ~SSL3_RECORD;
			ctx.status &= ~SSL3_HANDSHAKE;
			ctx.status |= SSL2_HANDSHAKE;
			if (ctx.session != nil)
				ctx.session.version = SSL_VERSION_2_0;
		}
		else if(vers == 3) { # may be sslv2 handshake using ssl3 record
			ctx.status |= SSL3_RECORD;
			ctx.status |= SSL3_HANDSHAKE;
			ctx.status &= ~SSL2_HANDSHAKE; # tmp test only
			if (ctx.session != nil)
				ctx.session.version = SSL_VERSION_3_0;
		}
		else if(vers == 23) { # may be sslv2 handshake using ssl3 record
			ctx.status &= ~SSL3_RECORD;
			ctx.status |= SSL3_HANDSHAKE;
			ctx.status |= SSL2_HANDSHAKE;
			vers = 2;
		}
		else
			err = "unsupported ssl device version";

		if((err == "") && (ctx.status & USE_DEVSSL)) {
			if(sys->fprint(ctx.c.cfd, "ver %d", vers) < 0)
				err = sys->sprint("ssl3: set ssl device version failed: %r");
		}
	}

	return err;
}

Context.connect(ctx: self ref Context, fd: ref Sys->FD): string
{
	err := "";

	if(ctx.status & USE_DEVSSL)
		(err, ctx.c) = ssl->connect(fd);
	else {
		ctx.c = ref Sys->Connection(fd, nil, "");
		ctx.in_queue.sequence_numbers[0] = 0;
		ctx.out_queue.sequence_numbers[1] = 0;
	}

	return err;
}

Context.read(ctx: self ref Context, a: array of byte, n: int): int
{	
	if(ctx.state != STATE_EXIT || !(ctx.status & IN_READY)) {
		if(SSL_DEBUG)
			log("ssl3: read not ready\n");
		return -1;
	}

	if(ctx.out_queue.data != nil)
		record_write_queue(ctx);

	if(ctx.status & USE_DEVSSL) {
		fd := ctx.c.dfd;
		if(ctx.status & SSL3_RECORD) {
			buf := array [n+3] of byte;
			m := sys->read(fd, buf, n+3); # header + n bytes
			if(m < 3) {
				if(SSL_DEBUG)
					log(sys->sprint("ssl3: read failure: %r"));
				return -1;
			}

			if(buf[1] != SSL_VERSION_3_0[0] || buf[2] != SSL_VERSION_3_0[1]) {
				if(SSL_DEBUG)
					log("ssl3: not ssl version 3 data: header = [" + bastr(buf[0:3]) + "]");
				return -1;
			}

			a[0:] = buf[3:m];

			content_type := int buf[0];
			case content_type {
			SSL_APPLICATION_DATA =>
				break;
			SSL_ALERT =>				
				if(SSL_DEBUG)
					log("ssl3: expect application data, got alert: [" + bastr(buf[3:m]) +"]");
				return 0;
			SSL_HANDSHAKE =>
				if(SSL_DEBUG)
					log("ssl3: expect application data, got handshake message");
				return 0;
			SSL_CHANGE_CIPHER_SPEC =>
				if(SSL_DEBUG)
					log("ssl3: dynamic change cipher spec not supported yet");
				return 0;
			}
			return m-3;
		}
		else
			return sys->read(fd, a, n);
	}
	else {
		q := ctx.in_queue;
		got := 0;
		if(q.fragment) {
			d := (hd q.data).data;
			m := q.e - q.b;
			i := q.e - q.fragment;
			if(q.fragment > n) {
				a[0:] = d[i:i+n];
				q.fragment -= n;
				got = n;
			}
			else {
				a[0:] = d[i:q.e];
				got = q.fragment;
				q.fragment = 0;
			}
		}
out:
		while(got < n) {
			err := q.read(ctx, ctx.c.dfd);
			if(err != "") {	
				if(SSL_DEBUG)
					log("ssl3: read: " + err);
				break;
			}
			r := hd q.data;
			if(ctx.status & SSL3_RECORD) {
				case r.content_type {
				SSL_APPLICATION_DATA =>
					break;
				SSL_ALERT =>
					if(SSL_DEBUG)
						log("ssl3: read: got alert\n\t\t" + bastr(r.data[q.b:q.e]));
					# delete session id
					ctx.session.session_id = nil;
					ctx.status &= ~IN_READY;
					break out;
				SSL_CHANGE_CIPHER_SPEC =>
					if(SSL_DEBUG)
						log("ssl3: read: got change cipher spec\n");
				SSL_HANDSHAKE =>
					if(SSL_DEBUG)
						log("ssl3: read: got handshake data\n");
					#do_handshake(ctx, r); # ?
				* =>
					if(SSL_DEBUG)
						log("ssl3: read: unknown data\n");
				}
			}

			if((n - got) <= (q.e - q.b)) {
				a[got:] = r.data[q.b:q.b+n-got];
				q.fragment = q.e - q.b - n + got;
				got = n;
			}
			else {
				a[got:] = r.data[q.b:q.e];
				q.fragment = 0;
				got += q.e - q.b;
			}
		}
		if(SSL_DEBUG)
			log(sys->sprint("ssl3: read: returning %d bytes\n", got));
		return got;
	}
}

Context.write(ctx: self ref Context, a: array of byte, n: int): int
{	
	if(ctx.state != STATE_EXIT || !(ctx.status & OUT_READY))
		return-1;

	if(ctx.out_queue.data != nil)
		record_write_queue(ctx);

	if(ctx.status & USE_DEVSSL) {
		if(ctx.status & SSL3_RECORD) {
			buf := array [n+3] of byte;
			buf[0] = byte SSL_APPLICATION_DATA;
			buf[1:] = SSL_VERSION_3_0;
			buf[3:] = a[0:n];
			n = sys->write(ctx.c.dfd, buf, n+3);
			if(n > 0)
				n -= 3;
		}
		else
			n = sys->write(ctx.c.dfd, a, n);
	}
	else {
		q := ctx.out_queue;
		v := SSL_VERSION_2_0;
		if(ctx.status&SSL3_RECORD)
			v = SSL_VERSION_3_0;
		for(i := 0; i < n;){
			m := n-i;
			if(m > q.length)
				m = q.length;
			r := ref Record(SSL_APPLICATION_DATA, v, a[i:i+m]);
			record_write(r, ctx); # return error?		
			i += m;
		}
	}
	return n;
}

devssl_read(ctx: ref Context): (ref Record, string)
{
	buf := array [Sys->ATOMICIO] of byte;
	r: ref Record;
	c := ctx.c;

	n := sys->read(c.dfd, buf, 3);
	if(n < 0)
		return (nil, sys->sprint("record read: read failure: %r")); 

	# in case of undetermined, do auto record version detection
	if((ctx.state == SSL2_STATE_SERVER_HELLO) &&
		(ctx.status & SSL2_HANDSHAKE) && (ctx.status & SSL3_HANDSHAKE)) {

		fstatus := sys->open(ctx.c.dir + "/status", Sys->OREAD);
		if(fstatus == nil)
			return (nil, "open status: " + sys->sprint("%r"));
		status := array [64] of byte;
		nbyte := sys->read(fstatus, status, len status);
		if(nbyte != 1)
			return (nil, "read status: " + sys->sprint("%r"));

		ver := int status[0];

		if(SSL_DEBUG)
			log("ssl3: auto record version detect as: " + string ver); 

		# assert ctx.status & SSL2_RECORD true ? before reset
		if(ver == 2) {
			ctx.status &= ~SSL3_RECORD;
			ctx.status |= SSL2_HANDSHAKE;
			ctx.status &= ~SSL3_HANDSHAKE;
		}
		else { 
			ctx.status |= SSL3_RECORD;
		}
	}

	if(ctx.status & SSL3_RECORD) {
		if(n < 3)
			return (nil, sys->sprint("record read: read failure: %r")); 

		# assert only major version number
		if(buf[1] != SSL_VERSION_3_0[0])
			return (nil, "record read: version mismatch");

		case int buf[0] {
		SSL_ALERT =>
			n = sys->read(c.dfd, buf, 5); # read in header plus rest
			if(n != 5)
				return (nil, sys->sprint("read alert failed: %r"));
			r = ref Record(SSL_ALERT, SSL_VERSION_3_0, buf[3:5]);

		SSL_CHANGE_CIPHER_SPEC =>
			n = sys->read(c.dfd, buf, 4); # read in header plus rest
			if(n != 4)
				return (nil, sys->sprint("read change_cipher_spec failed: %r"));
			r = ref Record(SSL_CHANGE_CIPHER_SPEC, SSL_VERSION_3_0, buf[3:4]);

		SSL_HANDSHAKE =>
			n = sys->read(c.dfd, buf, 7); # header + msg length
			if(n != 7)
				return (nil, sys->sprint("read handshake header + msg length failed: %r"));
			m := int_decode(buf[4:7]);
			if(m < 0)
				return (nil, "read handshake failed: unexpected length");
			data := array [m+4] of byte;
			data[0:] = buf[3:7]; # msg type + length
			if(m != 0) {
				# need exact m bytes (exclude header), otherwise failure
				remain := m;
				now := 4;
				while(remain > 0) {
					n = sys->read(c.dfd, buf, remain+3); # header + msg
					if(n < 3 || int buf[0] != SSL_HANDSHAKE)
						return (nil, sys->sprint("read handshake msg body failed: %r"));
					sys->print("expect %d, got %d bytes\n", m, n-3);
					remain -= n - 3;
					data[now:] = buf[3:n];
					now += n - 3;
				}
			}

			r = ref Record(SSL_HANDSHAKE, SSL_VERSION_3_0, data);
		* =>
			return (nil, "trying to read unknown protocol message");
		}

		if(SSL_DEBUG)
			log("ssl3: record_read: \n\theader = \n\t\t" + bastr(buf[0:3])
			+ "\n\tdata = \n\t\t" + bastr(r.data) + "\n");
	}
	# v2 record layer
	else {
		# assume the handshake record size less than Sys->ATOMICIO
		# in most case, this is ok
		if(n == 3) {
			n = sys->read(c.dfd, buf[3:], Sys->ATOMICIO - 3);
			if(n < 0)
				return (nil, sys->sprint("v2 record read: read failure: %r")); 
		}

		r = ref Record(SSL_V2HANDSHAKE, SSL_VERSION_2_0, buf[0:n+3]);

		if(SSL_DEBUG)
			log("ssl3: v2 record_read: \n\tdata = \n\t\t" + bastr(r.data) + "\n");
	}

	return (r, nil);
}

record_read(ctx: ref Context): (ref Record, string) 
{
	q := ctx.in_queue;
	if(q.fragment == 0) {
		err := q.read(ctx, ctx.c.dfd);
		if(err != "")
			return (nil, err);
		q.fragment = q.e - q.b;
	}

	r := hd q.data;
	if(ctx.status & SSL3_RECORD) {
		# confirm only major version number
		if(r.version[0] != SSL_VERSION_3_0[0])
			return (nil, "record read: not v3 record");

		case r.content_type {
		SSL_ALERT =>
			a := array [2] of byte;
			n := fetch_data(ctx, a, 2);
			if(n != 2)
				return (nil, "read alert failed");
			r = ref Record(SSL_ALERT, SSL_VERSION_3_0, a);

		SSL_CHANGE_CIPHER_SPEC =>
			a := array [1] of byte;
			n := fetch_data(ctx, a, 1);
			if(n != 1)
				return (nil, "read change_cipher_spec failed");
			r = ref Record(SSL_CHANGE_CIPHER_SPEC, SSL_VERSION_3_0, a);

		SSL_HANDSHAKE =>
			a := array [4] of byte;
			n := fetch_data(ctx, a, 4);
			if(n != 4)
				return (nil, "read message length failed");
			m := int_decode(a[1:]);
			if(m < 0)
				return (nil, "unexpected handshake message length");
			b := array [m+4] of byte;
			b[0:] = a;
			n = fetch_data(ctx, b[4:], m);
			if(n != m)
				return (nil, "read message body failed");
			r = ref Record(SSL_HANDSHAKE, SSL_VERSION_3_0, b);
		* =>
			return (nil, "trying to read unknown protocol message");
		}
	}
	# v2 record layer
	else {
		r = ref Record(SSL_V2HANDSHAKE, SSL_VERSION_2_0, r.data[q.b:q.e]);
		q.fragment = 0;
	}

	return (r, nil);
}

fetch_data(ctx: ref Context, a: array of byte, n: int): int
{
	q := ctx.in_queue;
	r := hd q.data;

	got := 0;
	cnt := -1;
out:
	while(got < n) {
		if(q.fragment) {
			cnt = r.content_type;
			i := q.e - q.fragment;			
			if(n-got <= q.fragment) {
				a[got:] = r.data[i:i+n-got];
				q.fragment -= n - got;
				got = n;
			}
			else {
				a[got:] = r.data[i:q.e];
				got += q.fragment;
				q.fragment = 0;
			}
		}
		else {
			err := q.read(ctx, ctx.c.dfd);
			if(err != "") 
				break out;
			if(cnt == -1)
				cnt = r.content_type;
			if(ctx.status & SSL3_RECORD) {
				case r.content_type {
				SSL_APPLICATION_DATA =>
					break;
				* =>
					if(cnt != r.content_type)
						break out;
				}
			}
			else {
				r.content_type = SSL_V2HANDSHAKE;
			}
		}
	}
	return got;
}

record_write(r: ref Record, ctx: ref Context)
{
	if(ctx.status & USE_DEVSSL) {
		buf: array of byte;
		n: int;
		c := ctx.c;

		if(ctx.status & SSL3_RECORD) {
			buf = array [3 + len r.data] of byte;
			buf[0] = byte r.content_type;
			buf[1:] = r.version; 
			buf[3:] = r.data;
			n = sys->write(c.dfd, buf, len buf);
			if(n < 0 || n != len buf) {
				if(SSL_DEBUG)
					log(sys->sprint("ssl3: v3 record write error: %d %r", n));
				return; # don't terminated until alerts being read
			}
		}
		else {
			buf = r.data;
			n = sys->write(c.dfd, buf, len buf);
			if(n < 0 || n != len buf) {
				if(SSL_DEBUG)
					log(sys->sprint("ssl3: v2 record write error: %d %r", n));
				return; # don't terminated until alerts being read
			}
		}
	}
	else 
		ctx.out_queue.write(ctx, ctx.c.dfd, r);
	
	# if(SSL_DEBUG) 
	#	log("ssl3: record_write: \n\t\t" + bastr(buf) + "\n");	
}

RecordQueue.new(): ref RecordQueue
{
	q := ref RecordQueue(
		ref MacState.null(0),
		ref CipherState.null(1),
		1 << 15,
		array [2] of { * => 0},
		nil,
		0,
		0, # b 
		0  # e	
	);
	return q;
}

RecordQueue.read(q: self ref RecordQueue, ctx: ref Context, fd: ref Sys->FD): string
{
	r := hd q.data;
	a := r.data;
	if(ensure(fd, a, 2) < 0)
		return "no more data";
	# auto record version detection
	m, h, pad: int = 0;
	if(int a[0] < 20 || int a[0] > 23) {
		ctx.status &= ~SSL3_RECORD;
		if(int a[0] & 16r80) {
			h = 2;
			m = ((int a[0] & 16r7f) << 8) | int a[1];
			pad = 0;
		} else {
			h = 3;
			m = ((int a[0] & 16r3f) << 8) | int a[1];
			if(ensure(fd, a[2:], 1) < 0)
				return "bad v2 record";
			pad = int a[2];
			if(pad > m)
				return "bad v2 pad";
		}
		r.content_type = SSL_V2HANDSHAKE;
		r.version = SSL_VERSION_2_0;
	}
	else {
		ctx.status |= SSL3_RECORD;
		h = 5;
		if(ensure(fd, a[2:], 3) < 0)
			return "bad v3 record";
		m = ((int a[3]) << 8) | int a[4];
		r.content_type = int a[0];
		r.version = a[1:3];
	}
	if(ensure(fd, a[h:], m) < 0)
#		return "data too short";
		return sys->sprint("data too short wanted %d", m);
	if(SSL_DEBUG) {
		log("ssl3: record read\n\tbefore decrypt\n\t\t" + bastr(a[0:m+h]));
		log(sys->sprint("SSL3=%d\n", ctx.status & SSL3_RECORD));
	}

	# decrypt (data, pad, mac)
	pick dec := q.cipherState {
	null =>
	rc4 =>
		keyring->rc4(dec.es, a[h:], m);
		if (SSL_DEBUG) log("rc4 1");
	descbc =>
		keyring->descbc(dec.es, a[h:], m, 1);
		if (SSL_DEBUG) log("descbc 1");
	ideacbc =>
		keyring->ideacbc(dec.es, a[h:], m, 1);
		if (SSL_DEBUG) log("ideacbc 1");
	* =>
	}

	if(SSL_DEBUG)
		log("ssl3: record read\n\tafter decrypt\n\t\t" + bastr(a[0:m]));

	idata, imac, ipad: int = 0;
	if(ctx.status & SSL3_RECORD) {
		if(q.cipherState.block_size > 1){
			pad = int a[h + m - 1];
			if(pad >= q.cipherState.block_size)
				return "bad v3 pad";
			# pad++;
			ipad = h+m-pad-1;
		}
		else
			ipad = h+m-pad;
		imac = ipad - q.macState.hash_size;
		idata = h;
	}
	else {
		imac = h;
		idata = imac + q.macState.hash_size;
		ipad = h + m - pad;
	}
	if(tagof q.macState != tagof MacState.null) {
		if (ctx.status & SSL3_RECORD)
			mac := q.calcmac(ctx, r.content_type, a, idata, imac-idata);
		else
			mac = q.calcmac(ctx, r.content_type, a, idata, ipad+pad-idata);
		if(bytes_cmp(mac, a[imac:imac+len mac]) < 0)
			return "bad mac";
	}
	q.b = idata;
	if (ctx.status & SSL3_RECORD)
		q.e = imac;
	else
		q.e = ipad;
	q.fragment = q.e - q.b;

	if((++q.sequence_numbers[0] == 0) && (ctx.status&SSL3_RECORD))
		++q.sequence_numbers[1];

	return "";
}

ensure(fd: ref Sys->FD, a: array of byte, n: int): int
{
	i, m: int = 0;
	while(i < n) {
		m = sys->read(fd, a[i:], n - i);
		if(m <= 0) {
			return -1;
		}
		i += m;
	}
	return n;
}

RecordQueue.write(q: self ref RecordQueue, ctx: ref Context, fd: ref Sys->FD, 
	r: ref Record): string
{
	m := len r.data;
	h, pad: int = 0;
	if(ctx.status & SSL3_RECORD) {
		h = 5;
		if(q.cipherState.block_size > 1) {
			pad = (m+q.macState.hash_size+1)%q.cipherState.block_size;
			if (pad)
				pad = q.cipherState.block_size - pad;
		}
	}
	else {
		h = 2;
		if(q.cipherState.block_size > 1) {
			pad = m%q.cipherState.block_size;
			if(pad) {
				pad = q.cipherState.block_size - pad;
				h++;
			}
		}
	}

	m += pad + q.macState.hash_size;
	if ((ctx.status & SSL3_RECORD) && q.cipherState.block_size > 1)
		m++;
	a := array [h+m] of byte;

	idata, imac, ipad: int = 0;
	if(ctx.status & SSL3_RECORD) {
		a[0] = byte r.content_type;
		a[1:] = r.version;
		a[3] = byte (m >> 8);			#CJL - netscape ssl3 traces do not show top bit set
#		a[3] = byte ((m >> 8) | 16r80);	#CJL
#		a[3] = byte (m | 16r8000) >> 8;
		a[4] = byte m;
		idata = h;
		imac = idata + len r.data;
		ipad = imac + q.macState.hash_size;
		if (q.cipherState.block_size > 1)
			a[h+m-1] = byte pad;
	}
	else {
		if(pad) {
			a[0] = byte m >> 8;
			a[2] = byte pad;
		}
		else
			a[0] = byte ((m >> 8) | 16r80);
		a[1] = byte m;
		imac = h;
		idata = imac + q.macState.hash_size;
		ipad = idata + len r.data;
	}
	a[idata:] = r.data;
	if(pad)
		a[ipad:] = array [pad] of { * => byte (pad-1)};

	if(tagof q.macState != tagof MacState.null) {
		if (ctx.status & SSL3_RECORD)
			a[imac:] = q.calcmac(ctx, r.content_type, a, idata, len r.data);
		else
			a[imac:] = q.calcmac(ctx, r.content_type, a, idata, ipad+pad-idata);
	}

	 if(SSL_DEBUG) {
		log("ssl3: record write\n\tbefore encrypt\n\t\t" + bastr(a));	
		log(sys->sprint("SSL3=%d\n", ctx.status & SSL3_RECORD));
	}

	# encrypt (data, pad, mac)
	pick enc := q.cipherState {
	null =>
	rc4 =>
		keyring->rc4(enc.es, a[h:], m);
		if (SSL_DEBUG) log("rc4 0");
	descbc =>
		keyring->descbc(enc.es, a[h:], m, 0);
		if (SSL_DEBUG) log(sys->sprint("descbc 0 %d", m));
	ideacbc =>
		keyring->ideacbc(enc.es, a[h:], m, 0);
		if (SSL_DEBUG) log(sys->sprint("ideacbc 0 %d", m));
	* =>
	}

	 if(SSL_DEBUG)
		log("ssl3: record write\n\tafter encrypt\n\t\t" + bastr(a));

	if(sys->write(fd, a, h+m) < 0)
		return sys->sprint("ssl3: record write: %r");

	if((++q.sequence_numbers[0] == 0) && (ctx.status&SSL3_RECORD))
		++q.sequence_numbers[1];

	return "";
}

RecordQueue.calcmac(q: self ref RecordQueue, ctx: ref Context, cntype: int, a: array of byte, 
	ofs, n: int) : array of byte
{
	digest, b: array of byte;

	if(ctx.status & SSL3_RECORD) {
		b = array [11] of byte;
		i := putn(b, 0, q.sequence_numbers[1], 4);
		i = putn(b, i, q.sequence_numbers[0], 4);
		b[i++] = byte cntype;
		putn(b, i, n, 2);
	}
	else {
		b = array [4] of byte;
		putn(b, 0, q.sequence_numbers[0], 4);
	}

	# if(SSL_DEBUG)
	#	log("ssl3: record mac\n\tother =\n\t\t" + bastr(b));

	pick ms := q.macState {
	md5 =>
		digest = array [Keyring->MD5dlen] of byte;
		ds0 := ms.ds[0].copy();
		if(ctx.status & SSL3_RECORD) {
			keyring->md5(b, len b, nil, ds0);
			keyring->md5(a[ofs:], n, digest, ds0);
			ds1 := ms.ds[1].copy();
			keyring->md5(digest, len digest, digest, ds1);
		}
		else {
			keyring->md5(a[ofs:], n, nil, ds0);
			keyring->md5(b, len b, digest, ds0);
		}
	sha =>
		digest = array [Keyring->SHA1dlen] of byte;
		ds0 := ms.ds[0].copy();
		if(ctx.status & SSL3_RECORD) {
			keyring->sha1(b, len b, nil, ds0);
			keyring->sha1(a[ofs:], n, digest, ds0);
			ds1 := ms.ds[1].copy();
			keyring->sha1(digest, len digest, digest, ds1);
		}
		else {
			keyring->sha1(a[ofs:], n, nil, ds0);
			keyring->sha1(b, len b, digest, ds0);
		}
	}			
	return digest;
}

set_queues(ctx: ref Context): string
{
	sw: array of byte;
	if(ctx.sw_key != nil) {
		sw = array [len ctx.sw_key + len ctx.sw_IV] of byte;
		sw[0:] = ctx.sw_key;
		sw[len ctx.sw_key:] = ctx.sw_IV;
	}
	cw: array of byte;
	if(ctx.cw_key != nil) {
		cw = array [len ctx.cw_key + len ctx.cw_IV] of byte;
		cw[0:] = ctx.cw_key;
		cw[len ctx.cw_key:] = ctx.cw_IV;
	}

	err := "";
	if(ctx.status & USE_DEVSSL) {
		err = set_secrets(ctx.c, ctx.sw_mac, ctx.cw_mac, sw, cw);
		if(err == "")
			err = set_cipher_algs(ctx);
	}
	else {
		err = set_out_queue(ctx);
		if(err == "")
			err = set_in_queue(ctx);
	}

	return err;
}

set_in_queue(ctx: ref Context): string
{
	sw: array of byte;
	if(ctx.sw_key != nil) {
		sw = array [len ctx.sw_key + len ctx.sw_IV] of byte;
		sw[0:] = ctx.sw_key;
		sw[len ctx.sw_key:] = ctx.sw_IV;
	}

	err := "";
	if(ctx.status & USE_DEVSSL) {
		err = set_secrets(ctx.c, ctx.sw_mac, nil, sw, nil);
		if(err == "")
			err = set_cipher_algs(ctx);
	}
	else
		err = set_queue(ctx, ctx.in_queue, ctx.sw_mac, sw);

	return err;
}

set_out_queue(ctx: ref Context): string
{
	cw: array of byte;
	if(ctx.cw_key != nil) {
		cw = array [len ctx.cw_key + len ctx.cw_IV] of byte;
		cw[0:] = ctx.cw_key;
		cw[len ctx.cw_key:] = ctx.cw_IV;
	}

	err := "";
	if(ctx.status & USE_DEVSSL) {
		err = set_secrets(ctx.c, nil, ctx.cw_mac, nil, cw);
		if(err == "")
			err = set_cipher_algs(ctx);
	}
	else
		err = set_queue(ctx, ctx.out_queue, ctx.cw_mac, cw);

	return err;
}

set_queue(ctx: ref Context, q: ref RecordQueue, mac, key: array of byte): string
{
	e := "";

	case ctx.sel_ciph.mac_algorithm {
	SSL_NULL_MAC =>
		q.macState = ref MacState.null(0);
	SSL_MD5 =>
		ds: array of ref DigestState;
		if(ctx.status & SSL3_RECORD) {
			ds = array [2] of ref DigestState;
			ds[0] = keyring->md5(mac, len mac, nil, nil);
			ds[1] = keyring->md5(mac, len mac, nil, nil);
			ds[0] = keyring->md5(SSL_MAC_PAD1, 48, nil, ds[0]);
			ds[1] = keyring->md5(SSL_MAC_PAD2, 48, nil, ds[1]);
		}
		else {
			ds = array [1] of ref DigestState;
			ds[0] = keyring->md5(mac, len mac, nil, nil);
		}
		q.macState = ref MacState.md5(Keyring->MD5dlen, ds);
	SSL_SHA =>
		ds: array of ref DigestState;
		if(ctx.status & SSL3_RECORD) {
			ds = array [2] of ref DigestState;
			ds[0] = keyring->sha1(mac, len mac, nil, nil);
			ds[1] = keyring->sha1(mac, len mac, nil, nil);
			ds[0] = keyring->sha1(SSL_MAC_PAD1, 40, nil, ds[0]);
			ds[1] = keyring->sha1(SSL_MAC_PAD2, 40, nil, ds[1]);
		}
		else {
			ds = array [1] of ref DigestState;
			ds[0] = keyring->sha1(mac, len mac, nil, nil);
		}
		q.macState = ref MacState.sha(Keyring->SHA1dlen, ds);
	* =>
		e = "ssl3: digest method: unknown";
	}

	case ctx.sel_ciph.bulk_cipher_algorithm {
	SSL_NULL_CIPHER =>
		q.cipherState = ref CipherState.null(1);
	SSL_RC4 =>
		if (SSL_DEBUG) log("rc4setup");
		rcs := keyring->rc4setup(key);
		q.cipherState = ref CipherState.rc4(1, rcs);
	SSL_DES_CBC =>
		dcs : ref keyring->DESstate;

		if (SSL_DEBUG) log(sys->sprint("dessetup %d", len key));
		if (len key >= 16)
			dcs = keyring->dessetup(key[0:8], key[8:16]);
		else if (len key >= 8)
			dcs = keyring->dessetup(key[0:8], nil);
		else
			e = "ssl3: bad DES key length";
		q.cipherState = ref CipherState.descbc(8, dcs);
	SSL_IDEA_CBC =>
		ics : ref keyring->IDEAstate;

		if (SSL_DEBUG) log(sys->sprint("ideasetup %d", len key));
		if (len key >= 24)
			ics = keyring->ideasetup(key[0:16], key[16:24]);
		else if (len key >= 16)
			ics = keyring->ideasetup(key[0:16], nil);
		else
			e = "ssl3: bad IDEA key length";
		q.cipherState = ref CipherState.ideacbc(8, ics);
	SSL_RC2_CBC or
	SSL_3DES_EDE_CBC or
	SSL_FORTEZZA_CBC =>
		e = "ssl3: unsupported cipher";
	* =>
		e = "ssl3: unknown cipher";
	}

	if(ctx.status & SSL3_RECORD) {
		q.length = 1 << 14;
		if(tagof q.macState != tagof MacState.null)
			q.length += 2048;
	}
	else {
		if(q.cipherState.block_size > 1) {
			q.length = (1<<14) - q.macState.hash_size - 1;
			q.length -= q.length % q.cipherState.block_size;
		}
		else
			q.length = (1<<15) - q.macState.hash_size - 1;
	}
	if(ctx.status & SSL3_RECORD)
		q.sequence_numbers[0] = q.sequence_numbers[1] = 0;

	return e;
}

set_cipher_algs(ctx: ref Context) : string
{
	e: string;

	algspec := "alg";

	case enc := ctx.sel_ciph.bulk_cipher_algorithm {
	SSL_NULL_CIPHER =>
		algspec += " clear";
	SSL_RC4 => 	# stream cipher
		algspec += " rc4_128";
	SSL_DES_CBC => # block cipher
		algspec += " descbc";
	SSL_IDEA_CBC => # block cipher
		algspec += " ideacbc";
	SSL_RC2_CBC or
	SSL_3DES_EDE_CBC or
	SSL_FORTEZZA_CBC =>
		e = "ssl3: encrypt method: unsupported";
	* =>
		e = "ssl3: encrypt method: unknown";
	}

	case mac := ctx.sel_ciph.mac_algorithm {
	SSL_NULL_MAC =>
		algspec += " clear";
	SSL_MD5 =>
		algspec += " md5";
	SSL_SHA =>
		algspec += " sha1";
	* =>
		e = "ssl3: digest method: unknown";
	}

	e = set_ctl(ctx.c, algspec);
	if(e != "") {
		if(SSL_DEBUG)
			log("failed to set cipher algs: " + e);
	}

	return e;
}

set_ctl(c: ref Sys->Connection, s: string): string
{
	a := array of byte s;
	if(sys->write(c.cfd, a, len a) < 0)
		return sys->sprint("error writing sslctl: %r");

	if(SSL_DEBUG)
		log("ssl3: set cipher algorithm:\n\t\t" + s + "\n");

	return "";
}

set_secrets(c: ref Sys->Connection, min, mout, sin, sout: array of byte) : string
{
	fmin := sys->open(c.dir + "/macin", Sys->OWRITE);
	fmout := sys->open(c.dir + "/macout", Sys->OWRITE);
	fsin := sys->open(c.dir + "/secretin", Sys->OWRITE);
	fsout := sys->open(c.dir + "/secretout", Sys->OWRITE);
	if(fmin == nil || fmout == nil || fsin == nil || fsout == nil)
		return sys->sprint("can't open ssl secret files: %r\n");

	if(sin != nil) {
		if(SSL_DEBUG)
			log("ssl3: set encryption secret and IV\n\tsecretin:\n\t\t" + bastr(sin) + "\n");
		if(sys->write(fsin, sin, len sin) < 0)
			return sys->sprint("error writing secretin: %r");
	}
	if(sout != nil) {
		if(SSL_DEBUG)
			log("ssl3: set encryption secret and IV\n\tsecretout:\n\t\t" + bastr(sout) + "\n");
		if(sys->write(fsout, sout, len sout) < 0)
			return sys->sprint("error writing secretout: %r");
	}
	if(min != nil) {
		if(SSL_DEBUG)
			log("ssl3: set digest secret\n\tmacin:\n\t\t" + bastr(min) + "\n");
		if(sys->write(fmin, min, len min) < 0)
			return sys->sprint("error writing macin: %r");
	}
	if(mout != nil) {
		if(SSL_DEBUG)
			log("ssl3: set digest secret\n\tmacout:\n\t\t" + bastr(mout) + "\n");
		if(sys->write(fmout, mout, len mout) < 0)
			return sys->sprint("error writing macout: %r");
	}

	return "";
}

#
# description must be alert description
#
fatal(description: int, debug_msg: string, ctx: ref Context)
{
	if(SSL_DEBUG)
		log("ssl3: " + debug_msg);

	# TODO: use V2Handshake.Error for v2
	alert_enque(ref Alert(SSL_FATAL, description), ctx);

	# delete session id
	ctx.session.session_id = nil;

	ctx.state = STATE_EXIT;
}

alert_enque(a: ref Alert, ctx: ref Context)
{
	p := ref Protocol.pAlert(a);

	protocol_write(p, ctx);
}

# clean up out queue before switch cipher. this is why
# change cipher spec differs from handshake message by ssl spec

ccs_enque(cs: ref ChangeCipherSpec, ctx: ref Context)
{
	p := ref Protocol.pChangeCipherSpec(cs);

	protocol_write(p, ctx);

	record_write_queue(ctx);
	ctx.out_queue.data = nil;
}

handshake_enque(h: ref Handshake, ctx: ref Context)
{
	p := ref Protocol.pHandshake(h);

	protocol_write(p, ctx);
}

protocol_write(p: ref Protocol, ctx: ref Context)
{
	record_version := SSL_VERSION_2_0;
	if(ctx.status & SSL3_RECORD)
		record_version = SSL_VERSION_3_0;
	(r, e) := p.encode(record_version);
	if(e != "") {
		if(SSL_DEBUG)
			log("ssl3: protocol_write: " + e);
		exit;
	}

	# Note: only for sslv3
	if((ctx.status&SSL2_HANDSHAKE) && (ctx.status&SSL3_HANDSHAKE)) {
		if(ctx.state == STATE_HELLO_REQUEST) {
			e = update_handshake_hash(ctx, r);
			if(e != "") {
				if(SSL_DEBUG)
					log("ssl3: protocol_write: " + e);
				exit;
			}
		}
	}
	if((ctx.status&SSL3_HANDSHAKE) && (r.content_type == SSL_HANDSHAKE)) {
		e = update_handshake_hash(ctx, r);
		if(e != "") {
			if(SSL_DEBUG)
				log("ssl3: protocol_write: " + e);
			exit;
		}
	}

	ctx.out_queue.data = r :: ctx.out_queue.data;
}

#feed_data(ctx: ref Context, a: array of byte, n: int): int 
#{
#
#}

# FIFO
record_write_queue(ctx: ref Context)
{
	write_queue : list of ref Record;

	wq := ctx.out_queue.data;
	while(wq != nil) {
		write_queue = hd wq :: write_queue;
		wq = tl wq;
	}

	wq = write_queue;
	while(wq != nil) {
		record_write(hd wq, ctx);
		wq = tl wq;
	}
}

# Possible combinations are v2 only, v3 only and both (undetermined). The v2 only must be 
# v2 handshake and v2 record layer. The v3 only must be v3 handshake and v3 record layer. 
# If both v2 and v3 are supported, it may be v2 handshake and v2 record layer, or v3 
# handshake and v3 record layer, or v2 handshake and v3 record layer. In the case of 
# both, the client should send a v2 client hello message with handshake protocol version v3. 

do_protocol(ctx: ref Context): string
{
	r: ref Record;
	in: ref Protocol;
	e: string = nil;

	while(ctx.state != STATE_EXIT) {

		if(SSL_DEBUG)
			log("ssl3: state = " + state_info(ctx));

		# init a new handshake
		if(ctx.state == STATE_HELLO_REQUEST) {
			# v2 and v3
			if((ctx.status&SSL2_HANDSHAKE) && (ctx.status&SSL3_HANDSHAKE)) {
				ch := ref V2Handshake.ClientHello(
						SSL_VERSION_3_0,
						v3tov2specs(ctx.local_info.suites),
						ctx.session.session_id,
						ctx.client_random
					);
				v2handshake_enque(ch, ctx);
				in = ref Protocol.pV2Handshake(ch);
			}
			# v3 only
			else if(ctx.status&SSL3_HANDSHAKE) {
				in = ref Protocol.pHandshake(ref Handshake.HelloRequest());
			}
			# v2 only
			else if(ctx.status&SSL2_HANDSHAKE) {		
				ch := ref V2Handshake.ClientHello(
						SSL_VERSION_2_0,
						v3tov2specs(ctx.local_info.suites),
						ctx.session.session_id,
						ctx.client_random[32-SSL2_CHALLENGE_LENGTH:32]
					);
				v2handshake_enque(ch, ctx);
				in = ref Protocol.pV2Handshake(ch);
			}
			# unknown version
			else {
				e = "unknown ssl device version";
				fatal(SSL_CLOSE_NOTIFY, "ssl3: " + e, ctx);
				continue;
			}
		}

		if(in == nil) {
			(r, in, e) = protocol_read(ctx);
			if(e != "") {
				fatal(SSL_CLOSE_NOTIFY, "ssl3: " + e, ctx);
				continue;
			}
			if(SSL_DEBUG)
				log("ssl3: protocol_read: ------\n" + in.tostring());
		}

		pick p := in {	
		pAlert =>
			do_alert(p.alert, ctx);

		pChangeCipherSpec =>
			if(ctx.state != STATE_CHANGE_CIPHER_SPEC) {
				e += "ChangeCipherSpec";
				break;
			}
			do_change_cipher_spec(ctx);

		pHandshake =>
			if(!(ctx.status & SSL3_HANDSHAKE)) {
				e = "Wrong Handshake";
				break;
			}
			if((ctx.status & SSL3_RECORD) && 
				(ctx.state == SSL2_STATE_SERVER_HELLO)) {
				ctx.state = STATE_SERVER_HELLO;
				ctx.status &= ~SSL2_HANDSHAKE;
			}
			e = do_handshake(p.handshake, ctx);

		pV2Handshake =>
			if(ctx.state != STATE_HELLO_REQUEST) {
				if(!(ctx.status & SSL2_HANDSHAKE)) {
					e = "Wrong Handshake";
					break;
				}
				e = do_v2handshake(p.handshake, ctx);
			}
			else
				ctx.state = SSL2_STATE_SERVER_HELLO;


		* =>
			e = "unknown protocol message";
		}

		if(e != nil) {
			e = "do_protocol: wrong protocol side or protocol message: " + e;
			fatal(SSL_UNEXPECTED_MESSAGE, e, ctx);
		}

		in = nil;

		record_write_queue(ctx);
		ctx.out_queue.data = nil;
	}

	return e;
}

state_info(ctx: ref Context): string
{
	info: string;

	if(ctx.status & SSL3_RECORD)
		info = "\n\tRecord Version 3: ";
	else
		info = "\n\tRecord Version 2: ";

	if(ctx.status & SSL2_HANDSHAKE) {

		if(ctx.status & SSL3_HANDSHAKE) {
			info += "\n\tHandshake Version Undetermined: Client Hello";
		}
		else {
			info += "\n\tHandshake Version 2: ";

			case ctx.state {
			SSL2_STATE_CLIENT_HELLO =>
				info += "Client Hello";
			SSL2_STATE_SERVER_HELLO =>
				info += "Server Hello";
			SSL2_STATE_CLIENT_MASTER_KEY =>
				info += "Client Master Key";
			SSL2_STATE_SERVER_VERIFY =>
				info += "Server Verify";
			SSL2_STATE_REQUEST_CERTIFICATE =>
				info += "Request Certificate";
			SSL2_STATE_CLIENT_CERTIFICATE =>
				info += "Client Certificate";
			SSL2_STATE_CLIENT_FINISHED =>
				info += "Client Finished";
			SSL2_STATE_SERVER_FINISHED =>		
				info += "Server Finished";
			SSL2_STATE_ERROR =>
				info += "Error";
			}
		}
	}
	else {
		info = "\n\tHandshake Version 3: ";

		case ctx.state {
		STATE_EXIT =>
			info += "Exit";

		STATE_CHANGE_CIPHER_SPEC =>
			info += "Change Cipher Spec";

		STATE_HELLO_REQUEST =>
			info += "Hello Request";

		STATE_CLIENT_HELLO =>
			info += "Client Hello";	

		STATE_SERVER_HELLO =>
			info += "Server Hello";

		STATE_CLIENT_KEY_EXCHANGE =>
			info += "Client Key Exchange";

		STATE_SERVER_KEY_EXCHANGE =>
			info += "Server Key Exchange";

		STATE_SERVER_HELLO_DONE =>
			info += "Server Hello Done";

		STATE_CLIENT_CERTIFICATE =>
			info += "Client Certificate";

		STATE_SERVER_CERTIFICATE =>
			info += "Server Certificate";

		STATE_CERTIFICATE_VERIFY =>
			info += "Certificate Verify";

		STATE_FINISHED =>
			info += "Finished";
		}
	}

	if(ctx.status & CLIENT_AUTH)
		info += ": Client Auth";
	if(ctx.status & CERT_REQUEST)
		info += ": Cert Request";
	if(ctx.status & CERT_SENT)
		info += ": Cert Sent";
	if(ctx.status & CERT_RECEIVED)
		info += ": Cert Received";

	return info;
}

reset_client_random(ctx: ref Context)
{
	ctx.client_random[0:] = int_encode(ctx.session.connection_time, 4);
	ctx.client_random[4:] = random->randombuf(Random->NotQuiteRandom, 28);
}

reset_server_random(ctx: ref Context)
{
	ctx.server_random[0:] = int_encode(ctx.session.connection_time, 4);
	ctx.server_random[4:] = random->randombuf(Random->NotQuiteRandom, 28);
}

update_handshake_hash(ctx: ref Context, r: ref Record): string
{
	err := "";

	ctx.sha_state = keyring->sha1(r.data, len r.data, nil, ctx.sha_state);
	ctx.md5_state = keyring->md5(r.data, len r.data, nil, ctx.md5_state);
	if(ctx.sha_state == nil || ctx.md5_state == nil)
		err = "update handshake hash failed";

	# if(SSL_DEBUG)
	#	log("ssl3: update_handshake_hash\n\tmessage_data =\n\t\t" + bastr(r.data) + "\n");

	return err;
}

# Note:
#	this depends on the record protocol
protocol_read(ctx: ref Context): (ref Record, ref Protocol, string)
{
	p: ref Protocol;
	r: ref Record;
	e: string;

	vers := SSL_VERSION_2_0;
	if(ctx.status & SSL3_RECORD)
		vers = SSL_VERSION_3_0;
	if(ctx.status & USE_DEVSSL)
		(r, e) = devssl_read(ctx);
	else
		(r, e) = record_read(ctx);
	if(e != "")
		return (nil, nil, e);

	(p, e) = Protocol.decode(r, ctx);
	if(e != "")
		return (r, nil, e);

	return (r, p, nil);
}

# Alert messages with a level of fatal result in the immediate 
# termination of the connection and zero out session.

do_alert(a: ref Alert, ctx: ref Context)
{
	case a.level {
	SSL_FATAL =>

		case a.description {
		SSL_UNEXPECTED_MESSAGE =>

			# should never be observed in communication  
			# between proper implementations.
			break;

		SSL_HANDSHAKE_FAILURE =>

			# unable to negotiate an acceptable set of security
			# parameters given the options available. 
			break;

		* =>
			break;
		}

		ctx.session.session_id = nil;
		ctx.state = STATE_EXIT;

	SSL_WARNING =>

		case a.description {
		SSL_CLOSE_NOTIFY =>

			if(SSL_DEBUG)
				log("ssl3: do_alert SSL_WARNING:SSL_CLOSE_NOTIFY\n");
			# notifies the recipient that the sender will not 
			# send any more messages on this connection.

			ctx.state = STATE_EXIT;
			fatal(SSL_CLOSE_NOTIFY, "ssl3: response close notify", ctx);

		SSL_NO_CERTIFICATE =>

			# A no_certificate alert message may be sent in
			# response to a certification request if no
			# appropriate certificate is available.

			if(ctx.state == STATE_CLIENT_CERTIFICATE) {
				hm := ref Handshake.Certificate(ctx.local_info.certs);
				handshake_enque(hm, ctx);
			}

		SSL_BAD_CERTIFICATE or 

			# A certificate was corrupt, contained signatures
			# that did not verify correctly, etc.

		SSL_UNSUPPORTED_CERTIFICATE or 	

			# A certificate was of an unsupported type.

		SSL_CERTIFICATE_REVOKED or

			# A certificate was revoked by its signer. 	

		SSL_CERTIFICATE_EXPIRED or

			# A certificate has expired or is not currently
			# valid.	

		SSL_CERTIFICATE_UNKNOWN =>

			# Some other (unspecified) issue arose in
			# processing the certificate, rendering it
			# unacceptable.
			break;

		* =>
			ctx.session.session_id = nil;
			fatal(SSL_ILLEGAL_PARAMETER, "ssl3: unknown alert description", ctx);
		}

	* =>
		ctx.session.session_id = nil;
		fatal(SSL_ILLEGAL_PARAMETER, "ssl3: unknown alert level received", ctx);
	}
}

# notify the receiving party that subsequent records will
# be protected under the just-negotiated CipherSpec and keys.

do_change_cipher_spec(ctx: ref Context)
{
	# calculate and set new keys
	if(!(ctx.status & IN_READY)) {
		e := set_in_queue(ctx);
		if(e != "") {
			fatal(SSL_CLOSE_NOTIFY, "do_change_cipher_spec: setup new cipher failed", ctx);
			return;
		}
		ctx.status |= IN_READY;

		if(SSL_DEBUG)
			log("ssl3: set in cipher done\n");
	}

	ctx.state = STATE_FINISHED;
}


# process and advance handshake messages, update internal stack and switch to next 
# expected state(s).

do_handshake(handshake: ref Handshake, ctx: ref Context) : string
{
	e := "";
	
	pick h := handshake {
	HelloRequest =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != STATE_HELLO_REQUEST) {
			e = "HelloRequest";
			break;
		}
		do_hello_request(ctx);

	ClientHello =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != STATE_CLIENT_HELLO) {
			e = "ClientHello";
			break;
		}
		do_client_hello(h, ctx);

	ServerHello =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != STATE_SERVER_HELLO) {
			e = "ServerHello";
			break;
		}
		do_server_hello(h, ctx);

	ClientKeyExchange =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != STATE_CLIENT_KEY_EXCHANGE) {
			e = "ClientKeyExchange";
			break;
		}
		do_client_keyex(h, ctx);

	ServerKeyExchange =>
		if(!(ctx.status & CLIENT_SIDE) || 
			(ctx.state != STATE_SERVER_KEY_EXCHANGE && ctx.state != STATE_SERVER_HELLO_DONE)) {
			e = "ServerKeyExchange";
			break;
		}
		do_server_keyex(h, ctx);

	ServerHelloDone =>
		# diff from SSLRef, to support variant impl
		if(!(ctx.status & CLIENT_SIDE) || 
			(ctx.state != STATE_SERVER_HELLO_DONE && ctx.state != STATE_SERVER_KEY_EXCHANGE)) {
			e = "ServerHelloDone";
			break;
		}
		do_server_done(ctx);

	Certificate =>
		if(ctx.status & CLIENT_SIDE) {
			if(ctx.state != STATE_SERVER_CERTIFICATE) {
				e = "ServerCertificate";
				break;
			}
			do_server_cert(h, ctx);
		}
		else {
			if(ctx.state != STATE_CLIENT_CERTIFICATE) {
				e = "ClientCertificate";
				break;
			}
			do_client_cert(h, ctx); # server_side
		}

	CertificateRequest =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != STATE_SERVER_HELLO_DONE
			|| ctx.state != STATE_SERVER_KEY_EXCHANGE) {
			e = "CertificateRequest";
			break;
		}
		do_cert_request(h, ctx);

	CertificateVerify =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != STATE_CERTIFICATE_VERIFY) {
			e = "CertificateVerify";
			break;
		}
		do_cert_verify(h, ctx);

	Finished =>
		if(ctx.status & CLIENT_SIDE) {
			if(ctx.state != STATE_FINISHED) {
				e = "ClientFinished";
				break;
			}
			do_finished(SSL_CLIENT_SENDER, ctx);
		}
		else {
			if(ctx.state != STATE_FINISHED) {
				e = "ServerFinished";
				break;
			}
			do_finished(SSL_SERVER_SENDER, ctx);
		}

	* =>
		e = "unknown handshake message";
	}

	if(e != nil)
		e = "do_handshake: " + e;

	return e;
}

# [client side]
# The hello request message may be sent by server at any time, but will be ignored by 
# the client if the handshake protocol is already underway. It is simple notification 
# that the client should begin the negotiation process anew by sending a client hello 
# message.

do_hello_request(ctx: ref Context)
{
	# start from new handshake digest state
	ctx.sha_state = ctx.md5_state = nil;

	# Note:
	# 	sending ctx.local_info.suites instead of ctx.session.suite, 
	#	if session is resumable by server, ctx.session.suite will be used.
	handshake_enque(
		ref Handshake.ClientHello(
			ctx.session.version, 
			ctx.client_random, 
			ctx.session.session_id,	
			ctx.local_info.suites, 
			ctx.local_info.comprs
		),
		ctx
	);

	ctx.state = STATE_SERVER_HELLO;
}

# [client side]
# Processes the received server hello handshake message and determines if the session
# is resumable. (The client sends a client hello using the session id of the session
# to be resumed. The server then checks its session cache for a match. If a match is
# FOUND, and the server is WILLING to re-establish the connection under the specified
# session state, it will send a server hello with the SAME session id value.) If the
# session is resumed, at this point both client and server must send change cipher
# spec messages. If the session is not resumable, the client and server perform
# a full handshake. (On the server side, if a session id match is not found, the
# server generates a new session id or if the server is not willing to resume, the
# server uses a null session id).

do_server_hello(hm: ref Handshake.ServerHello, ctx: ref Context)
{
	# trying to resume
	if(bytes_cmp(ctx.session.session_id, hm.session_id) == 0) {

		if(SSL_DEBUG)
			log("ssl3: session resumed\n");

		ctx.status |= SESSION_RESUMABLE;
		# avoid version attack
		if(ctx.session.version[0] != hm.version[0] || 
			ctx.session.version[1] != hm.version[1]) {
			fatal(SSL_CLOSE_NOTIFY,	"do_server_hello: version mismatch", ctx);
			return;
		}

		ctx.server_random = hm.random;

		# uses the retrieved session suite by server (should be same by client)
		(ciph, keyx, sign, e) 
			:= suite_to_spec(hm.suite, SSL3_Suites);
		if(e != nil) {
			fatal(SSL_UNEXPECTED_MESSAGE, "server hello: suite not found", ctx);
			return;
		}
		ctx.sel_ciph = ciph;
		ctx.sel_keyx = keyx;
		ctx.sel_sign = sign;
		ctx.sel_cmpr = int ctx.session.compression; # not supported by ssl3 yet

		# calculate keys
		(ctx.cw_mac, ctx.sw_mac, ctx.cw_key, ctx.sw_key, ctx.cw_IV, ctx.sw_IV) 
			= calc_keys(ctx.sel_ciph, ctx.session.master_secret, 
			ctx.client_random, ctx.server_random);
		

		ctx.state = STATE_CHANGE_CIPHER_SPEC;
	}
	else {
		ctx.status &= ~SESSION_RESUMABLE;

		# On the server side, if a session id match is not found, the
		# server generates a new session id or if the server is not willing 
		# to resume, the server uses an empty session id and cannot be
		# cached by both client and server.

		ctx.session.session_id = hm.session_id;
		ctx.session.version = hm.version;
		ctx.server_random = hm.random;

		if(SSL_DEBUG)
			log("ssl3: do_server_hello:\n\tselected cipher suite =\n\t\t" 
			+ cipher_suite_info(hm.suite, SSL3_Suites) + "\n");

		(ciph, keyx, sign, e) := suite_to_spec(hm.suite, SSL3_Suites);
		if(e != nil) {
			fatal(SSL_UNEXPECTED_MESSAGE, "server hello: suite not found", ctx);
			return;
		}
		
		ctx.sel_ciph = ciph;
		ctx.sel_keyx = keyx;
		ctx.sel_sign = sign;
		ctx.sel_cmpr = int hm.compression; # not supported by ssl3 yet

		# next state is determined by selected key exchange and signature methods
		# the ctx.sel_keyx and ctx.sel_sign are completed by the following handshake
		# Certificate and/or ServerKeyExchange

		if(tagof ctx.sel_keyx == tagof KeyExAlg.DH && 
			tagof ctx.sel_sign == tagof SigAlg.anon)
			ctx.state = STATE_SERVER_KEY_EXCHANGE;
		else
			ctx.state = STATE_SERVER_CERTIFICATE;
	}
}

# [client side]
# Processes the received server key exchange message. The server key exchange message
# is sent by the server if it has no certificate, has a certificate only used for
# signing, or FORTEZZA KEA key exchange is used.

do_server_keyex(hm: ref Handshake.ServerKeyExchange, ctx: ref Context)
{
	# install exchange keys sent by server, this may require public key
	# retrieved from certificate sent by Handshake.Certificate message

	(err, i) := install_server_xkey(hm.xkey, ctx.sel_keyx);
	if(err == "")
		err = verify_server_xkey(ctx.client_random, ctx.server_random, hm.xkey, i, ctx.sel_sign);

	if(err == "")
		ctx.state = STATE_SERVER_HELLO_DONE;
	else
		fatal(SSL_HANDSHAKE_FAILURE, "do_server_keyex: " + err, ctx);
}

# [client side]
# Processes the received server hello done message by verifying that the server
# provided a valid certificate if required and checking that the server hello
# parameters are acceptable.

do_server_done(ctx: ref Context)
{
	# On client side, optionally send client cert chain if client_auth 
	# is required by the server. The server may drop the connection, 
	# if it does not receive client certificate in the following 
	# Handshake.ClientCertificate message
	if(ctx.status & CLIENT_AUTH) {
		if(ctx.local_info.certs != nil) {
			handshake_enque(
				ref Handshake.Certificate(ctx.local_info.certs),
				ctx
			);
			ctx.status |= CERT_SENT;
		}
		else {
			alert_enque(
				ref Alert(SSL_WARNING, SSL_NO_CERTIFICATE), 
				ctx
			);
		}
	}

	# calculate premaster secrect, client exchange keys and update ref KeyExAlg 
	# of the client side
	(x, pm, e) := calc_client_xkey(ctx.sel_keyx);
	if(e != "") {
		fatal(SSL_HANDSHAKE_FAILURE, e, ctx);
		return;
	}
	handshake_enque(ref Handshake.ClientKeyExchange(x), ctx);

	ms := calc_master_secret(pm, ctx.client_random, ctx.server_random);
	if(ms == nil) {
		fatal(SSL_HANDSHAKE_FAILURE, "server hello done: calc master secret failed", ctx);
		return;
	}
	# ctx.premaster_secret = pm;
	ctx.session.master_secret = ms;

	# sending certificate verifiy message if the client auth is required 
	# and client certificate has been sent,
	if(ctx.status & CERT_SENT) {
		sig : array of byte;
		(md5_hash, sha_hash) 
			:= calc_finished(nil, ctx.session.master_secret, ctx.sha_state, ctx.md5_state);
		# check type of client cert being sent
		pick sk := ctx.local_info.sk {
		RSA =>
			hashes := array [36] of byte;
			hashes[0:] = md5_hash;
			hashes[16:] = sha_hash;
			#(e, sig) = pkcs->rsa_sign(hashes, sk, PKCS->MD5_WithRSAEncryption);
		DSS =>
			#(e, sig) = pkcs->dss_sign(sha_hash, sk);
		* =>
			e = "unknown sign";
		}
		if(e != "") {
			fatal(SSL_HANDSHAKE_FAILURE, "server hello done: sign cert verify failed", ctx);
			return;
		}
		handshake_enque(ref Handshake.CertificateVerify(sig), ctx);
	}

	ccs_enque(ref ChangeCipherSpec(1), ctx);
	(ctx.cw_mac, ctx.sw_mac, ctx.cw_key, ctx.sw_key, ctx.cw_IV, ctx.sw_IV) 
		= calc_keys(ctx.sel_ciph, ctx.session.master_secret, 
		ctx.client_random, ctx.server_random);

	# set cipher on write channel
	e = set_out_queue(ctx);
	if(e != nil) {
		fatal(SSL_HANDSHAKE_FAILURE, "do_server_done: " + e, ctx);
		return;
	}
	ctx.status |= OUT_READY;

	if(SSL_DEBUG)
		log("ssl3: set out cipher done\n");
	(mh, sh) := calc_finished(SSL_CLIENT_SENDER, ctx.session.master_secret, 
		ctx.sha_state, ctx.md5_state);
# sending out the Finished msg causes MS https servers to hangup
#sys->print("RETURNING FROM DO_SERVER_DONE\n");
#return;
	handshake_enque(ref Handshake.Finished(mh, sh), ctx);

	ctx.state = STATE_CHANGE_CIPHER_SPEC;
}

# [client side]
# Process the received certificate message. 
# Note:
#	according to current US export law, RSA moduli larger than 512 bits
# 	may not be used for key exchange in software exported from US. With
# 	this message, larger RSA keys may be used as signature only
# 	certificates to sign temporary shorter RSA keys for key exchange.

do_server_cert(hm: ref Handshake.Certificate, ctx: ref Context)
{
	if(hm.cert_list == nil) {
		fatal(SSL_UNEXPECTED_MESSAGE, "nil peer certificate", ctx);
		return;
	}

	# server's certificate is the last one in the chain (reverse required)
	cl := hm.cert_list;
	ctx.session.peer_certs = nil;
	while(cl != nil) {
		ctx.session.peer_certs = hd cl::ctx.session.peer_certs;
		cl = tl cl;
	}

	# TODO: verify certificate chain
	#	check if in the acceptable dnlist
	# ctx.sel_keyx.peer_pk = x509->verify_chain(ctx.session.peer_certs);
	if(SSL_DEBUG)
		log("ssl3: number certificates got: " + string len ctx.session.peer_certs);
	peer_cert := hd ctx.session.peer_certs;
	(e, signed) := x509->Signed.decode(peer_cert);
	if(e != "") {
		if(SSL_DEBUG)
			log("ss3: server certificate: " + e);
		fatal(SSL_HANDSHAKE_FAILURE, "server certificate: " + e, ctx);
		return;
	}

	srv_cert: ref Certificate;
	(e, srv_cert) = x509->Certificate.decode(signed.tobe_signed);
	if(e != "") {
		if(SSL_DEBUG)
			log("ss3: server certificate: " + e);
		fatal(SSL_HANDSHAKE_FAILURE, "server certificate: " + e, ctx);
		return;
	}
	if(SSL_DEBUG)
		log("ssl3: " + srv_cert.tostring());

	# extract and determine byte of user certificate
	id: int;
	peer_pk: ref X509->PublicKey;
	(e, id, peer_pk) = srv_cert.subject_pkinfo.getPublicKey();
	if(e != "") {
		if(SSL_DEBUG)
			log("ss3: server certificate: " + e);
		fatal(SSL_HANDSHAKE_FAILURE, "server certificate:" + e, ctx);
		return;
	}

	pick key := peer_pk {
	RSA =>
		# TODO: to allow checking X509v3 KeyUsage extension
		if((0 && key.pk.modulus.bits() > 512 && ctx.sel_ciph.is_exportable)
			|| id == PKCS->id_pkcs_md2WithRSAEncryption 
			|| id == PKCS->id_pkcs_md4WithRSAEncryption 
			|| id == PKCS->id_pkcs_md5WithRSAEncryption) {
			pick sign := ctx.sel_sign {
			anon =>
				break;
			RSA =>
				break;
			* =>
				# error
			}
			if(ctx.local_info.sk == nil)
				ctx.sel_sign = ref SigAlg.RSA(nil, key.pk);
			else {
				pick mysk := ctx.local_info.sk {
				RSA =>
					ctx.sel_sign = ref SigAlg.RSA(mysk.sk, key.pk);
				* =>
					ctx.sel_sign = ref SigAlg.RSA(nil, key.pk);
				}
			}
			# key exchange may be tmp RSA, emhemeral DH depending on cipher suite
			ctx.state = STATE_SERVER_KEY_EXCHANGE;
		}
		# TODO: allow id == PKCS->id_rsa
		else if(id == PKCS->id_pkcs_rsaEncryption) {
			pick sign := ctx.sel_sign {
			anon =>
				break;
			* =>
				# error
			}
			ctx.sel_sign = ref SigAlg.anon();
			pick keyx := ctx.sel_keyx {
			RSA =>
				keyx.peer_pk = key.pk;
			* =>
				# error
			}
			ctx.state = STATE_SERVER_HELLO_DONE;
		}
		else {
			# error
		}
	DSS =>
		pick sign := ctx.sel_sign {
		DSS =>
			sign.peer_pk = key.pk;
			break;
		* =>
			# error
		}
		# should be key exchagne such as emhemeral DH
		ctx.state = STATE_SERVER_KEY_EXCHANGE;
	DH =>
		# fixed DH signed in certificate either by RSA or DSS???
		pick keyx := ctx.sel_keyx {
		DH =>
			keyx.peer_pk = key.pk;
		* => 
			# error 
		}
		ctx.state = STATE_SERVER_KEY_EXCHANGE;
	}

	if(e != nil) {
		fatal(SSL_HANDSHAKE_FAILURE, "do_server_cert: " + e, ctx);
		return;
	}
}

# [client side]
# Processes certificate request message. A non-anonymous server can optionally
# request a certificate from the client, if appropriate for the selected cipher
# suite It is a fatal handshake failure alert for an anonymous server to
# request client identification.

# TODO: use another module to do x509 certs, lookup and matching rules

do_cert_request(hm: ref Handshake.CertificateRequest, ctx: ref Context)
{
	found := 0;
	for(i := 0; i < len hm.cert_types; i++) {
		if(ctx.local_info.root_type == int hm.cert_types[i]) {
			found = 1;
			break;
		}
	}
	if(!found) {
		fatal(SSL_HANDSHAKE_FAILURE, "do_cert_request: no required type of cert", ctx);
		return;		
	}
	if(dn_cmp(ctx.local_info.dns, hm.dn_list) < 0) {
		fatal(SSL_HANDSHAKE_FAILURE, "do_cert_request: no required dn", ctx);
		return;		
	}
	if(ctx.session.peer_certs == nil) {
		fatal(SSL_NO_CERTIFICATE, "certificate request: no peer certificates", ctx);
		return;
	}

	ctx.status |= CLIENT_AUTH;
}

dn_cmp(a, b: list of array of byte): int
{
	return -1;
}

# [server side]
# Process client hello message. 

do_client_hello(hm: ref Handshake.ClientHello, ctx: ref Context)
{
	sndm : ref Handshake;
	e : string;

	if(hm.version[0] != SSL_VERSION_3_0[0] || hm.version[1] != SSL_VERSION_3_0[1]) { 
		fatal(SSL_UNEXPECTED_MESSAGE, "client hello: version mismatch", ctx);
		return;
	}
	# else SSL_VERSION_2_0

	if(hm.session_id != nil) { # trying to resume
		if(ctx.status & SESSION_RESUMABLE) {
			s := sslsession->get_session_byid(hm.session_id);
			if(s == nil) {
				fatal(SSL_UNEXPECTED_MESSAGE, "client hello: retrieve nil session", ctx);
				return;
			}

			if(s.version[0] != hm.version[0] || s.version[1] != hm.version[1]) {
				# avoid version attack
				fatal(SSL_UNEXPECTED_MESSAGE, "client hello: protocol mismatch", ctx);
				return;
			}

			reset_server_random(ctx);
			ctx.client_random = hm.random;

			sndm = ref Handshake.ServerHello(s.version, ctx.server_random, 
				s.session_id, s.suite, s.compression);
			handshake_enque(sndm, ctx);

			ccs_enque(ref ChangeCipherSpec(1), ctx);
			# use existing master_secret, calc keys
			(ctx.cw_mac, ctx.sw_mac, ctx.cw_key, ctx.sw_key, ctx.cw_IV, ctx.sw_IV) 
				= calc_keys(ctx.sel_ciph, ctx.session.master_secret, ctx.client_random, 
				ctx.server_random);
			e = set_out_queue(ctx);
			if(e != nil) {
				fatal(SSL_CLOSE_NOTIFY,	"client hello: setup new cipher failure", ctx);
				return;
			}
			if(SSL_DEBUG)
				log("do_client_hello: set out cipher done\n");

			(md5_hash, sha_hash) := calc_finished(SSL_SERVER_SENDER, 
				s.master_secret, ctx.sha_state, ctx.md5_state);

			handshake_enque(ref Handshake.Finished(md5_hash, sha_hash), ctx);
			
			ctx.session = s;
			ctx.state = STATE_CHANGE_CIPHER_SPEC;
			return;
		}

		fatal(SSL_CLOSE_NOTIFY,	"client hello: resume session failed", ctx);
		return;		
	}

	ctx.session.version = hm.version;
	if(ctx.session.peer != nil) {		
		ctx.session.session_id = random->randombuf(Random->NotQuiteRandom, 32);
		if(ctx.session.session_id == nil) {
			fatal(SSL_CLOSE_NOTIFY,	"client hello: generate session id failed", ctx);
			return;
		}
	}

	suite := find_cipher_suite(hm.suites, ctx.local_info.suites);
	if(suite != nil) {
		fatal(SSL_HANDSHAKE_FAILURE, "client hello: find cipher suite failed", ctx);
		return;
	}
		
	(ctx.sel_ciph, ctx.sel_keyx, ctx.sel_sign, e) = suite_to_spec(suite, SSL3_Suites);
	if(e != nil) {
		fatal(SSL_HANDSHAKE_FAILURE, "client hello: find cipher suite failed" + e, ctx);
		return;
	}

	# not supported by ssl3 yet
	ctx.sel_cmpr = int hm.compressions[0];
	ctx.client_random = hm.random;
	ctx.sha_state = nil;
	ctx.md5_state = nil;

	sndm = ref Handshake.ServerHello(ctx.session.version, ctx.server_random, 
		ctx.session.session_id, ctx.session.suite, ctx.session.compression);
	handshake_enque(sndm, ctx);

	# set up keys based on algorithms

	if(tagof ctx.sel_keyx != tagof KeyExAlg.DH) {
		if(ctx.local_info.certs == nil || ctx.local_info.sk == nil) {
			fatal(SSL_HANDSHAKE_FAILURE, "client hello: no local cert or key", ctx);
			return;
		}

		sndm = ref Handshake.Certificate(ctx.local_info.certs);
		handshake_enque(sndm, ctx);
	}

	if(tagof ctx.sel_keyx != tagof KeyExAlg.RSA || 
		tagof ctx.sel_sign != tagof SigAlg.anon) {
		params, signed_params, xkey: array of byte;
		(params, e) = calc_server_xkey(ctx.sel_keyx);
		if(e == "")
			(signed_params, e) = sign_server_xkey(ctx.sel_sign, params, 
				ctx.client_random, ctx.server_random); 
		if(e != "")
			
		n := len params + 2 + len signed_params;
		xkey = array [n] of byte;
		xkey[0:] = params;
		xkey[len params:] = int_encode(len signed_params, 2);
		xkey[len params+2:] = signed_params;
		handshake_enque(ref Handshake.ServerKeyExchange(xkey), ctx);
	}

	if(ctx.status & CLIENT_AUTH) {
		sndm = ref Handshake.CertificateRequest(ctx.local_info.types, ctx.local_info.dns);
		handshake_enque(sndm, ctx);

		ctx.status |= CERT_REQUEST;
		ctx.state = STATE_CLIENT_CERTIFICATE;
	}
	else
		ctx.state = STATE_CLIENT_KEY_EXCHANGE;

	handshake_enque(ref Handshake.ServerHelloDone(), ctx);
}

# [server side]
# Process the received client key exchange message. 

do_client_keyex(hm: ref Handshake.ClientKeyExchange, ctx: ref Context)
{
	(premaster_secret, err) := install_client_xkey(hm.xkey, ctx.sel_keyx);
	if(err != "") {
		fatal(SSL_HANDSHAKE_FAILURE, err, ctx);
		return;
	}
		
	ctx.session.master_secret = calc_master_secret(premaster_secret, 
		ctx.client_random, ctx.server_random);

	if(ctx.status & CERT_RECEIVED)	
		ctx.state = STATE_CERTIFICATE_VERIFY;
	else
		ctx.state = STATE_CHANGE_CIPHER_SPEC;
}

# [server side]
# Process the received certificate message from client. 

do_client_cert(hm: ref Handshake.Certificate, ctx: ref Context)
{
	ctx.session.peer_certs = hm.cert_list;
	
	# verify cert chain and determine the type of cert
	# ctx.peer_info.sk = x509->verify_chain(ctx.session.peer_certs);
	# if(ctx.peer_info.key == nil) {
	#	fatal(SSL_HANDSHAKE_FAILURE, "client certificate: cert verify failed", ctx);
	#	return;
	# }

	ctx.status |= CERT_RECEIVED;

	ctx.state = STATE_CLIENT_KEY_EXCHANGE;
}

# [server side]
# Process the received certificate verify message from client.

do_cert_verify(hm: ref Handshake.CertificateVerify, ctx: ref Context)
{
	if(ctx.status & CERT_RECEIVED) {
		# exp : array of byte;
		(md5_hash, sha_hash) 
			:= calc_finished(nil, ctx.session.master_secret, ctx.sha_state, ctx.md5_state);
		ok := 0;
		pick upk := ctx.sel_sign {
		RSA =>
			hashes := array [36] of byte;
			hashes[0:] = md5_hash;
			hashes[16:] = sha_hash;
			ok = pkcs->rsa_verify(hashes, hm.signature, upk.peer_pk, PKCS->MD5_WithRSAEncryption);
		DSS =>
			ok = pkcs->dss_verify(sha_hash, hm.signature, upk.peer_pk);
		}

		if(!ok) {
			fatal(SSL_HANDSHAKE_FAILURE, "do_cert_verify: client auth failed", ctx);
			return;
		}
	}
	else {
		alert_enque(ref Alert(SSL_WARNING, SSL_NO_CERTIFICATE), ctx);
		return;
	}

	ctx.state = STATE_CHANGE_CIPHER_SPEC;
}

# [client or server side]
# Process the received finished message either from client or server. 

do_finished(sender: array of byte, ctx: ref Context)
{
	# setup write_cipher if not yet
	if(!(ctx.status & OUT_READY)) {
		ccs_enque(ref ChangeCipherSpec(1), ctx);
		e := set_out_queue(ctx);
		if(e != nil) {
			fatal(SSL_CLOSE_NOTIFY, "do_finished: setup new cipher failed", ctx);
			return;
		}
		ctx.status |= OUT_READY;

		if(SSL_DEBUG)
			log("ssl3: set out cipher done\n");

		(md5_hash, sha_hash) := calc_finished(sender, ctx.session.master_secret, 
			ctx.sha_state, ctx.md5_state);
		handshake_enque(ref Handshake.Finished(md5_hash, sha_hash), ctx);
	}

	ctx.state = STATE_EXIT; # normal

	# clean read queue
	ctx.in_queue.fragment = 0;

	sslsession->add_session(ctx.session);

	if(SSL_DEBUG)
		log("ssl3: add session to session database done\n");
}

install_client_xkey(a: array of byte, keyx: ref KeyExAlg): (array of byte, string)
{
	pmaster, x : array of byte;
	err := "";
	pick kx := keyx {
	DH =>
		i := 0;
		(kx.peer_pk, i) = dh_params_decode(a);
		if(kx.peer_pk != nil) 
			pmaster = pkcs->computeDHAgreedKey(kx.sk.param, kx.sk.sk, kx.peer_pk.pk);
		else
			err = "decode dh params failed";
	RSA =>
		(err, x) = pkcs->rsa_decrypt(a, kx.sk, 2);
		if(err != "" || len x != 48) {
			err = "impl error";
		}
		else {
			if(x[0] != SSL_VERSION_3_0[0] && x[1] != SSL_VERSION_3_0[1])
				err = "version wrong: possible version attack";
			else
				pmaster = x[2:];
		}
	FORTEZZA_KEA =>
		err = "Fortezza unsupported";
	}
	return (pmaster, err);
}

install_server_xkey(a: array of byte, keyx: ref KeyExAlg): (string, int)
{
	err := "";
	i := 0;

	pick kx := keyx {
	DH =>
		(kx.peer_pk, i) = dh_params_decode(a);
		if(kx.peer_pk != nil) 
			kx.peer_params = kx.peer_pk.param;
	RSA =>
		peer_tmp: ref RSAParams;
		(peer_tmp, i, err) = rsa_params_decode(a);
		if(err == "") {
			modlen := len peer_tmp.modulus.iptobebytes();
			kx.peer_pk = ref RSAKey(peer_tmp.modulus, modlen, peer_tmp.exponent);
		}
	FORTEZZA_KEA =>	
		return ("Fortezza unsupported", i);
	}

	return (err, i);
}

verify_server_xkey(crand, srand: array of byte, a: array of byte, i : int, sign: ref SigAlg)
	: string
{
	pick sg := sign {
	anon => 
	RSA =>
		lb := a[0:i]::crand::srand::nil;
		(exp, nil, nil) := md5_sha_hash(lb, nil, nil);
		ok := pkcs->rsa_verify(exp, a[i+2:], sg.peer_pk, PKCS->MD5_WithRSAEncryption); 
		if(!ok)
			return "RSA sigature verification failed";
	DSS =>
		lb := a[0:i]::crand::srand::nil;
		(exp, nil) := sha_hash(lb, nil);
		ok := pkcs->dss_verify(exp, a[i+2:], sg.peer_pk); 
		if(!ok)
			return "DSS sigature verification failed";
	}

	return "";
}

calc_client_xkey(keyx: ref KeyExAlg): (array of byte, array of byte, string)
{
	pm, x : array of byte;
	err := "";
	pick kx := keyx {
	DH =>	
		# generate our own DH keys based on DH params of peer side
		(kx.sk, kx.exch_pk) = pkcs->setupDHAgreement(kx.peer_params);
		# TODO: need check type of client cert if(!ctx.status & CLIENT_AUTH)
		# 	for implicit case
		(x, err) = dh_exchpub_encode(kx.exch_pk);
		pm = pkcs->computeDHAgreedKey(kx.sk.param, kx.sk.sk, kx.peer_pk.pk);
	RSA =>
		pm = array [48] of byte;
		pm[0:] = SSL_VERSION_3_0; # against version attack
		pm[2:] = random->randombuf(Random->NotQuiteRandom, 46);
		(err, x) = pkcs->rsa_encrypt(pm, kx.peer_pk, 2);
	FORTEZZA_KEA =>	
		err = "Fortezza unsupported";
	}
	if(SSL_DEBUG)
		log("ssl3: calc_client_xkey: " + bastr(x));
	return (x, pm, err);
}

calc_server_xkey(keyx: ref KeyExAlg): (array of byte, string)
{
	params: array of byte;
	err: string;
	pick kx := keyx {
	DH =>
		(kx.sk, kx.exch_pk) = pkcs->setupDHAgreement(kx.params);
		(params, err) = dh_params_encode(kx.exch_pk);
	RSA =>
		tmp := ref RSAParams(kx.export_key.modulus, kx.export_key.exponent);
		(params, err) = rsa_params_encode(tmp);

	FORTEZZA_KEA =>	
		err = "Fortezza unsupported";
	}
	return (params, err);
}

sign_server_xkey(sign: ref SigAlg, params, cr, sr: array of byte): (array of byte, string)
{
	signed_params: array of byte;
	err: string;
	pick sg := sign {
	anon =>
	RSA =>
		lb := cr::sr::params::nil;
		(hashes, nil, nil) := md5_sha_hash(lb, nil, nil);
		(err, signed_params) = pkcs->rsa_sign(hashes, sg.sk, PKCS->MD5_WithRSAEncryption);
	DSS =>
		lb := cr::sr::params::nil;
		(hashes, nil) := sha_hash(lb, nil);
		(err, signed_params) = pkcs->dss_sign(hashes, sg.sk);
	}
	return (signed_params, err);
}

# ssl encoding of DH exchange public key

dh_exchpub_encode(dh: ref DHPublicKey): (array of byte, string)
{
	if(dh != nil) {		
		yb := dh.pk.iptobebytes();	
		if(yb != nil) {
			n := 2 + len yb;
			a := array [n] of byte;
			i := 0;
			a[i:] = int_encode(len yb, 2);			
			i += 2;
			a[i:] = yb;
			return (a, nil);
		}
	}
	return (nil, "nil dh params");
}

dh_params_encode(dh: ref DHPublicKey): (array of byte, string)
{
	if(dh != nil && dh.param != nil) {
		pb := dh.param.prime.iptobebytes();		
		gb := dh.param.base.iptobebytes();
		yb := dh.pk.iptobebytes();	
		if(pb != nil && gb != nil && yb != nil) {
			n := 6 + len pb + len gb + len yb;
			a := array [n] of byte;
			i := 0;
			a[i:] = int_encode(len pb, 2);			
			i += 2;
			a[i:] = pb;					
			i += len pb;
			a[i:] = int_encode(len gb, 2);			
			i += 2;
			a[i:] = gb;					
			i += len gb;
			a[i:] = int_encode(len yb, 2);			
			i += 2;
			a[i:] = yb;					
			i += len yb;
			return (a, nil);
		}
	}
	return (nil, "nil dh public key");
}

dh_params_decode(a: array of byte): (ref DHPublicKey, int)
{
	i := 0;
	for(;;) {
		n := int_decode(a[i:i+2]);			
		i += 2;
		if(i+n > len a)
			break;
		p := a[i:i+n];					
		i += n; 
		n = int_decode(a[i:i+2]);			
		i += 2;
		if(i+n > len a)
			break;
		g := a[i:i+n];					
		i += n;
		n = int_decode(a[i:i+2]);			
		i += 2;
		if(i+n > len a)
			break;
		Ys := a[i:i+n];				
		i += n;

		if(SSL_DEBUG)
			log("ssl3: dh_params_decode:" + "\n\tp =\n\t\t" + bastr(p)
			+ "\n\tg =\n\t\t" + bastr(g) + "\n\tYs =\n\t\t" + bastr(Ys) + "\n");

		# don't care privateValueLength
		param := ref DHParams(IPint.bebytestoip(p), IPint.bebytestoip(g), 0);
		return (ref DHPublicKey(param, IPint.bebytestoip(Ys)), i);
	}
	return (nil, i);
}

rsa_params_encode(rsa_params: ref RSAParams): (array of byte, string)
{
	if(rsa_params != nil) {
		mod := rsa_params.modulus.iptobebytes();
		exp := rsa_params.exponent.iptobebytes();
		if(mod != nil || exp != nil) {
			n := 4 + len mod + len exp;
			a := array [n] of byte;
			i := 0;
			a[i:] = int_encode(len mod, 2); 		
			i += 2;
			a[i:] = mod;					
			i += len mod;
			a[i:] = int_encode(len exp, 2);			
			i += 2;
			a[i:] = exp;					
			i += len exp;
			return (a, nil);
		}
	}
	return (nil, "nil rsa params");
}

rsa_params_decode(a: array of byte): (ref RSAParams, int, string)
{
	i := 0;
	for(;;) {
		if(len a < 2)
			break;
		n := int_decode(a[i:i+2]);
		i += 2;
		if(n < 0 || n + i > len a)
			break;
		mod := a[i:i+n];				
		i += n;
		n = int_decode(a[i:i+2]);			
		i += 2;
		if(n < 0 || n + i > len a)
			break;
		exp := a[i:i+n];				
		i += n;
		m := i;
		modulus := IPint.bebytestoip(mod);
		exponent := IPint.bebytestoip(exp);

		if(SSL_DEBUG)
			log("ssl3: decode RSA params\n\tmodulus = \n\t\t" + bastr(mod)
			+ "\n\texponent = \n\t\t" + bastr(exp) + "\n");

		if(len a < i+2)
			break;
		n = int_decode(a[i:i+2]);
		i += 2;
		if(len a != i + n)	
			break;
		return (ref RSAParams(modulus, exponent), m, nil);
	}
	return (nil, i, "encoding error");
}

# md5_hash       MD5(master_secret + pad2 +
#                     MD5(handshake_messages + Sender +
#                          master_secret + pad1));
# sha_hash       SHA(master_secret + pad2 +
#                     SHA(handshake_messages + Sender +
#                          master_secret + pad1));
#
# handshake_messages  All of the data from all handshake messages
#                     up to but not including this message.  This
#                     is only data visible at the handshake layer
#                     and does not include record layer headers.
#
# sender [4], master_secret [48]
# pad1 and pad2, 48 bytes for md5, 40 bytes for sha

calc_finished(sender, master_secret: array of byte, sha_state, md5_state: ref DigestState)
	: (array of byte, array of byte)
{
	sha_value := array [Keyring->SHA1dlen] of byte;
	md5_value := array [Keyring->MD5dlen] of byte;
	sha_inner := array [Keyring->SHA1dlen] of byte;
	md5_inner := array [Keyring->MD5dlen] of byte;

	lb := master_secret::SSL_MAC_PAD1[0:48]::nil;
	if(sender != nil)
		lb = sender::lb;
	(md5_inner, nil) = md5_hash(lb, md5_state);

	lb = master_secret::SSL_MAC_PAD1[0:40]::nil;
	if(sender != nil)
		lb = sender::lb;
	(sha_inner, nil) = sha_hash(lb, sha_state);

	(md5_value, nil) = md5_hash(master_secret::SSL_MAC_PAD2[0:48]::md5_inner::nil, nil);
	(sha_value, nil) = sha_hash(master_secret::SSL_MAC_PAD2[0:40]::sha_inner::nil, nil);

	# if(SSL_DEBUG)
	#	log("ssl3: calc_finished:" 
	#	+ "\n\tmd5_inner = \n\t\t" + bastr(md5_inner) 
	#	+ "\n\tsha_inner = \n\t\t" + bastr(sha_inner)
	#	+ "\n\tmd5_value = \n\t\t" + bastr(md5_value)
	#	+ "\n\tsha_value = \n\t\t" + bastr(sha_value) 
	#	+ "\n");

	return (md5_value, sha_value);
}


# master_secret =
#	MD5(premaster_secret + SHA('A' + premaster_secret +
#		ClientHello.random + ServerHello.random)) +
#	MD5(premaster_secret + SHA('BB' + premaster_secret +
#		ClientHello.random + ServerHello.random)) +
#	MD5(premaster_secret + SHA('CCC' + premaster_secret +
#		ClientHello.random + ServerHello.random));

calc_master_secret(pm, cr, sr: array of byte): array of byte
{
	ms := array [48] of byte;
	sha_value := array [Keyring->SHA1dlen] of byte;
	leader := array [3] of byte;

	j := 0;
	lb := pm::cr::sr::nil;
	for(i := 1; i <= 3; i++) {
		leader[0] = leader[1] = leader[2] = byte (16r40 + i);
		(sha_value, nil) = sha_hash(leader[0:i]::lb, nil);
		(ms[j:], nil) = md5_hash(pm::sha_value::nil, nil); 
		j += 16; # Keyring->MD5dlen
	}

	if(SSL_DEBUG)
		log("ssl3: calc_master_secret:\n\tmaster_secret = \n\t\t" + bastr(ms) + "\n");

	return ms;
}


# key_block =
# 	MD5(master_secret + SHA(`A' + master_secret + 
#				ServerHello.random + ClientHello.random)) +
#       MD5(master_secret + SHA(`BB' + master_secret + 
#				ServerHello.random + ClientHello.random)) +
#       MD5(master_secret + SHA(`CCC' + master_secret + 
#				ServerHello.random + ClientHello.random)) +
#	[...];

calc_key_material(n: int, ms, cr, sr: array of byte): array of byte
{
	key_block := array [n] of byte;
	sha_value := array [Keyring->SHA1dlen] of byte; # [20]
	md5_value := array [Keyring->MD5dlen] of byte; # [16]
	leader := array [10] of byte;

	if(n > 16*(len leader)) {
		if(SSL_DEBUG)
			log(sys->sprint("ssl3: calc key block: key size too long [%d]", n));
		return nil;
	}

	m := n;
	i, j, consumed, next : int = 0;
	lb := ms::sr::cr::nil;
	for(i = 0; m > 0; i++) {
		for(j = 0; j <= i; j++)
			leader[j] = byte (16r41 + i); # 'A', 'BB', 'CCC', etc.

		(sha_value, nil) = sha_hash(leader[0:i+1]::lb, nil);
		(md5_value, nil) = md5_hash(ms::sha_value::nil, nil); 

		consumed = Keyring->MD5dlen;
		if(m < Keyring->MD5dlen)
			consumed = m;
		m -= consumed;

		key_block[next:] = md5_value[0:consumed];
		next += consumed;		
	}

	if(SSL_DEBUG)
		log("ssl3: calc_key_material:" + "\n\tkey_block = \n\t\t" + bastr(key_block) + "\n");

	return key_block;
}

# Then the key_block is partitioned as follows.
#
#	client_write_MAC_secret[CipherSpec.hash_size]
#	server_write_MAC_secret[CipherSpec.hash_size]
#	client_write_key[CipherSpec.key_material]
#	server_write_key[CipherSpec.key_material]
#	client_write_IV[CipherSpec.IV_size] /* non-export ciphers */
#	server_write_IV[CipherSpec.IV_size] /* non-export ciphers */
#
# Any extra key_block material is discarded.
#
# Exportable encryption algorithms (for which
# CipherSpec.is_exportable is true) require additional processing as
# follows to derive their final write keys:
#
#	final_client_write_key = MD5(client_write_key +
#					ClientHello.random +
#					ServerHello.random);
#	final_server_write_key = MD5(server_write_key +
#					ServerHello.random +
#					ClientHello.random);
#
# Exportable encryption algorithms derive their IVs from the random
# messages:
#
#	client_write_IV = MD5(ClientHello.random + ServerHello.random);
#	server_write_IV = MD5(ServerHello.random + ClientHello.random);

calc_keys(ciph: ref CipherSpec, ms, cr, sr: array of byte) 
	: (array of byte, array of byte, array of byte, array of byte, array of byte, array of byte)
{
	cw_mac, sw_mac, cw_key, sw_key,	cw_IV, sw_IV: array of byte;

	n := ciph.key_material + ciph.hash_size;
	if(ciph.is_exportable == SSL_EXPORT_FALSE)
		n += ciph.IV_size;
	n *= 2;

	key_block := calc_key_material(n, ms, cr, sr);

	i := 0;
	if(ciph.hash_size != 0) {
		cw_mac = key_block[i:i+ciph.hash_size]; 
		i += ciph.hash_size;
		sw_mac = key_block[i:i+ciph.hash_size]; 
		i += ciph.hash_size;
	}

	if(ciph.is_exportable == SSL_EXPORT_FALSE) {
		if(ciph.key_material != 0) {
			cw_key = key_block[i:i+ciph.key_material]; 
			i += ciph.key_material;
			sw_key = key_block[i:i+ciph.key_material]; 
			i += ciph.key_material;
		}
		if(ciph.IV_size != 0) {
			cw_IV = key_block[i:i+ciph.IV_size]; 
			i += ciph.IV_size;
			sw_IV = key_block[i:i+ciph.IV_size]; 
			i += ciph.IV_size;
		}
	}
	else {
		if(ciph.key_material != 0) {
			cw_key = key_block[i:i+ciph.key_material]; 
			i += ciph.key_material;
			sw_key = key_block[i:i+ciph.key_material]; 
			i += ciph.key_material;
			(cw_key, nil) = md5_hash(cw_key::cr::sr::nil, nil);
			(sw_key, nil) = md5_hash(sw_key::sr::cr::nil, nil);
		}
		if(ciph.IV_size != 0) {
			(cw_IV, nil) = md5_hash(cr::sr::nil, nil);
			(sw_IV, nil) = md5_hash(sr::cr::nil, nil);
		}
	}

	if(SSL_DEBUG)
		log("ssl3: calc_keys:" 
		+ "\n\tclient_write_mac = \n\t\t" + bastr(cw_mac)
		+ "\n\tserver_write_mac = \n\t\t" + bastr(sw_mac)
		+ "\n\tclient_write_key = \n\t\t" + bastr(cw_key)
		+ "\n\tserver_write_key = \n\t\t" + bastr(sw_key)
 		+ "\n\tclient_write_IV  = \n\t\t" + bastr(cw_IV)
		+ "\n\tserver_write_IV = \n\t\t" + bastr(sw_IV) + "\n");

	return (cw_mac, sw_mac, cw_key, sw_key, cw_IV, sw_IV);
}

#
# decode protocol message
#
Protocol.decode(r: ref Record, ctx: ref Context): (ref Protocol, string)
{
	p : ref Protocol;

	case r.content_type {
	SSL_ALERT =>
		if(len r.data != 2)
			return (nil, "alert decode failed");

		p = ref Protocol.pAlert(ref Alert(int r.data[0], int r.data[1])); 

	SSL_CHANGE_CIPHER_SPEC =>
		if(len r.data != 1 || r.data[0] != byte 1)
			return (nil, "ChangeCipherSpec decode failed");

		p = ref Protocol.pChangeCipherSpec(ref ChangeCipherSpec(1));

	SSL_HANDSHAKE =>
		(hm, e) := Handshake.decode(r.data);
		if(e != nil)
			return (nil, e);

		pick h := hm {
		Finished =>
			exp_sender := SSL_CLIENT_SENDER;
			if(ctx.status & CLIENT_SIDE)
				exp_sender = SSL_SERVER_SENDER;

			(md5_hash, sha_hash) := calc_finished(exp_sender, 
				ctx.session.master_secret, ctx.sha_state, ctx.md5_state);

			if(SSL_DEBUG)
				log("ssl3: handshake_decode: finished"
				+ "\n\texpected_md5_hash = \n\t\t" + bastr(md5_hash)
				+ "\n\tgot_md5_hash = \n\t\t" + bastr(h.md5_hash)
				+ "\n\texpected_sha_hash = \n\t\t" + bastr(sha_hash)
				+ "\n\tgot_sha_hash = \n\t\t" + bastr(h.sha_hash) + "\n");

			#if(string md5_hash != string h.md5_hash || string sha_hash != string h.sha_hash)
			if(bytes_cmp(md5_hash, h.md5_hash) < 0 || bytes_cmp(sha_hash, h.sha_hash) < 0)
				return (nil, "finished: sender mismatch");

			e = update_handshake_hash(ctx, r);
			if(e != nil)
				return (nil, e);

		CertificateVerify =>

			e = update_handshake_hash(ctx, r);
			if(e != nil)
				return (nil, e);

		* =>
			e = update_handshake_hash(ctx, r);
			if(e != nil)
				return (nil, e);
		}

		p = ref Protocol.pHandshake(hm);

	SSL_V2HANDSHAKE =>

		(hm, e) := V2Handshake.decode(r.data);
		if(e != "")
			return (nil, e);

		p = ref Protocol.pV2Handshake(hm);

	* =>
		return (nil, "protocol read: unknown protocol");
	}

	return (p, nil);

}


# encode protocol message and return tuple of data record and error message,
# may be v2 or v3 record depending on vers.

Protocol.encode(protocol: self ref Protocol, vers: array of byte): (ref Record, string)
{
	r: ref Record;
	e: string;

	pick p := protocol {
	pAlert =>
		r = ref Record(
				SSL_ALERT,
				vers,
				array [] of {byte p.alert.level, byte p.alert.description}
			);

	pChangeCipherSpec =>
		r = ref Record(
				SSL_CHANGE_CIPHER_SPEC,
				vers,
				array [] of {byte p.change_cipher_spec.value}
			);

	pHandshake =>
		data: array of byte;
		(data, e) = p.handshake.encode();
		if(e != "")
			break;
		r = ref Record(
				SSL_HANDSHAKE, 
				vers,
				data
			);

	pV2Handshake =>
		data: array of byte;
		(data, e) = p.handshake.encode();
		if(e != "")
			break;
		r = ref Record(
				SSL_V2HANDSHAKE,
				vers,
				data
			);

	* =>
		e = "unknown protocol";
	}

	if(SSL_DEBUG)
		log("ssl3: protocol encode\n" + protocol.tostring());

	return (r, e);
}

#
# protocol message description
#
Protocol.tostring(protocol: self ref Protocol): string
{
	info : string;

	pick p := protocol {
	pAlert =>
		info = "\tAlert\n" + p.alert.tostring();

	pChangeCipherSpec =>
		info = "\tChangeCipherSpec\n";

	pHandshake =>
		info = "\tHandshake\n" + p.handshake.tostring();

	pV2Handshake =>
		info = "\tV2Handshake\n" + p.handshake.tostring();

	pApplicationData =>
		info = "\tApplicationData\n";

	* =>
		info = "\tUnknownProtocolType\n";
	}

	return "ssl3: Protocol:\n" + info;
}

Handshake.decode(buf: array of byte): (ref Handshake, string)
{
	m : ref Handshake;
	e : string;

	a := buf[4:]; # ignore msg length

	i := 0;
	case int buf[0] {
	SSL_HANDSHAKE_HELLO_REQUEST =>
		m = ref Handshake.HelloRequest();

        SSL_HANDSHAKE_CLIENT_HELLO =>
    		if(len a < 38) {
			e = "client hello: unexpected message";
			break;
		}
    		cv := a[i:i+2];
		i += 2;
		rd := a[i:i+32];	
		i += 32;    
		lsi := int a[i++];
    		if(len a < 38 + lsi) {
			e = "client hello: unexpected message";
			break;
		}
		sid: array of byte;
		if(lsi != 0) {
			sid = a[i:i+lsi];			
			i += lsi;
		}
		else
			sid = nil;
		lcs := int_decode(a[i:i+2]);    	
		i += 2;
		if((lcs & 1) || lcs < 2 || len a < 40 + lsi + lcs) {
			e = "client hello: unexpected message";
			break;
		}
		cs := array [lcs/2] of byte;
		cs = a[i:i+lcs];
		i += lcs;
		lcm := int a[i++];
		cr := a[i:i+lcm];			
		i += lcm;
		# In the interest of forward compatibility, it is
		# permitted for a client hello message to include
		# extra data after the compression methods. This
		# data must be included in the handshake hashes, 
		# but otherwise be ignored.
		# if(i != len a) {
		#	e = "client hello: unexpected message";
		#	break;
		# }
		m = ref Handshake.ClientHello(cv, rd, sid, cs, cr);

        SSL_HANDSHAKE_SERVER_HELLO =>
		if(len a < 38) {
			e = "server hello: unexpected message";
			break;
		}
		sv := a[i:i+2];			
		i += 2;
		rd := a[i:i+32];			
		i += 32;
		lsi := int a[i++];
		if(len a < 38 + lsi) {
			e = "server hello: unexpected message";
			break;
		}
		sid : array of byte;
		if(lsi != 0) {
			sid = a[i:i+lsi];			
			i += lsi;
		}
		else
			sid = nil;
		cs := a[i:i+2];			
		i += 2;
		cr := a[i++];
		if(i != len a) {
			e = "server hello: unexpected message";
			break;
		}
		m = ref Handshake.ServerHello(sv, rd, sid, cs, cr);

        SSL_HANDSHAKE_CERTIFICATE =>
		n := int_decode(a[i:i+3]);		
		i += 3;
		if(len a != n + 3) {
			e = "certificate: unexpected message";
			break;
		}
		cl : list of array of byte;
		k : int;
		while(i < n) {
			k = int_decode(a[i:i+3]);
			i += 3;	
			if(k < 0 || i + k > len a) {
				e = "certificate: unexpected message";
				break;
			}
			cl = a[i:i+k] :: cl;		
			i += k;
		}
		if(e != nil)
			break;
		m = ref Handshake.Certificate(cl);

        SSL_HANDSHAKE_SERVER_KEY_EXCHANGE =>

		m = ref Handshake.ServerKeyExchange(a[i:]);
		
        SSL_HANDSHAKE_CERTIFICATE_REQUEST =>
		ln := int_decode(a[i:i+2]);		
		i += 2;
		types := a[i:i+ln];			
		i += ln;
		ln = int_decode(a[i:i+2]);		
		i += 2;
		auths : list of array of byte;
		for(j := 0; j < ln; j++) {
			ln = int_decode(a[i:i+2]);	
			i += 2;
			auths = a[i:i+ln]::auths;	
			i += ln;
		}
		m = ref Handshake.CertificateRequest(types, auths);

        SSL_HANDSHAKE_SERVER_HELLO_DONE =>
		if(len a != 0) {
			e = "server hello done: unexpected message";
			break;
		}
		m = ref Handshake.ServerHelloDone();
	
        SSL_HANDSHAKE_CERTIFICATE_VERIFY =>
		ln := int_decode(a[i:i+2]);		
		i +=2;
		sig := a[i:];				
		i += ln;
		if(i != len a) {
			e = "certificate verify: unexpected message";
			break;
		}
		m = ref Handshake.CertificateVerify(sig);

        SSL_HANDSHAKE_CLIENT_KEY_EXCHANGE =>
		m = ref Handshake.ClientKeyExchange(a);

        SSL_HANDSHAKE_FINISHED =>
		if(len a != Keyring->MD5dlen + Keyring->SHA1dlen) { # 16+20
			e = "finished: unexpected message";
			break;
		}
		md5_hash := a[i:i+Keyring->MD5dlen];	
		i += Keyring->MD5dlen;
		sha_hash := a[i:i+Keyring->SHA1dlen];	
		i += Keyring->SHA1dlen;
		if(i != len a) {
			e = "finished: unexpected message";
			break;
		}
		m = ref Handshake.Finished(md5_hash, sha_hash);

	* =>
		e = "unknown message";
	}

	if(e != nil)
		return (nil, "Handshake decode: " + e);

	return (m, nil);
}

Handshake.encode(hm: self ref Handshake): (array of byte, string)
{
	a : array of byte;
	n : int;
	e : string;

	i := 0;
	pick m := hm {
	HelloRequest =>
		a = array [4] of byte;
		a[i++] = byte SSL_HANDSHAKE_HELLO_REQUEST;
		a[i:] = int_encode(n, 3);
		i += 3;
		if(i != 4)
			e = "hello request: wrong message length";

        ClientHello =>
		lsi := len m.session_id;
		lcs := len m.suites;
		if((lcs &1) || lcs < 2) {
			e = "client hello: cipher suites is not multiple of 2 bytes";
			break;
		}
		lcm := len m.compressions;
		n = 38 + lsi + lcs + lcm; # 2+32+1+2+1
		a = array[n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_CLIENT_HELLO;
		a[i:] = int_encode(n, 3);
		i += 3;
		a[i:] = m.version;
		i += 2;
		a[i:] = m.random;
		i += 32;
		a[i++] = byte lsi;
		if(lsi != 0) {
			a[i:] = m.session_id;	
			i += lsi;
		}
		a[i:] = int_encode(lcs, 2);		
		i += 2;
		a[i:] = m.suites; # not nil
		i += lcs;
		a[i++] = byte lcm;
		a[i:] = m.compressions;	# not nil	
		i += lcm;
		if(i != n+4)
			e = "client hello: wrong message length";

        ServerHello =>
		lsi := len m.session_id;
		n = 38 + lsi; # 2+32+1+2+1
		a = array [n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_SERVER_HELLO;
		a[i:] = int_encode(n, 3);		
		i += 3;
		a[i:] = m.version;		
		i += 2;
		a[i:] = m.random;			
		i += 32;
		a[i++] = byte lsi;
		if(lsi != 0) {
			a[i:] = m.session_id;			
			i += lsi;
		}
		a[i:] = m.suite; # should be verified, not nil
		i += 2;
		a[i++] = m.compression; # should be verified, not nil
		if(i != n+4)
			e = "server hello: wrong message length";

        Certificate =>
		cl := m.cert_list;
		while(cl != nil) {
			n += 3 + len hd cl;
			cl = tl cl;
		}
		a = array [n+7] of byte; 
		a[i++] = byte SSL_HANDSHAKE_CERTIFICATE;
		a[i:] = int_encode(n+3, 3); # length of record		
		i += 3;
		a[i:] = int_encode(n, 3); # total length of cert chain
		i += 3;
		cl = m.cert_list;
		while(cl != nil) {
			a[i:] = int_encode(len hd cl, 3); 
			i += 3;
			a[i:] = hd cl;			
			i += len hd cl;
			cl = tl cl;
		} 
		if(i != n+7)
			e = "certificate: wrong message length";

        ServerKeyExchange =>
		n = len m.xkey;
		a = array [n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_SERVER_KEY_EXCHANGE;
		a[i:] = int_encode(n, 3);		
		i += 3;
		a[i:] = m.xkey;		
		i += len m.xkey;
		if(i != n+4)
			e = "server key exchange: wrong message length";
		
        CertificateRequest =>
		ntypes := len m.cert_types;
		nauths := len m.dn_list;
		n = 1 + ntypes;
		dl := m.dn_list;
		while(dl != nil) {
			n += 2 + len hd dl;			
			dl = tl dl;
		}
		n += 2;	
		a = array [n+4] of byte;
		a[i++] =  byte SSL_HANDSHAKE_CERTIFICATE_REQUEST;
		a[i:] = int_encode(n, 3);		
		i += 3;
		a[i++] = byte ntypes;
		a[i:] = m.cert_types;		
		i += ntypes;
		a[i:] = int_encode(nauths, 2);		
		i += 2;
		dl = m.dn_list;
		while(dl != nil) {
			a[i:] = int_encode(len hd dl, 2); 
			i += 2;
			a[i:] = hd dl;			
			i += len hd dl;
			dl = tl dl;
		}
		if(i != n+4)
			e = "certificate request: wrong message length";
		
        ServerHelloDone =>
		n = 0;
		a = array[n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_SERVER_HELLO_DONE;
		a[i:] = int_encode(0, 3); # message has 0 length
		i += 3;
		if(i != n+4)
			e = "server hello done: wrong message length";

        CertificateVerify =>
		n = 2 + len m.signature;
		a = array [n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_CERTIFICATE_VERIFY;
		a[i:] = int_encode(n, 3);		
		i += 3;
		a[i:] = int_encode(n-2, 2);		
		i += 2;
		a[i:] = m.signature;			
		i += n-2;
		if(i != n+4)
			e = "certificate verify: wrong message length";

        ClientKeyExchange =>
		n = len m.xkey;
		a = array [n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_CLIENT_KEY_EXCHANGE;
		a[i:] = int_encode(n, 3);		
		i += 3;
		a[i:] = m.xkey;		
		i += n;
		if(i != n+4)
			e = "client key exchange: wrong message length";

        Finished =>
		n = len m.md5_hash + len m.sha_hash;
		a = array [n+4] of byte;
		a[i++] = byte SSL_HANDSHAKE_FINISHED;    
		a[i:] = int_encode(n, 3);
		i += 3;
		a[i:] = m.md5_hash;			
		i += len m.md5_hash;
		a[i:] = m.sha_hash;			
		i += len m.sha_hash;
		if(i != n+4)
			e = "finished: wrong message length";

	* =>
		e = "unknown message";
	}
	
	if(e != nil)
		return (nil, "Handshake encode: " + e);

	return (a, e);
}

Handshake.tostring(handshake: self ref Handshake): string
{
	info: string;

	pick m := handshake {
        HelloRequest =>
		info = "\tHelloRequest\n"; 

        ClientHello =>
		info = "\tClientHello\n" + 
			"\tversion = \n\t\t" + bastr(m.version) + "\n" +
			"\trandom = \n\t\t" + bastr(m.random) + "\n" +
			"\tsession_id = \n\t\t" + bastr(m.session_id) + "\n" +
			"\tsuites = \n\t\t" + bastr(m.suites) + "\n" +
			"\tcomperssion_methods = \n\t\t" + bastr(m.compressions) +"\n";

        ServerHello =>
		info = "\tServerHello\n" + 
			"\tversion = \n\t\t" + bastr(m.version) + "\n" +
			"\trandom = \n\t\t" + bastr(m.random) + "\n" +
			"\tsession_id = \n\t\t" + bastr(m.session_id) + "\n" +
			"\tsuite = \n\t\t" + bastr(m.suite) + "\n" +
			"\tcomperssion_method = \n\t\t" + string m.compression +"\n";

        Certificate =>
		info = "\tCertificate\n" + 
			"\tcert_list = \n\t\t" + lbastr(m.cert_list) + "\n";

        ServerKeyExchange =>
		info = "\tServerKeyExchange\n" +
			"\txkey = \n\t\t" + bastr(m.xkey) +"\n";

        CertificateRequest =>
		info = "\tCertificateRequest\n" +
			"\tcert_types = \n\t\t" + bastr(m.cert_types) + "\n" +
			"\tdn_list = \n\t\t" + lbastr(m.dn_list) + "\n";

        ServerHelloDone =>
		info = "\tServerDone\n";

        CertificateVerify =>
		info = "\tCertificateVerify\n" +
			"\tsignature = \n\t\t" + bastr(m.signature) + "\n"; 

        ClientKeyExchange =>
		info = "\tClientKeyExchange\n" +
			"\txkey = \n\t\t" + bastr(m.xkey) +"\n";

        Finished =>
		info = "\tFinished\n" +
			"\tmd5_hash = \n\t\t" + bastr(m.md5_hash) + "\n" +
			"\tsha_hash = \n\t\t" + bastr(m.sha_hash) + "\n";
	}

	return info;
}

Alert.tostring(alert: self ref Alert): string
{
	info: string;

	case alert.level {
	SSL_WARNING =>				
		info += "\t\twarning: ";

	SSL_FATAL =>				
		info += "\t\tfatal: ";

	*  =>
		info += sys->sprint("unknown alert level[%d]: ", alert.level);
	}

	case alert.description {
	SSL_CLOSE_NOTIFY => 			
		info += "close notify";

	SSL_NO_CERTIFICATE => 			
		info += "no certificate";

	SSL_BAD_CERTIFICATE => 			
		info += "bad certificate";

	SSL_UNSUPPORTED_CERTIFICATE => 		
		info += "unsupported certificate";

	SSL_CERTIFICATE_REVOKED => 		
		info += "certificate revoked";

	SSL_CERTIFICATE_EXPIRED =>		
		info += "certificate expired";

	SSL_CERTIFICATE_UNKNOWN =>		
		info += "certificate unknown";

	SSL_UNEXPECTED_MESSAGE =>		
		info += "unexpected message";

	SSL_BAD_RECORD_MAC =>	 		
		info += "bad record mac";

	SSL_DECOMPRESSION_FAILURE => 		
		info += "decompression failure";

	SSL_HANDSHAKE_FAILURE => 		
		info += "handshake failure";

	SSL_ILLEGAL_PARAMETER => 		
		info += "illegal parameter";

	* =>
		info += sys->sprint("unknown alert description[%d]", alert.description);
	}

	return info;
}

find_cipher_suite(s, suites: array of byte) : array of byte
{
	i, j : int;
	a, b : array of byte;

	n := len s;
	if((n & 1) || n < 2)
		return nil;

	m := len suites;
	if((m & 1) || m < 2)
		return nil;

	for(i = 0; i < n; ) {
		a = s[i:i+2];
		i += 2;
		for(j = 0; j < m; ) {
			b = suites[j:j+2];
			j += 2;
			if(a[0] == b[0] && a[1] == b[1]) 
				return b;
		}
	}

	return nil;
}

#
# cipher suites and specs
#
suite_to_spec(cs: array of byte, cipher_suites: array of array of byte) 
	: (ref CipherSpec, ref KeyExAlg, ref SigAlg, string)
{
	cip : ref CipherSpec;
	kex : ref KeyExAlg;
	sig : ref SigAlg;

	n := len cipher_suites;
	i : int;
	found := array [2] of byte;
	for(i = 0; i < n; i++) {
		found = cipher_suites[i];
		if(found[0]==cs[0] && found[1]==cs[1]) break;
	}

	if(i == n)
		return (nil, nil, nil, "fail to find a matched spec");

	case i {
	NULL_WITH_NULL_NULL =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_NULL_CIPHER, 
			SSL_STREAM_CIPHER, 0, 0, SSL_NULL_MAC, 0);
		kex = ref KeyExAlg.NULL();
		sig = ref SigAlg.anon();

	RSA_WITH_NULL_MD5 => # sign only certificate
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_NULL_CIPHER, 
			SSL_STREAM_CIPHER, 0, 0, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_WITH_NULL_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_NULL_CIPHER, 
			SSL_STREAM_CIPHER, 0, 0, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_EXPORT_WITH_RC4_40_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_RC4, 
			SSL_STREAM_CIPHER, 5, 0, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_WITH_RC4_128_MD5 => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC4, 
			SSL_STREAM_CIPHER, 16, 0, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_WITH_RC4_128_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC4, 
			SSL_STREAM_CIPHER, 16, 0, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_EXPORT_WITH_RC2_CBC_40_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_RC2_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	RSA_WITH_IDEA_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_IDEA_CBC,
			SSL_BLOCK_CIPHER, 16, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_EXPORT_WITH_DES40_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	RSA_WITH_DES_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	RSA_WITH_3DES_EDE_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.RSA(nil, nil, nil);
		sig = ref SigAlg.anon();

	DH_DSS_EXPORT_WITH_DES40_CBC_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DH_DSS_WITH_DES_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DH_DSS_WITH_3DES_EDE_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DH_RSA_EXPORT_WITH_DES40_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DH_RSA_WITH_DES_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_STREAM_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DH_RSA_WITH_3DES_EDE_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DHE_DSS_EXPORT_WITH_DES40_CBC_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DHE_DSS_WITH_DES_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DHE_DSS_WITH_3DES_EDE_CBC_SHA => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.DSS(nil, nil);

	DHE_RSA_EXPORT_WITH_DES40_CBC_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DHE_RSA_WITH_DES_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DHE_RSA_WITH_3DES_EDE_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.RSA(nil, nil);

	DH_anon_EXPORT_WITH_RC4_40_MD5 => 
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_RC4, 
			SSL_STREAM_CIPHER, 5, 0, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.anon();

	DH_anon_WITH_RC4_128_MD5 => 
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC4, 
			SSL_STREAM_CIPHER, 16, 0, SSL_MD5, Keyring->MD5dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.anon();

	DH_anon_EXPORT_WITH_DES40_CBC_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 5, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.anon();

	DH_anon_WITH_DES_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, 
			SSL_BLOCK_CIPHER, 8, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.anon();

	DH_anon_WITH_3DES_EDE_CBC_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, 
			SSL_BLOCK_CIPHER, 24, 8, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.DH(nil, nil, nil, nil, nil);
		sig = ref SigAlg.anon();

	FORTEZZA_KEA_WITH_NULL_SHA => 	
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_NULL_CIPHER, 
			SSL_STREAM_CIPHER, 0, 0, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.FORTEZZA_KEA();
		sig = ref SigAlg.FORTEZZA_KEA();

	FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_FORTEZZA_CBC, 
			SSL_BLOCK_CIPHER, 0, 0, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.FORTEZZA_KEA();
		sig = ref SigAlg.FORTEZZA_KEA();

	FORTEZZA_KEA_WITH_RC4_128_SHA =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC4, 
			SSL_STREAM_CIPHER, 16, 0, SSL_SHA, Keyring->SHA1dlen);
		kex = ref KeyExAlg.FORTEZZA_KEA();
		sig = ref SigAlg.FORTEZZA_KEA();

	}

	return (cip, kex, sig, nil);
}

#
# use suites as default SSL3_Suites
#
cipher_suite_info(cs: array of byte, suites: array of array of byte) : string
{
	tag : string;

	a := array [2] of byte;
	n := len suites;
	for(i := 0; i < n; i++) {
		a = suites[i];
		if(a[0]==cs[0] && a[1]==cs[1]) break;
	}

	if(i == n)
		return "unknown cipher suite [" + string cs + "]";

	case i {
	NULL_WITH_NULL_NULL => 		
		tag = "NULL_WITH_NULL_NULL";

	RSA_WITH_NULL_MD5 => 		
		tag = "RSA_WITH_NULL_MD5";

	RSA_WITH_NULL_SHA => 		
		tag = "RSA_WITH_NULL_SHA";

	RSA_EXPORT_WITH_RC4_40_MD5 => 	
		tag = "RSA_EXPORT_WITH_RC4_40_MD5";

	RSA_WITH_RC4_128_MD5 => 		
		tag = "RSA_WITH_RC4_128_MD5"; 	

	RSA_WITH_RC4_128_SHA => 		
		tag = "RSA_WITH_RC4_128_SHA";

	RSA_EXPORT_WITH_RC2_CBC_40_MD5 => 	
		tag = "RSA_EXPORT_WITH_RC2_CBC_40_MD5";

	RSA_WITH_IDEA_CBC_SHA => 		
		tag = "RSA_WITH_IDEA_CBC_SHA";

	RSA_EXPORT_WITH_DES40_CBC_SHA => 	
		tag ="RSA_EXPORT_WITH_DES40_CBC_SHA";

	RSA_WITH_DES_CBC_SHA =>		
		tag = "RSA_WITH_DES_CBC_SHA";

	RSA_WITH_3DES_EDE_CBC_SHA => 	
		tag = "RSA_WITH_3DES_EDE_CBC_SHA";

	DH_DSS_EXPORT_WITH_DES40_CBC_SHA => 
		tag = "DH_DSS_EXPORT_WITH_DES40_CBC_SHA";

	DH_DSS_WITH_DES_CBC_SHA => 		
		tag = "DH_DSS_WITH_DES_CBC_SHA";

	DH_DSS_WITH_3DES_EDE_CBC_SHA => 	
		tag = "DH_DSS_WITH_3DES_EDE_CBC_SHA";

	DH_RSA_EXPORT_WITH_DES40_CBC_SHA => 
		tag = "DH_RSA_EXPORT_WITH_DES40_CBC_SHA";

	DH_RSA_WITH_DES_CBC_SHA => 		
		tag = "DH_RSA_WITH_DES_CBC_SHA";

	DH_RSA_WITH_3DES_EDE_CBC_SHA => 	
		tag = "DH_RSA_WITH_3DES_EDE_CBC_SHA";

	DHE_DSS_EXPORT_WITH_DES40_CBC_SHA => 
		tag = "DHE_DSS_EXPORT_WITH_DES40_CBC_SHA";

	DHE_DSS_WITH_DES_CBC_SHA => 	
		tag = "DHE_DSS_WITH_DES_CBC_SHA";

	DHE_DSS_WITH_3DES_EDE_CBC_SHA => 	
		tag = "DHE_DSS_WITH_3DES_EDE_CBC_SHA";

	DHE_RSA_EXPORT_WITH_DES40_CBC_SHA => 
		tag = "DHE_RSA_EXPORT_WITH_DES40_CBC_SHA";

	DHE_RSA_WITH_DES_CBC_SHA => 
		tag = "DHE_RSA_WITH_DES_CBC_SHA";

	DHE_RSA_WITH_3DES_EDE_CBC_SHA => 
		tag = "DHE_RSA_WITH_3DES_EDE_CBC_SHA";

	DH_anon_EXPORT_WITH_RC4_40_MD5 => 
		tag = "DH_anon_EXPORT_WITH_RC4_40_MD5";

	DH_anon_WITH_RC4_128_MD5 => 
		tag = "DH_anon_WITH_RC4_128_MD5";

	DH_anon_EXPORT_WITH_DES40_CBC_SHA => 
		tag = "DH_anon_EXPORT_WITH_DES40_CBC_SHA";

	DH_anon_WITH_DES_CBC_SHA => 
		tag = "DH_anon_WITH_DES_CBC_SHA";

	DH_anon_WITH_3DES_EDE_CBC_SHA => 
		tag = "DH_anon_WITH_3DES_EDE_CBC_SHA";

	FORTEZZA_KEA_WITH_NULL_SHA => 
		tag = "FORTEZZA_KEA_WITH_NULL_SHA";

	FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA => 
		tag = "FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA";

	FORTEZZA_KEA_WITH_RC4_128_SHA => 
		tag = "FORTEZZA_KEA_WITH_RC4_128_SHA";
	}

	return "cipher suite = [" + tag + "]";
}

#################################
## FOR SSLv2 BACKWARD COMPATIBLE
#################################

# Protocol Version Codes
SSL2_CLIENT_VERSION				:= array [] of {byte 0, byte 16r02};
SSL2_SERVER_VERSION				:= array [] of {byte 0, byte 16r02};

# Protocol Message Codes

SSL2_MT_ERROR,
	SSL2_MT_CLIENT_HELLO,
	SSL2_MT_CLIENT_MASTER_KEY,
	SSL2_MT_CLIENT_FINISHED,
	SSL2_MT_SERVER_HELLO,
	SSL2_MT_SERVER_VERIFY,
	SSL2_MT_SERVER_FINISHED,
	SSL2_MT_REQUEST_CERTIFICATE,
	SSL2_MT_CLIENT_CERTIFICATE		: con iota;

# Error Message Codes

SSL2_PE_NO_CIPHER				:= array [] of {byte 0, byte 16r01};
SSL2_PE_NO_CERTIFICATE				:= array [] of {byte 0, byte 16r02};
SSL2_PE_BAD_CERTIFICATE				:= array [] of {byte 0, byte 16r04};
SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE		:= array [] of {byte 0, byte 16r06};

# Cipher Kind Values

SSL2_CK_RC4_128_WITH_MD5,
	SSL2_CK_RC4_128_EXPORT40_WITH_MD5,
	SSL2_CK_RC2_CBC_128_CBC_WITH_MD5,
	SSL2_CK_RC2_CBC_128_CBC_EXPORT40_WITH_MD5,
	SSL2_CK_IDEA_128_CBC_WITH_MD5,
	SSL2_CK_DES_64_CBC_WITH_MD5,
	SSL2_CK_DES_192_EDE3_CBC_WITH_MD5 	: con iota;

SSL2_Cipher_Kinds := array [] of {
	SSL2_CK_RC4_128_WITH_MD5 => 		array [] of {byte 16r01, byte 0, byte 16r80},
	SSL2_CK_RC4_128_EXPORT40_WITH_MD5 => 	array [] of {byte 16r02, byte 0, byte 16r80},
	SSL2_CK_RC2_CBC_128_CBC_WITH_MD5 => 	array [] of {byte 16r03, byte 0, byte 16r80},
	SSL2_CK_RC2_CBC_128_CBC_EXPORT40_WITH_MD5 =>
						array [] of {byte 16r04, byte 0, byte 16r80},
	SSL2_CK_IDEA_128_CBC_WITH_MD5 => 	array [] of {byte 16r05, byte 0, byte 16r80},
	SSL2_CK_DES_64_CBC_WITH_MD5 => 		array [] of {byte 16r06, byte 0, byte 16r40},
	SSL2_CK_DES_192_EDE3_CBC_WITH_MD5 => 	array [] of {byte 16r07, byte 0, byte 16rC0},
};

# Certificate Type Codes

SSL2_CT_X509_CERTIFICATE			: con 16r01; # encode as one byte

# Authentication Type Codes

SSL2_AT_MD5_WITH_RSA_ENCRYPTION			: con byte 16r01;

# Upper/Lower Bounds

SSL2_MAX_MASTER_KEY_LENGTH_IN_BITS		: con 256;
SSL2_MAX_SESSION_ID_LENGTH_IN_BYTES		: con 16;
SSL2_MIN_RSA_MODULUS_LENGTH_IN_BYTES		: con 64;
SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER		: con 32767;
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER		: con 16383;

# Handshake Internal State

SSL2_STATE_CLIENT_HELLO,
	SSL2_STATE_SERVER_HELLO,
	SSL2_STATE_CLIENT_MASTER_KEY,	
	SSL2_STATE_SERVER_VERIFY,
	SSL2_STATE_REQUEST_CERTIFICATE,
	SSL2_STATE_CLIENT_CERTIFICATE,
	SSL2_STATE_CLIENT_FINISHED,
	SSL2_STATE_SERVER_FINISHED,		
	SSL2_STATE_ERROR			: con iota;

# The client's challenge to the server for the server to identify itself is a 
# (near) arbitary length random. The v3 server will right justify the challenge 
# data to become the ClientHello.random data (padding with leading zeros, if 
# necessary). If the length of the challenge is greater than 32 bytes, then only
# the last 32 bytes are used. It is legitimate (but not necessary) for a v3 
# server to reject a v2 ClientHello that has fewer than 16 bytes of challenge 
# data.

SSL2_CHALLENGE_LENGTH				: con 16;

V2Handshake: adt {
	pick {
	Error =>
		code				: array of byte; # [2];
	ClientHello =>
		version				: array of byte; # [2]
		cipher_specs			: array of byte; # [3] x
		session_id			: array of byte;
		challenge			: array of byte;
	ServerHello =>
		session_id_hit			: int;
		certificate_type		: int;
		version				: array of byte; # [2]
		certificate			: array of byte; # only user certificate
		cipher_specs			: array of byte; # [3] x
		connection_id			: array of byte;
	ClientMasterKey =>
		cipher_kind			: array of byte; # [3]
		clear_key			: array of byte;
		encrypt_key			: array of byte;
		key_arg				: array of byte;
	ServerVerify =>
		challenge			: array of byte;
	RequestCertificate =>
		authentication_type		: int;
		certificate_challenge		: array of byte;
	ClientCertificate =>
		certificate_type		: int;
		certificate			: array of byte; # only user certificate
		response			: array of byte;
	ClientFinished =>
		connection_id			: array of byte;
	ServerFinished =>
		session_id			: array of byte;
	}  

	encode: fn(hm: self ref V2Handshake): (array of byte, string);
	decode: fn(a: array of byte): (ref V2Handshake, string);
	tostring: fn(h: self ref V2Handshake): string;
};


V2Handshake.tostring(handshake: self ref V2Handshake): string
{
	info := "";

	pick m := handshake {
        ClientHello =>
		info += "\tClientHello\n" + 
			"\tversion = \n\t\t" + bastr(m.version) + "\n" +
			"\tcipher_specs = \n\t\t" + bastr(m.cipher_specs) + "\n" +
			"\tsession_id = \n\t\t" + bastr(m.session_id) + "\n" +
			"\tchallenge = \n\t\t" + bastr(m.challenge) + "\n";

        ServerHello =>
		info += "\tServerHello\n" + 
			"\tsession_id_hit = \n\t\t" + string m.session_id_hit + "\n" +
			"\tcertificate_type = \n\t\t" + string m.certificate_type + "\n" +
			"\tversion = \n\t\t" + bastr(m.version) + "\n" +
			"\tcertificate = \n\t\t" + bastr(m.certificate) + "\n" +
			"\tcipher_specs = \n\t\t" + bastr(m.cipher_specs) + "\n" +
			"\tconnection_id = \n\t\t" + bastr(m.connection_id) + "\n";

	ClientMasterKey =>
		info += "\tClientMasterKey\n" +
			"\tcipher_kind = \n\t\t" + bastr(m.cipher_kind) + "\n" +
			"\tclear_key = \n\t\t" + bastr(m.clear_key) + "\n" +
			"\tencrypt_key = \n\t\t" + bastr(m.encrypt_key) + "\n" +
			"\tkey_arg = \n\t\t" + bastr(m.key_arg) + "\n";

	ServerVerify =>
		info += "\tServerVerify\n" + 
			"\tchallenge = \n\t\t" + bastr(m.challenge) + "\n";

	RequestCertificate =>
		info += "\tRequestCertificate\n" +
			"\tauthentication_type = \n\t\t" + string m.authentication_type + "\n" +
			"\tcertificate_challenge = \n\t\t" + bastr(m.certificate_challenge) + "\n";

	ClientCertificate =>
		info += "ClientCertificate\n" +
			"\tcertificate_type = \n\t\t" + string m.certificate_type + "\n" +
			"\tcertificate = \n\t\t" + bastr(m.certificate) + "\n" +
			"\tresponse = \n\t\t" + bastr(m.response) + "\n";

	ClientFinished =>
		info += "\tClientFinished\n" +
			"\tconnection_id = \n\t\t" + bastr(m.connection_id) + "\n";

	ServerFinished =>
		info += "\tServerFinished\n" +
			"\tsession_id = \n\t\t" + bastr(m.session_id) + "\n";
	}

	return info;
}


# v2 handshake protocol - message driven, v2 and v3 sharing the same context stack

do_v2handshake(v2hs: ref V2Handshake, ctx: ref Context): string
{
	e: string = nil;

	pick h := v2hs {
	Error =>
		do_v2error(h, ctx);

	ClientHello =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_CLIENT_HELLO) {
			e = "V2ClientHello";
			break;
		}
		do_v2client_hello(h, ctx);

	ServerHello =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_SERVER_HELLO) {
			e = "V2ServerHello";
			break;
		}
		do_v2server_hello(h, ctx);

	ClientMasterKey =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_CLIENT_MASTER_KEY) {
			e = "V2ClientMasterKey";
			break;
		}
		do_v2client_master_key(h, ctx);

	ServerVerify =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_SERVER_VERIFY) {
			e = "V2ServerVerify";
			break;
		}
		do_v2server_verify(h, ctx);
		
	RequestCertificate =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_SERVER_VERIFY) {
			e = "V2RequestCertificate";
			break;
		}
		do_v2req_cert(h, ctx);

	ClientCertificate =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_CLIENT_CERTIFICATE) {
			e = "V2ClientCertificate";
			break;
		}
		do_v2client_certificate(h, ctx);

	ClientFinished =>
		if((ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_CLIENT_FINISHED) {
			e = "V2ClientFinished";
			break;
		}
		do_v2client_finished(h, ctx);

	ServerFinished =>
		if(!(ctx.status & CLIENT_SIDE) || ctx.state != SSL2_STATE_SERVER_FINISHED) {
			e = "V2ServerFinished";
			break;
		}
		do_v2server_finished(h, ctx);
	}

	return e;
}

do_v2error(v2hs: ref V2Handshake.Error, ctx: ref Context)
{
	if(SSL_DEBUG)
		log("do_v2error: " + string v2hs.code);
	ctx.state = STATE_EXIT;
}

# [server side]
do_v2client_hello(v2hs: ref V2Handshake.ClientHello, ctx: ref Context)
{
	if(v2hs.version[0] != SSL2_CLIENT_VERSION[0] || v2hs.version[1] != SSL2_CLIENT_VERSION[1]) {
		# promote this message to v3 handshake protocol
		ctx.state = STATE_CLIENT_HELLO;
		return;
	}
	
	# trying to resume
	s: ref Session;
	if((v2hs.session_id != nil) && (ctx.status & SESSION_RESUMABLE))
		s = sslsession->get_session_byid(v2hs.session_id);
	if(s != nil) { # found a hit
		# prepare and send v2 handshake hello message
		v2handshake_enque(
			ref V2Handshake.ServerHello(
				1, # hit found
				0, # no certificate required
				SSL2_SERVER_VERSION, 
				nil, # no authetication required
				s.suite, # use hit session cipher kind
				ctx.server_random # connection_id
			),
			ctx
		);
		# TODO: should in supported cipher_kinds
		err: string;
		(ctx.sel_ciph, ctx.sel_keyx, ctx.sel_sign, err) 
			= v2suite_to_spec(ctx.session.suite, SSL2_Cipher_Kinds);
		if(err != "") {
			if(SSL_DEBUG)
				log("do_v2client_hello: " + err);
			ctx.state = SSL2_STATE_ERROR;
			return;
		}			
		ctx.state = SSL2_STATE_SERVER_FINISHED;
	}
	else {
		# find matching cipher kinds
		n := len v2hs.cipher_specs;
		matchs := array [n] of byte; 
		j, k: int = 0;
		while(j < n) {
			# ignore those not in SSL2_Cipher_Kinds
			matchs[k:] = v2hs.cipher_specs[j:j+3];
			for(i := 0; i < len SSL2_Cipher_Kinds; i++) {
				ck := SSL2_Cipher_Kinds[i];
				if(matchs[k] == ck[0] && matchs[k+1] == ck[1] && matchs[k+2] == ck[2])
					k +=3;
			}
			j += 3;
		}
		if(k == 0) {
			if(SSL_DEBUG)
				log("do_v2client_hello: No matching cipher kind");
			ctx.state = SSL2_STATE_ERROR;
		}
		else {
			matchs = matchs[0:k];

			# Note: 
			#	v2 challenge -> v3 client_random
			#	v2 connection_id -> v3 server_random

			chlen := len v2hs.challenge;
			if(chlen > 32)
				chlen = 32;
			ctx.client_random = array [chlen] of byte;
			if(chlen > 32)
				ctx.client_random[0:] = v2hs.challenge[chlen-32:];
			else
				ctx.client_random[0:] = v2hs.challenge;
			ctx.server_random = random->randombuf(Random->NotQuiteRandom, 16);
			s.session_id = random->randombuf (
					Random->NotQuiteRandom, 
					SSL2_MAX_SESSION_ID_LENGTH_IN_BYTES
				);
			s.suite = matchs;
			ctx.session = s;
			v2handshake_enque(
				ref V2Handshake.ServerHello(
					0, # no hit - not resumable
					SSL2_CT_X509_CERTIFICATE, 
					SSL2_SERVER_VERSION, 
					hd ctx.local_info.certs, # the first is user certificate
					ctx.session.suite, # matched cipher kinds
					ctx.server_random # connection_id
				),
				ctx
			);
			ctx.state = SSL2_STATE_CLIENT_MASTER_KEY;
		}
	}
}

# [client side]

do_v2server_hello(v2hs: ref V2Handshake.ServerHello, ctx: ref Context)
{
	# must be v2 server hello otherwise it will be v3 server hello
	# determined by auto record layer version detection
	if(v2hs.version[0] != SSL2_SERVER_VERSION[0] 
		|| v2hs.version[1] != SSL2_SERVER_VERSION[1]) {
		if(SSL_DEBUG)
			log("do_v2server_hello: not a v2 version");
		ctx.state = SSL2_STATE_ERROR;
		return;
	}

	ctx.session.version = SSL2_SERVER_VERSION;
	ctx.server_random = v2hs.connection_id;

	# check if a resumable session is found
	if(v2hs.session_id_hit != 0) { # resume ok
		err: string;
		# TODO: should in supported cipher_kinds
		(ctx.sel_ciph, nil, nil, err) = v2suite_to_spec(ctx.session.suite, SSL2_Cipher_Kinds);
		if(err !=  "") {
			if(SSL_DEBUG)
				log("do_v2server_hello: " + err);
			ctx.state = SSL2_STATE_ERROR;
			return;
		}
	}
	else { 	# not resumable session

		# use the first matched cipher kind; install cipher spec
		if(len v2hs.cipher_specs < 3) {
			if(SSL_DEBUG)
				log("do_v2server_hello: too few bytes");
			ctx.state = SSL2_STATE_ERROR;
			return;
		}
		ctx.session.suite = array [3] of byte;
		ctx.session.suite[0:] = v2hs.cipher_specs[0:3];
		err: string;
		(ctx.sel_ciph, nil, nil, err) = v2suite_to_spec(ctx.session.suite, SSL2_Cipher_Kinds);
		if(err != "") {
			if(SSL_DEBUG)
				log("do_v2server_hello: " + err);
			return;
		}
			
		# decode x509 certificates, authenticate server and extract 
		# public key from server certificate
		if(v2hs.certificate_type != int SSL2_CT_X509_CERTIFICATE) {
			if(SSL_DEBUG)
				log("do_v2server_hello: not x509 certificate");
			ctx.state = SSL2_STATE_ERROR;
			return;
		}
		ctx.session.peer_certs = v2hs.certificate :: nil;
		# TODO: decode v2hs.certificate as list of certificate
		# 	verify the list of certificate
		(e, signed) := x509->Signed.decode(v2hs.certificate);
		if(e != "") {
			if(SSL_DEBUG)
				log("do_v2server_hello: " + e);
			ctx.state = SSL2_STATE_ERROR;
			return;
		}
		certificate: ref Certificate;
		(e, certificate) = x509->Certificate.decode(signed.tobe_signed);
		if(e != "") {
			if(SSL_DEBUG)
				log("do_v2server_hello: " + e);
			ctx.state = SSL2_STATE_ERROR;
			return;
		}		
		id: int;
		peer_pk: ref X509->PublicKey;
		(e, id, peer_pk) = certificate.subject_pkinfo.getPublicKey();
		if(e != nil) {
			ctx.state = SSL2_STATE_ERROR; # protocol error
			return;
		}
		pk: ref RSAKey;
		pick key := peer_pk {
		RSA =>
			pk = key.pk;
		* =>
		}
		# prepare and send client master key message
		# TODO: change CipherSpec adt for more key info
		# Temporary solution
		# mkey (master key), ckey (clear key), skey(secret key)
		mkey, ckey, skey, keyarg: array of byte;
		(mkeylen, ckeylen, keyarglen) := v2suite_more(ctx.sel_ciph);
		mkey = random->randombuf(Random->NotQuiteRandom, mkeylen);
		if(ckeylen != 0)
			ckey = mkey[0:ckeylen];
		if(mkeylen > ckeylen)
			skey = mkey[ckeylen:];
		if(keyarglen > 0)
			keyarg = random->randombuf(Random->NotQuiteRandom, keyarglen);
		ekey: array of byte;
		(e, ekey) = pkcs->rsa_encrypt(skey, pk, 2);
		if(e != nil) {
			if(SSL_DEBUG)
				log("do_v2server_hello: " + e);
			ctx.state = SSL2_STATE_ERROR;	
			return;
		}
		ctx.session.master_secret = mkey;
		v2handshake_enque(
			ref V2Handshake.ClientMasterKey(ctx.session.suite, ckey, ekey, keyarg),
			ctx
		);
	}

	# clean up out_queue before switch cipher
	record_write_queue(ctx);
	ctx.out_queue.data = nil;

	# install keys onto ctx that will be pushed on ssl record when ready
	(ctx.cw_mac, ctx.sw_mac, ctx.cw_key, ctx.sw_key, ctx.cw_IV, ctx.sw_IV)
		= v2calc_keys(ctx.sel_ciph, ctx.session.master_secret, 
		ctx.client_random, ctx.server_random);
	e := set_queues(ctx);
	if(e != "") {
		if(SSL_DEBUG)
			log("do_v2server_finished: " + e);
		ctx.state = SSL2_STATE_ERROR;
		return;
	}
	ctx.status |= IN_READY;
	ctx.status |= OUT_READY;

	# prepare and send client finished message
	v2handshake_enque(
		ref V2Handshake.ClientFinished(ctx.server_random), # as connection_id
		ctx
	);

	ctx.state = SSL2_STATE_SERVER_VERIFY;
}

# [server side]

do_v2client_master_key(v2hs: ref V2Handshake.ClientMasterKey, ctx: ref Context)
{
	#if(cmk.cipher == -1 || cipher_info[cmk.cipher].cryptalg == -1) {
	#	# return ("protocol error: bad cipher in masterkey", nullc);
	#	ctx.state = SSL2_STATE_ERROR; # protocol error
	#	return;
	#}

	ctx.session.suite = v2hs.cipher_kind;

	# TODO:
	#	someplace shall be able to install the key
	# need further encapsulate encrypt and decrypt functions from KeyExAlg adt
	master_key_length: int;
	secret_key: array of byte;
	pick alg := ctx.sel_keyx {
	RSA =>
		e: string;
		(e, secret_key) = pkcs->rsa_decrypt(v2hs.encrypt_key, alg.sk, 0);
		if(e != "") {
			if(SSL_DEBUG)
				log("do_v2client_master_key: " + e);
			ctx.state = SSL2_STATE_ERROR;
			return;
		}
		master_key_length = len v2hs.clear_key + len secret_key;
	* =>
		if(SSL_DEBUG)
			log("do_v2client_master_key: unknown public key algorithm");
		ctx.state = SSL2_STATE_ERROR;
		return;
	}
	#TODO: do the following lines after modifying the CipherSpec adt
	#if(master_key_length != ci.keylen) {
	#	ctx.state = SSL2_STATE_ERROR; # protocol error
	#	return;
	#}

	ctx.session.master_secret = array [master_key_length] of byte;
	ctx.session.master_secret[0:] = v2hs.clear_key;
	ctx.session.master_secret[len v2hs.clear_key:] = secret_key;

	# install keys onto ctx that will be pushed on ssl record when ready
	(ctx.cw_mac, ctx.sw_mac, ctx.cw_key, ctx.sw_key, ctx.cw_IV, ctx.sw_IV)
		= v2calc_keys(ctx.sel_ciph, ctx.session.master_secret, 
		ctx.client_random, ctx.server_random);
	v2handshake_enque(
		ref V2Handshake.ServerVerify(ctx.client_random[16:]),
		ctx
	);
	v2handshake_enque(
		ref V2Handshake.ServerFinished(ctx.session.session_id),
		ctx
	);
	ctx.state = SSL2_STATE_CLIENT_FINISHED;
}

# used by client side
do_v2server_verify(v2hs: ref V2Handshake.ServerVerify, ctx: ref Context)
{
	# TODO:
	#	the challenge length may not be 16 bytes
	if(bytes_cmp(v2hs.challenge, ctx.client_random[32-SSL2_CHALLENGE_LENGTH:]) < 0) {
		if(SSL_DEBUG)
			log("do_v2server_verify: challenge mismatch");
		ctx.state = SSL2_STATE_ERROR;
		return;
	}

	ctx.state = SSL2_STATE_SERVER_FINISHED;
}

# [client side]

do_v2req_cert(v2hs: ref V2Handshake.RequestCertificate, ctx: ref Context)
{
	# not supported until v3
	if(SSL_DEBUG)
		log("do_v2req_cert: authenticate client not supported");
	v2hs = nil;
	ctx.state = SSL2_STATE_ERROR;
}

# [server side]

do_v2client_certificate(v2hs: ref V2Handshake.ClientCertificate, ctx: ref Context)
{
	# not supported until v3
	if(SSL_DEBUG)
		log("do_v2client_certificate: authenticate client not supported");
	v2handshake_enque (
		ref V2Handshake.Error(SSL2_PE_NO_CERTIFICATE),
		ctx
	);
	v2hs = nil;
	ctx.state = SSL2_STATE_ERROR;
}

# [server side]

do_v2client_finished(v2hs: ref V2Handshake.ClientFinished, ctx: ref Context)
{
	if(bytes_cmp(ctx.server_random, v2hs.connection_id) < 0) {
		ctx.session.session_id = nil;
		if(SSL_DEBUG)
			log("do_v2client_finished: connection id mismatch");
		ctx.state = SSL2_STATE_ERROR;
	}
	# TODO:
	#	the challenge length may not be 16 bytes
	v2handshake_enque(
		ref V2Handshake.ServerVerify(ctx.client_random[32-SSL2_CHALLENGE_LENGTH:]),
		ctx
	);
	if(ctx.session.session_id == nil)
		ctx.session.session_id = random->randombuf(Random->NotQuiteRandom, 16);
	v2handshake_enque(
		ref V2Handshake.ServerFinished(ctx.session.session_id),
		ctx
	);
	e := set_queues(ctx);
	if(e != "") {
		if(SSL_DEBUG)
			log("do_v2client_finished: " + e);
		ctx.state = SSL2_STATE_ERROR;
		return;
	}
	ctx.status |= IN_READY;
	ctx.status |= OUT_READY;
	sslsession->add_session(ctx.session);

	ctx.state = STATE_EXIT;
}

# [client side]

do_v2server_finished(v2hs: ref V2Handshake.ServerFinished, ctx: ref Context)
{
	if(ctx.session.session_id == nil)
		ctx.session.session_id = array [16] of byte;
	ctx.session.session_id[0:] = v2hs.session_id[0:];

	sslsession->add_session(ctx.session);

	ctx.state = STATE_EXIT;
}


# Note:
#	the key partitioning for v2 is different from v3

v2calc_keys(ciph: ref CipherSpec, ms, cr, sr: array of byte)
	: (array of byte, array of byte, array of byte, array of byte, array of byte, array of byte)
{
	cw_mac, sw_mac, cw_key, sw_key,	cw_IV, sw_IV: array of byte;

	# TODO: check the size of key block if IV exists
	(mkeylen, ckeylen, keyarglen) := v2suite_more(ciph);
	kblen := 2*mkeylen;
	if(kblen%Keyring->MD5dlen != 0) {
		if(SSL_DEBUG)
			log("v2calc_keys: key block length is not multiple of MD5 hash length");
	}
	else {
		key_block := array [kblen] of byte;

		challenge := cr[32-SSL2_CHALLENGE_LENGTH:32]; # TODO: if challenge length != 16 ?
		connection_id := sr[0:16]; # TODO: if connection_id length != 16 ?
		var := array [1] of byte;
		var[0] = byte 16r30;
		i := 0;
		while(i < kblen) {
			(hash, nil) := md5_hash(ms::var::challenge::connection_id::nil, nil);
			key_block[i:] = hash;
			i += Keyring->MD5dlen;
			++var[0];
		}

		if(SSL_DEBUG)
			log("ssl3: calc_keys:" 
			+ "\n\tmaster key = \n\t\t" + bastr(ms)
			+ "\n\tchallenge = \n\t\t" + bastr(challenge)
			+ "\n\tconnection id = \n\t\t" + bastr(connection_id)
			+ "\n\tkey block = \n\t\t" + bastr(key_block) + "\n");

		i = 0;
		# server write key == client read key
		# server write mac == server write key
		sw_key = array [mkeylen] of byte;
		sw_key[0:] = key_block[i:mkeylen];
		sw_mac = array [mkeylen] of byte;
		sw_mac[0:] = key_block[i:mkeylen];
		# client write key == server read key
		# client write mac == client write key
		i += mkeylen;
		cw_key = array [mkeylen] of byte;
		cw_key[0:] = key_block[i:i+mkeylen];
		cw_mac = array [mkeylen] of byte;
		cw_mac[0:] = key_block[i:i+mkeylen];
		# client IV == server IV
		# Note:
		#	IV is a part of writing or reading key for ssl device
		#	this is composed again in setctl
		cw_IV = array [keyarglen] of byte;
		cw_IV[0:] = ms[mkeylen:mkeylen+keyarglen];
		sw_IV = array [keyarglen] of byte;
		sw_IV[0:] = ms[mkeylen:mkeylen+keyarglen];
	}

	if(SSL_DEBUG)
		log("ssl3: calc_keys:" 
		+ "\n\tclient_write_mac = \n\t\t" + bastr(cw_mac)
		+ "\n\tserver_write_mac = \n\t\t" + bastr(sw_mac)
		+ "\n\tclient_write_key = \n\t\t" + bastr(cw_key)
		+ "\n\tserver_write_key = \n\t\t" + bastr(sw_key)
 		+ "\n\tclient_write_IV  = \n\t\t" + bastr(cw_IV)
		+ "\n\tserver_write_IV = \n\t\t" + bastr(sw_IV) + "\n");

	return (cw_mac, sw_mac, cw_key, sw_key, cw_IV, sw_IV);
}

v3tov2specs(suites: array of byte): array of byte
{
	# v3 suite codes are 2 bytes each, v2 codes are 3 bytes
	n := len suites / 2;
	kinds := array [n*3*2] of byte;
	k := 0;
	for(i := 0; i < n;) {
		a := suites[i:i+2];
		i += 2;
		m := len SSL3_Suites;
		for(j := 0; j < m; j++) {
			b := SSL3_Suites[j]; 
			if(a[0]==b[0] && a[1]==b[1]) 
				break;
		}
		if (j == m) {
			if(SSL_DEBUG)
				log("ssl3: unknown v3 suite");
			continue;
		}
		case j {
		RSA_EXPORT_WITH_RC4_40_MD5 => 	
			kinds[k:] = SSL2_Cipher_Kinds[SSL2_CK_RC4_128_EXPORT40_WITH_MD5];
			k += 3;
		RSA_WITH_RC4_128_MD5 => 		
			kinds[k:] = SSL2_Cipher_Kinds[SSL2_CK_RC4_128_WITH_MD5];
			k += 3;
		RSA_WITH_IDEA_CBC_SHA =>
			kinds[k:] = SSL2_Cipher_Kinds[SSL2_CK_IDEA_128_CBC_WITH_MD5];
			k += 3;
		RSA_WITH_DES_CBC_SHA =>
			;
		* =>
			if(SSL_DEBUG)
				log("ssl3: unable to convert v3 suite to v2 kind");
		}
		# append v3 code in v2-safe manner
		# (suite[0] == 0) => will be ignored by v2 server, picked up by v3 server
		kinds[k] = byte 16r00;
		kinds[k+1:] = SSL3_Suites[j];
		k += 3;
	}
	return kinds[0:k];
}

v2suite_to_spec(cs: array of byte, cipher_kinds: array of array of byte)
	: (ref CipherSpec, ref KeyExAlg, ref SigAlg, string)
{
	cip : ref CipherSpec;
	kex : ref KeyExAlg;
	sig : ref SigAlg;

	n := len cipher_kinds;
	for(i := 0; i < n; i++) {
		found := cipher_kinds[i];
		if(found[0]==cs[0] && found[1]==cs[1] && found[2]==cs[2]) break;
	}

	if(i == n)
		return (nil, nil, nil, "fail to find a matched spec");

	case i {
	SSL2_CK_RC4_128_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC4, SSL_STREAM_CIPHER, 
				16, 0, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_RC4_128_EXPORT40_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_RC4, SSL_STREAM_CIPHER, 
				5, 0, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_RC2_CBC_128_CBC_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_RC2_CBC, SSL_BLOCK_CIPHER, 
				16, 8, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_RC2_CBC_128_CBC_EXPORT40_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_TRUE, SSL_RC2_CBC, SSL_BLOCK_CIPHER, 
				5, 8, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_IDEA_128_CBC_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_IDEA_CBC, SSL_BLOCK_CIPHER, 
				16, 8, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_DES_64_CBC_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_DES_CBC, SSL_BLOCK_CIPHER, 
				8, 8, SSL_MD5, Keyring->MD4dlen);

	SSL2_CK_DES_192_EDE3_CBC_WITH_MD5 =>
		cip = ref CipherSpec(SSL_EXPORT_FALSE, SSL_3DES_EDE_CBC, SSL_BLOCK_CIPHER, 
				24, 8, SSL_MD5, Keyring->MD4dlen);
	}

	kex = ref KeyExAlg.RSA(nil, nil, nil);
	sig = ref SigAlg.RSA(nil, nil);

	return (cip, kex, sig, nil);
}

v2suite_more(ciph: ref CipherSpec): (int, int, int)
{
	mkeylen, ckeylen, keyarglen: int;

	case ciph.bulk_cipher_algorithm {
	SSL_RC4 =>
		mkeylen = 16;
		if(ciph.key_material == 5)
			ckeylen = 16 - 5;
		else
			ckeylen = 0;
		keyarglen = 0;
		
	SSL_RC2_CBC =>
		mkeylen = 16;
		if(ciph.key_material == 5)
			ckeylen = 16 - 5;
		else
			ckeylen = 0;
		keyarglen = 8;

	SSL_IDEA_CBC =>
		mkeylen = 16;
		ckeylen = 0;
		keyarglen = 8;

	SSL_DES_CBC =>
		mkeylen = 8;
		if(ciph.key_material == 5)
			ckeylen = 8 - 5;
		else
			ckeylen = 0;
		keyarglen = 8;

	SSL_3DES_EDE_CBC =>
		mkeylen = 24;
		ckeylen = 0;
		keyarglen = 8;
	}

	return (mkeylen, ckeylen, keyarglen);
}

v2handshake_enque(h: ref V2Handshake, ctx: ref Context)
{
	p := ref Protocol.pV2Handshake(h);

	protocol_write(p, ctx);
}

V2Handshake.encode(hm: self ref V2Handshake): (array of byte, string)
{
	a : array of byte;
	n : int;
	e : string;

	i := 0;
	pick m := hm {
	Error =>
		n = 3;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_ERROR;
		a[i:] = m.code;

	ClientHello =>
		specslen := len m.cipher_specs;
		sidlen := len m.session_id;
		challen := len m.challenge;
		n = 9+specslen + sidlen + challen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_CLIENT_HELLO;
		a[i:] = m.version;
		i += 2;
		a[i:] = int_encode(specslen, 2);
		i += 2;
		a[i:] = int_encode(sidlen, 2);
		i += 2;
		a[i:] = int_encode(challen, 2);
		i += 2;
		a[i:] = m.cipher_specs;
		i += specslen;
		if(sidlen != 0) {
			a[i:] = m.session_id;
			i += sidlen;
		}
		if(challen != 0) {
			a[i:] = m.challenge;
			i += challen;
		}	

	ServerHello =>
		# use only the user certificate
		certlen := len m.certificate;
#		specslen := 3*len m.cipher_specs;
		specslen := len m.cipher_specs;
		cidlen := len m.connection_id;
		n = 11 + certlen + specslen + cidlen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_SERVER_HELLO;
		a[i++] = byte m.session_id_hit;
		a[i++] = byte m.certificate_type;
		a[i:] = m.version;
		i += 2;
		a[i:] = int_encode(certlen, 2);
		i += 2;
		a[i:] = int_encode(specslen, 2);
		i += 2;
		a[i:] = int_encode(cidlen, 2);
		i += 2;
		a[i:] = m.certificate;		
		i += certlen;
		a[i:] = m.cipher_specs;
		i += specslen;
		a[i:] = m.connection_id;
		i += cidlen;

	ClientMasterKey =>
		ckeylen := len m.clear_key;
		ekeylen := len m.encrypt_key;
		karglen := len m.key_arg;
		n = 10 + ckeylen + ekeylen + karglen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_CLIENT_MASTER_KEY;
		a[i:] = m.cipher_kind;
		i += 3;
		a[i:] = int_encode(ckeylen, 2);
		i += 2;
		a[i:] = int_encode(ekeylen, 2);
		i += 2;
		a[i:] = int_encode(karglen, 2);
		i += 2;
		a[i:] = m.clear_key;
		i += ckeylen;
		a[i:] = m.encrypt_key;
		i += ekeylen;
		a[i:] = m.key_arg;
		i += karglen;

	ServerVerify =>
		challen := len m.challenge;
		n = 1 + challen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_SERVER_VERIFY;
		a[i:] = m.challenge;

	RequestCertificate =>
		cclen := len m.certificate_challenge;
		n = 2 + cclen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_REQUEST_CERTIFICATE;
		a[i++] = byte m.authentication_type;
		a[i:] = m.certificate_challenge;
		i += cclen;

	ClientCertificate =>
		# use only the user certificate
		certlen := len m.certificate;
		resplen := len m.response;
		n = 6 + certlen + resplen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_CLIENT_CERTIFICATE;
		a[i++] = byte m.certificate_type;
		a[i:] = int_encode(certlen, 2);
		i += 2;
		a[i:] = int_encode(resplen, 2);
		i += 2;
		a[i:] = m.certificate;
		i += certlen;
		a[i:] = m.response;
		i += resplen;

	ClientFinished =>
		cidlen := len m.connection_id;
		n = 1 + cidlen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_CLIENT_FINISHED;
		a[i:] = m.connection_id;
		i += cidlen;

	ServerFinished =>
		sidlen := len m.session_id;
		n = 1 + sidlen;
		a = array[n] of byte;
		a[i++] = byte SSL2_MT_SERVER_FINISHED;
		a[i:] = m.session_id;
		i += sidlen;
	}

	return (a, e);
}

V2Handshake.decode(a: array of byte): (ref V2Handshake, string)
{
	m : ref V2Handshake;
	e : string;

	n := len a;
	i := 1; 
	case int a[0] {
	SSL2_MT_ERROR =>
		if(n != 3)
			break;
		code := a[i:i+2];
		i += 2;
		m = ref V2Handshake.Error(code);

	SSL2_MT_CLIENT_HELLO =>
		if(n < 9) {
			e = "client hello: message too short";
			break;
		}
		ver := a[i:i+2];
		i += 2;
		specslen := int_decode(a[i:i+2]);
		i += 2;
		sidlen := int_decode(a[i:i+2]);
		i += 2;
		challen := int_decode(a[i:i+2]);
		i += 2;
		if(n != 9+specslen+sidlen+challen) {
			e = "client hello: length mismatch";
			break;
		}
		if(specslen%3 != 0) {
			e = "client hello: must multiple of 3 bytes";
			break;
		}
		specs: array of byte;
		if(specslen != 0) {
			specs = a[i:i+specslen];
			i += specslen;
		}
		sid: array of byte;
		if(sidlen != 0) {
			sid = a[i:i+sidlen];
			i += sidlen;
		}
		chal: array of byte;
		if(challen != 0) {
			chal = a[i:i+challen];
			i += challen;
		}
		m = ref V2Handshake.ClientHello(ver, specs, sid, chal);

	SSL2_MT_CLIENT_MASTER_KEY =>
		if(n < 10) {
			e = "client master key: message too short";
			break;
		}
		kind := a[i:i+3];
		i += 3;
		ckeylen := int_decode(a[i:i+2]);
		i += 2;
		ekeylen := int_decode(a[i:i+2]);
		i += 2;
		karglen := int_decode(a[i:i+2]);
		i += 2;
		if(n != 10 + ckeylen + ekeylen + karglen) {
			e = "client master key: length mismatch";
			break;
		}
		ckey := a[i:i+ckeylen];
		i += ckeylen;
		ekey := a[i:i+ekeylen];
		i += ekeylen;
		karg := a[i:i+karglen];
		i += karglen;
		m = ref V2Handshake.ClientMasterKey(kind, ckey, ekey, karg);

	SSL2_MT_CLIENT_FINISHED =>
		cid := a[i:n];
		i = n;
		m = ref V2Handshake.ClientFinished(cid);

	SSL2_MT_SERVER_HELLO =>
		if(n < 11) {
			e = "server hello: messsage too short";
			break;
		}
		sidhit := int a[i++];
		certtype := int a[i++];
		ver := a[i:i+2];
		i += 2;
		certlen := int_decode(a[i:i+2]);
		i += 2;
		specslen := int_decode(a[i:i+2]);
		i += 2;
		cidlen := int_decode(a[i:i+2]);
		i += 2;
		if(n != 11+certlen+specslen+cidlen) {
			e = "server hello: length mismatch";
			break;
		}
		cert := a[i:i+certlen];
		i += certlen;
		if(specslen%3 != 0) {
			e = "server hello: must be multiple of 3 bytes";
			break;
		}
		specs := a[i:i+specslen];
		i += specslen;
		if(cidlen < 16 || cidlen > 32) {
			e = "server hello: connection id length out of range";
			break;
		}
		cid := a[i:i+cidlen];
		i += cidlen;
		m = ref V2Handshake.ServerHello(sidhit, certtype, ver, cert, specs, cid);

	SSL2_MT_SERVER_VERIFY =>
		chal := a[i:n];
		i = n;
		m = ref V2Handshake.ServerVerify(chal);

	SSL2_MT_SERVER_FINISHED =>
		sid := a[i:n];
		m = ref V2Handshake.ServerFinished(sid);

	SSL2_MT_REQUEST_CERTIFICATE =>
		if(n < 2) {
			e = "request certificate: message too short";
			break;
		}
		authtype := int a[i++];
		certchal := a[i:n];
		i = n;
		m = ref V2Handshake.RequestCertificate(authtype, certchal);

	SSL2_MT_CLIENT_CERTIFICATE =>
		if(n < 6) {
			e = "client certificate: message too short";
			break;
		}
		certtype := int a[i++];
		certlen := int_decode(a[i:i+2]);
		i += 2;
		resplen := int_decode(a[i:i+2]);
		i += 2;
		if(n != 6+certlen+resplen) {
			e = "client certificate: length mismatch";
			break;
		}
		cert := a[i:i+certlen];
		i += certlen;
		resp := a[i:i+resplen];
		m = ref V2Handshake.ClientCertificate(certtype, cert, resp);

	* =>
		e = "unknown message [" + string a[0] + "]";
	}

	return (m, e);
}

# utilities

md5_hash(input: list of array of byte, md5_ds: ref DigestState): (array of byte, ref DigestState)
{
	hash_value := array [Keyring->MD5dlen] of byte;
	ds : ref DigestState;

	if(md5_ds != nil)
		ds = md5_ds.copy();

	lab := input;
	for(i := 0; i < len input - 1; i++) {
		ds = keyring->md5(hd lab, len hd lab, nil, ds);
		lab = tl lab;
	}
	ds = keyring->md5(hd lab, len hd lab, hash_value, ds);

	return (hash_value, ds);
}

sha_hash(input: list of array of byte, sha_ds: ref DigestState): (array of byte, ref DigestState)
{
	hash_value := array [Keyring->SHA1dlen] of byte;
	ds : ref DigestState;

	if(sha_ds != nil)
		ds = sha_ds.copy();

	lab := input;
	for(i := 0; i < len input - 1; i++) {
		ds = keyring->sha1(hd lab, len hd lab, nil, ds);
		lab = tl lab;
	}
	ds = keyring->sha1(hd lab, len hd lab, hash_value, ds);

	return (hash_value, ds);
}

md5_sha_hash(input: list of array of byte, md5_ds, sha_ds: ref DigestState)
	: (array of byte, ref DigestState, ref DigestState)
{
	buf := array [Keyring->MD5dlen+Keyring->SHA1dlen] of byte;

	(buf[0:], md5_ds) = md5_hash(input, md5_ds);
	(buf[Keyring->MD5dlen:], sha_ds) = sha_hash(input, sha_ds);

	return (buf, md5_ds, sha_ds);
}

int_decode(buf: array of byte): int
{
	val := 0;
	for(i := 0; i < len buf; i++)
		val = (val << 8) | (int buf[i]);

	return val;	
}

int_encode(value, length: int): array of byte
{
	buf := array [length] of byte;

	while(length--)	{   
		buf[length] = byte value;
		value >>= 8;
	}

	return buf;
}


bastr(a: array of byte) : string
{
	ans : string = "";

	for(i := 0; i < len a; i++) {
		if(i < len a - 1 && i != 0 && i%10 == 0)
			ans += "\n\t\t";
		if(i == len a -1)
			ans += sys->sprint("%2x", int a[i]);
		else
			ans += sys->sprint("%2x ", int a[i]);
	}

	return ans;
}

bbastr(a: array of array of byte) : string
{
	info := "";

	for(i := 0; i < len a; i++)
		info += bastr(a[i]);
	
	return info;
}

lbastr(a: list of array of byte) : string
{
	info := "";

	l := a;
	while(l != nil) {
		info += bastr(hd l) + "\n\t\t";
		l = tl l;
	}

	return info;
}

# need to fix (string a == string b)
bytes_cmp(a, b: array of byte): int
{
	if(len a != len b)
		return -1;

	n := len a;
	for(i := 0; i < n; i++) {
		if(a[i] != b[i])
			return -1;
	}

	return 0;
}

putn(a: array of byte, i, value, n: int): int
{
	j := n;
	while(j--) {   
		a[i+j] = byte value;
		value >>= 8;
	}
	return i+n;
}

INVALID_SUITE : con "invalid suite list";
ILLEGAL_SUITE : con "illegal suite list";

cksuites(suites : array of byte) : string
{
	m := len suites;
	if (m == 0 || (m&1))
		return INVALID_SUITE;
	n := len SSL3_Suites;
	ssl3s := array [2] of byte;
	for (j := 0; j < m; j += 2) {
		for( i := 0; i < n; i++) {
			ssl3s = SSL3_Suites[i];
			if(suites[j] == ssl3s[0] && suites[j+1] == ssl3s[1])
				break;
		}
		if (i == n)
			return ILLEGAL_SUITE;
	}
	return nil;
}