summaryrefslogtreecommitdiff
path: root/src/coolkey/slot.cpp
blob: b360f02812dbf06df6b85af1101d49d04032cbc0 (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
/* ***** BEGIN COPYRIGHT BLOCK *****
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation version
 * 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * ***** END COPYRIGHT BLOCK *****/

#include <string>
#include "mypkcs11.h"
#include <stdio.h>
#include <assert.h>
#include "log.h"
#include "PKCS11Exception.h"
#include <winscard.h>
#include "slot.h"
#include "zlib.h"
#include "params.h"

#include "machdep.h"

#define MIN(x, y) ((x) < (y) ? (x) : (y))



#ifdef DEBUG
#define PRINTF(args) printf args
#else
#define PRINTF(args)
#endif
// #define DISPLAY_WHOLE_GET_DATA 1


// The Cyberflex Access 32k egate ATR
const CKYByte ATR[] =
{ 0x3b, 0x75, 0x94, 0x00, 0x00, 0x62, 0x02, 0x02, 0x02, 0x01 };
const CKYByte ATR1[] =
{ 0x3b, 0x75, 0x94, 0x00, 0x00, 0x62, 0x02, 0x02, 0x03, 0x01 };
const CKYByte ATR3[] = 
{ 0x3b, 0x76, 0x94, 0x00, 0x00, 0xff, 0x62, 0x76, 0x01, 0x00, 0x00 };
/* RSA SecurID */
const CKYByte ATR2[] = 
{  0x3B, 0x6F, 0x00, 0xFF, 0x52, 0x53, 0x41, 0x53, 0x65, 0x63, 0x75, 0x72,
   0x49, 0x44, 0x28, 0x52, 0x29, 0x31, 0x30 };

SlotList::SlotList(Log *log_) : log(log_)
{
    // initialize things to NULL so we can recover from an exception
    slots = NULL;
    numSlots = 0;
    readerStates = NULL;
    numReaders = 0;
    context = NULL;
    shuttingDown  = FALSE;

    try {

        context = CKYCardContext_Create(SCARD_SCOPE_USER);
        if( context == NULL) {
            throw PKCS11Exception(CKR_GENERAL_ERROR,
                "Failed to create card context\n");
        }
	updateSlotList();
    } catch( PKCS11Exception &) {
        CKYCardContext_Destroy(context);
	if (readerStates) {
	    CKYReader_DestroyArray(readerStates, numReaders);
	}
        throw;
    }
}

SlotList::~SlotList()
{
    if( slots ) {
        assert( numSlots > 0 );
        for( unsigned int i=0; i < numSlots; ++i ) {
            delete slots[i];
        }
        delete [] slots;
        slots = NULL;
        numSlots = 0;
    }
    if (readerStates) {
	CKYReader_DestroyArray(readerStates, numReaders);
	readerStates = NULL;
        numReaders = 0;
    }
    if (context) {
	CKYCardContext_Destroy(context);
 	context = NULL;
    }
}
void
SlotList::shutdown()
{
   shuttingDown = TRUE;
   CKYCardContext_Cancel(context);
}

void
SlotList::updateSlotList()
{
    Slot **newSlots = NULL;
    Slot **oldSlots = NULL;

    readerListLock.getLock();

    updateReaderList();

    if (numSlots == numReaders) {
        readerListLock.releaseLock();
	return;
    }
    assert(numSlots < numReaders);
    if (numSlots > numReaders) {
        readerListLock.releaseLock();
	throw PKCS11Exception(CKR_GENERAL_ERROR,
			"Reader and slot count inconsistant\n");
    }

    try {
	newSlots = new Slot*[numReaders];
        if (newSlots == NULL ) 
	    throw PKCS11Exception(CKR_HOST_MEMORY);
	memset(newSlots, 0, numReaders*sizeof(Slot*));

        memcpy(newSlots, slots, sizeof(slots[0]) * numSlots);

	for (unsigned int i=numSlots; i < numReaders; i++) {
	    newSlots[i] = new
		Slot(CKYReader_GetReaderName(&readerStates[i]), log, context);
	}

	oldSlots = slots;
	slots = newSlots;  // update the pointer first 
	numSlots = numReaders; // now update the count 
	if (oldSlots) {    // ok we can free the old value now
	    delete [] oldSlots;
	}
    } catch( PKCS11Exception &) {
        // Recover by deleting everything that was created.
        if( newSlots ) {
            assert(numSlots < numReaders );
            for( unsigned int i=numSlots; i < numReaders; ++i ) {
                if( newSlots[i] ) {
                    delete newSlots[i];
                }
            }
            delete [] newSlots;
        }
        readerListLock.releaseLock();
        throw;
    }
    readerListLock.releaseLock();
	
}

bool
SlotList::readerExists(const char *readerName, unsigned int *hint)
{
    unsigned int start = 0;
    unsigned int i;

    if (hint && (*hint < numReaders)) {
	start = *hint;
    }

    /*
     * We use 'hint' as a way of deciding where to
     * start. This way we can handle the normal case where the name list
     * and the readerState matches one for one with a single string compare.
     */ 
    for (i=start; i < numReaders; i++) {
	if (strcmp(CKYReader_GetReaderName(&readerStates[i]),readerName) == 0) {
	    if (hint) {
		*hint = i+1;
	    }
	    return TRUE;
	}
    }
    /* we guessed wrong, check the first part of the reader states */
    for (i=0; i < start; i++) {
	if (strcmp(CKYReader_GetReaderName(&readerStates[i]),readerName) == 0) {
	    if (hint) {
		*hint = i+1;
	    }
	    return TRUE;
	}
    }
    /* OK, we've found a genuinely new reader */
    return FALSE;
}

bool
SlotList::readerNameExistsInList(const char *readerName,CKYReaderNameList *readerNameList)
{
    if( !readerName || !readerNameList) {
        return FALSE;
    }

    int i = 0;
    int readerNameCnt = CKYReaderNameList_GetCount(*readerNameList);

    const char *curReaderName = NULL;
    for(i=0; i < readerNameCnt; i++) {
        curReaderName = CKYReaderNameList_GetValue(*readerNameList,i);

        if(!strcmp(curReaderName,readerName)) {
            return TRUE;
        }
        
    }
    
    return FALSE;
}

/*
 * you need to hold the ReaderList Lock before you can update the ReaderList
 */
#define MAX_READER_DELTA 4
void
SlotList::updateReaderList()
{
    CKYReaderNameList readerNames = NULL;

    CKYStatus status = CKYCardContext_ListReaders(context, &readerNames);
    if ( status != CKYSUCCESS ) {
	throw PKCS11Exception(CKR_GENERAL_ERROR,
                "Failed to list readers: 0x%x\n", 
				CKYCardContext_GetLastError(context));
    }

    if (!readerStates) {
	/* fresh Reader State list, just create it */
	readerStates = CKYReader_CreateArray(readerNames, (CKYSize *)&numReaders);

	/* if we have no readers, make sure we have at least one to keep things
	 * happy */
	if (readerStates == NULL &&
			 CKYReaderNameList_GetCount(readerNames) == 0) {
	    readerStates = (SCARD_READERSTATE *)
				malloc(sizeof(SCARD_READERSTATE));
	    if (readerStates) {
		CKYReader_Init(readerStates);
		status = CKYReader_SetReaderName(readerStates, "E-Gate 0 0");
		if (status != CKYSUCCESS) {
 		    CKYReader_DestroyArray(readerStates, 1);
		    readerStates = NULL;
		} else {
		    numReaders = 1;
		}
	    }
	}
	CKYReaderNameList_Destroy(readerNames);
	        
	if (readerStates == NULL) {
	    throw PKCS11Exception(CKR_HOST_MEMORY,
				"Failed to allocate ReaderStates\n");
	}
	return;
    }

    /* it would be tempting at this point just to see if we have more readers
     * then specified previously. The problem with this is it is possible that
     * some readers have been deleted, so the only way to tell if we have
     * new readers is to see if there are any readers on the list that we
     * don't recognize.
     */

    /* first though, let's check to see if any previously removed readers have 
     * come back from the dead. If the ignored bit has been set, we do not need
     * it any more.
    */

    const char *curReaderName = NULL;
    unsigned long knownState = 0;
    for(int ri = 0 ; ri < numReaders; ri ++)  {
       
        knownState = CKYReader_GetKnownState(&readerStates[ri]);
        if( !(knownState & SCARD_STATE_IGNORE))  {
            continue;
        }
 
        curReaderName =  CKYReader_GetReaderName(&readerStates[ri]); 
        if(readerNameExistsInList(curReaderName,&readerNames)) {
            CKYReader_SetKnownState(&readerStates[ri], knownState & ~SCARD_STATE_IGNORE); 
                 
        }
    } 

    const char *newReadersData[MAX_READER_DELTA];
    const char **newReaders = &newReadersData[0];
    unsigned int newReaderCount = 0;
    unsigned int hint = 0;

    try {
	CKYReaderNameIterator iter;

	for (iter = CKYReaderNameList_GetIterator(readerNames);
				!CKYReaderNameIterator_End(iter); 
				iter = CKYReaderNameIterator_Next(iter)) {
	    const char *thisReaderName = CKYReaderNameIterator_GetValue(iter);
	    if (!readerExists(thisReaderName, &hint)) {
		if (newReaderCount == MAX_READER_DELTA) {
		    /* oops, we overflowed our buffer, alloc a new one right 
		     * quick. This code is very unlikely, so it's not fast, 
		     * but it's  meant to keep working, even in this weird 
		     * condition. NOTE: it assumes that we can't have any
		     * more  new readers than candidate readers we are
		     * checking */
		    int maxReaders = CKYReaderNameList_GetCount(readerNames);
		    assert(maxReaders > MAX_READER_DELTA);
		    newReaders = new const char *[maxReaders]; 
		    if (!newReaders) {
			throw PKCS11Exception(CKR_HOST_MEMORY,
			   "Could allocate space for %d new readers\n", 
								maxReaders);
		    }
		    memcpy(newReaders, newReadersData, 
				MAX_READER_DELTA*sizeof(newReadersData[0]));
		}
		newReaders[newReaderCount++] = thisReaderName;
	    }
	}
	/* OK, we haven't added any new readers, blow out now */
	if (newReaderCount == 0) {
	    CKYReaderNameList_Destroy(readerNames);
	    return;
	}

	status = CKYReader_AppendArray(&readerStates, numReaders,
				newReaders, newReaderCount);
	if (status != CKYSUCCESS) {
	    throw PKCS11Exception(CKR_GENERAL_ERROR,
			"Couldn't append %d new reader states\n",
				newReaderCount);
	}
	numReaders += newReaderCount;

	CKYReaderNameList_Destroy(readerNames);
	/* free newReaders if w were forced to alloc it */
	if (newReaders != &newReadersData[0]) {
	    delete [] newReaders;
	}
	return;

    } catch( PKCS11Exception &) {
	CKYReaderNameList_Destroy(readerNames);
	/* free newReaders if w were forced to alloc it */
	if (newReaders != &newReadersData[0]) {
	    delete [] newReaders;
	}

        throw;
    }
}
    

Slot::Slot(const char *readerName_, Log *log_, CKYCardContext* context_)
    : log(log_), readerName(NULL), personName(NULL), manufacturer(NULL),
	slotInfoFound(false), context(context_), conn(NULL), state(UNKNOWN), 
	isVersion1Key(false), needLogin(false), fullTokenName(false), 
	mCoolkey(false),
#ifdef USE_SHMEM
	shmem(readerName_),
#endif
	sessionHandleCounter(1), objectHandleCounter(1)
{

  tokenFWVersion.major = 0;
  tokenFWVersion.minor = 0;


  try {
    conn = CKYCardConnection_Create(context);
    if( conn == 0 ) {
        throw PKCS11Exception(CKR_GENERAL_ERROR);
    }
    hwVersion.major = 255;
    hwVersion.minor = 255;

    //Initialize login state for both Version 1 keys and older keys
    reverify = false;
    nonceValid = false;
    loggedIn = false;
    pinCache.invalidate();
    pinCache.clearPin();
    //readSlotInfo();
    manufacturer = strdup("Unknown");
    if (!manufacturer) {
	throw PKCS11Exception(CKR_HOST_MEMORY);
    }
    readerName = strdup(readerName_);
    if (!readerName) {
	throw PKCS11Exception(CKR_HOST_MEMORY);
    }
    CKYStatus ret = CKYBuffer_InitFromLen(&nonce, NONCE_SIZE);
    if (ret != CKYSUCCESS) {
	throw PKCS11Exception(CKR_HOST_MEMORY);
    }
    CKYBuffer_InitEmpty(&cardATR);
    CKYBuffer_InitEmpty(&mCUID);
  } catch(PKCS11Exception &) {
	if (conn) {
	    CKYCardConnection_Destroy(conn);
	}
	if (manufacturer) {
	    free(manufacturer);
	}
	if (readerName) {
	    free(readerName);
	}
        throw;
  }
}

void
Slot::readSlotInfo(void)
{
#ifdef WIN32  /* Mac doesn't have the SCardGetAttrib function */
    CKYStatus status;
    CKYBuffer attrBuf;

    CKYBuffer_InitEmpty(&attrBuf);
    status = CKYCardConnection_GetAttribute(conn, 
			SCARD_ATTR_VENDOR_IFD_VERSION, &attrBuf);
    if (status == CKYSUCCESS) {
	const CKYByte *type = CKYBuffer_Data(&attrBuf);

	if (CKYBuffer_Size(&attrBuf) == sizeof(unsigned long)) {
	    /* buffer data is returned in machine order, not network or
	     * applet order */
	    unsigned long version = *(unsigned long *)type;
	    hwVersion.major = (CK_BYTE) (version >> 24) & 0xff;
	    hwVersion.minor = (CK_BYTE) (version >> 16) & 0xff;
	}
        status = CKYCardConnection_GetAttribute(conn, 
					SCARD_ATTR_VENDOR_NAME, &attrBuf);
	if (status == CKYSUCCESS) {
	    free(manufacturer);
	    /* make sure manufacturer is NULL terminated */
	    CKYBuffer_AppendChar(&attrBuf,0);
	    manufacturer = strdup((const char *)CKYBuffer_Data(&attrBuf));
	    slotInfoFound = true;
	} 
    } else {
	PRINTF(("readSlotInfo failed\n"));
    }
    CKYBuffer_FreeData(&attrBuf);
#endif  /* WIN32 */
}

Slot::~Slot()
{
    if (conn) {
	CKYCardConnection_Destroy(conn);
    }
    if (readerName) {
	free(readerName);
    }
    if (personName) {
	free(personName);
    }
    if (manufacturer) {
	free(manufacturer);
    }
    CKYBuffer_FreeData(&nonce);
    CKYBuffer_FreeData(&cardATR);
    CKYBuffer_FreeData(&mCUID);
}

template <class C>
class ArrayFreer {
  private:
    C *ptr;
  public:
    ArrayFreer(C* cptr) : ptr(cptr) { }
    ~ArrayFreer() {
        if( ptr ) {
            delete [] ptr;
        }
    }
    void release() { ptr = NULL; }
};

CK_RV
SlotList::getSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList,
         CK_ULONG_PTR pulCount) 
{
    CK_RV rv = CKR_OK;
    unsigned int i;

    if( pulCount == NULL ) {
        throw PKCS11Exception(CKR_ARGUMENTS_BAD);
    }

    if (pSlotList == NULL) {
        updateSlotList();
    }

    //
    // first, figure out which slots have tokens present
    //
    bool * tokenIsPresent = new bool[numSlots];
    if( tokenIsPresent == NULL ) {
        throw PKCS11Exception(CKR_HOST_MEMORY);
    }
    ArrayFreer<bool> deleteTokIsPres(tokenIsPresent);

    unsigned int numPresent = 0;
    for( i = 0; i < numSlots; ++i ) {
        tokenIsPresent[i] = slots[i]->isTokenPresent();
        numPresent += tokenIsPresent[i];
    }

    //
    // now fill in the slot list if it was supplied
    //
    if( pSlotList != NULL ) {
        if( tokenPresent ) {
            // only slots with tokens present
            if( *pulCount >= numPresent ) {
                // we have enough space to copy the slot IDs
                unsigned int j;
                for( i=0, j=0; i < numSlots; ++i ) {
                    if( tokenIsPresent[i] ) {
                        assert(j < numPresent);
                        pSlotList[j++] = slotIndexToID(i);
                    }
                }
                assert( j == numPresent );
            } else {
                // not enough space
                rv = CKR_BUFFER_TOO_SMALL;
            }
        } else {
            // all slots, even without tokens present
            if( *pulCount >= numSlots ) {
                // we have enough space to copy the slot IDs
                for( i=0; i < numSlots; ++i ) {
                    pSlotList[i] = slotIndexToID(i);
                }
            } else {
                // not enough space
                rv = CKR_BUFFER_TOO_SMALL;
            }
        }
    }

    // set the number of slots
    if( tokenPresent ) {
        *pulCount = numPresent;
    } else {
        *pulCount = numSlots;
    }

    return rv;
}

void
Slot::connectToToken()
{
    CKYStatus status = CKYSCARDERR;
    OSTime time = OSTimeNow();

    mCoolkey = 0;
    tokenFWVersion.major = 0;
    tokenFWVersion.minor = 0;

    // try to connect to the card
    if( ! CKYCardConnection_IsConnected(conn) ) {
        int i = 0;
    //for cranky readers try again a few more times
        while( i++ < 5 && status != CKYSUCCESS )
        {
            status = CKYCardConnection_Connect(conn, readerName);
            if( status != CKYSUCCESS && 
                CKYCardConnection_GetLastError(conn) == SCARD_E_PROTO_MISMATCH ) 
            {
                log->log("Unable to connect to token status %d ConnGetGetLastError %x .\n",status,CKYCardConnection_GetLastError(conn));

            }
            else
            {
                break;
            }
            OSSleep(100000);
        }

        if( status != CKYSUCCESS)
        {
            state = UNKNOWN;
            return;
        }
    }

    log->log("time connect: Connect Time %d ms\n", OSTimeNow() - time);
    if (!slotInfoFound) {
	readSlotInfo();
    }
    log->log("time connect: Read Slot %d ms\n", OSTimeNow() - time);

    // Get card state. See if it is present, and if the ATR matches
    unsigned long cardState;
    status = CKYCardConnection_GetStatus(conn, &cardState, &cardATR);
    if( status != CKYSUCCESS ) {
        disconnect();
        return;
    }
    log->log("time connect: connection status %d ms\n", OSTimeNow() - time);
    if( cardState & SCARD_PRESENT ) {
        state = CARD_PRESENT;
    }

    if (Params::hasParam("noAppletOK"))
    {      
        state |=  APPLET_SELECTABLE;
	mCoolkey = 1;
    }

    /* support CAC card. identify the card based on applets, not the ATRS */
    state |= ATR_MATCH;

    /* our production cards should "ALWAYS" have an applet, even if it
     * doesn't exit */
    if ( CKYBuffer_DataIsEqual(&cardATR, ATR3, sizeof (ATR3)) ) {
        state |= ATR_MATCH | APPLET_SELECTABLE;
	mCoolkey = 1;

    }

    Transaction trans;
    status = trans.begin(conn);

    /* CAC card are cranky after they are first inserted.
     *  don't continue until we can convince the tranaction to work */
    for (int count = 0; count < 10 && status == CKYSCARDERR 
       && CKYCardConnection_GetLastError(conn) == SCARD_W_RESET_CARD; count++) {
	log->log("CAC Card Reset detected retry %d: time %d ms\n", count,
		OSTimeNow() - time);
        CKYCardConnection_Disconnect(conn);
	OSSleep(100000); /* 100 ms */
        status = CKYCardConnection_Connect(conn, readerName);
	if (status != CKYSUCCESS) {
	   continue;
	}
	status = trans.begin(conn);
    }

    /* Can't get a transaction, give up */
    if (status != CKYSUCCESS) {
        log->log("Transaction Failed 0x%x\n", status);
	handleConnectionError();
    }

    // see if the applet is selectable

    log->log("time connnect: Begin transaction %d ms\n", OSTimeNow() - time);
    status = CKYApplet_SelectCoolKeyManager(conn, NULL);
    if (status != CKYSUCCESS) {
        log->log("CoolKey Select failed 0x%x\n", status);
	status = CACApplet_SelectPKI(conn, 0, NULL);
	if (status != CKYSUCCESS) {
            log->log("CAC Select failed 0x%x\n", status);
	    if (status == CKYSCARDERR) {
		log->log("CAC Card Failure 0x%x\n", 
			CKYCardConnection_GetLastError(conn));
		disconnect();
	    }
	    return;
	}
	state |= CAC_CARD | APPLET_SELECTABLE | APPLET_PERSONALIZED;
	/* skip the read of the cuid. We really don't need it and,
         * the only way to get it from the cac is to reset it.
         * other apps may be running now, so resetting the cac is a bit
         * unfriendly */
	isVersion1Key = 0;
	needLogin = 1;

	return;
    }
    mCoolkey = 1;
    log->log("time connect: Select Applet %d ms\n", OSTimeNow() - time);

    state |= APPLET_SELECTABLE;

    // now see if the applet is personalized
    CKYAppletRespGetLifeCycleV2 lifeCycleV2;
    status = CKYApplet_GetLifeCycleV2(conn, &lifeCycleV2, NULL);
    if (status != CKYSUCCESS) {
	if (status == CKYSCARDERR) {
	    disconnect();
	}
	return;
    }
    log->log("time connect: Get Personalization %d ms\n", OSTimeNow() - time);
    if (lifeCycleV2.lifeCycle == CKY_APPLICATION_PERSONALIZED )
    {
        state |= APPLET_PERSONALIZED;
    }
    isVersion1Key = (lifeCycleV2.protocolMajorVersion == 1);
    needLogin = (lifeCycleV2.pinCount != 0);
    tokenFWVersion.major = lifeCycleV2.protocolMajorVersion;
    tokenFWVersion.minor = lifeCycleV2.protocolMinorVersion;
}
    
bool
Slot::cardStateMayHaveChanged()
{
    CKYStatus status;

log->log("calling IsConnected\n");
    if( !CKYCardConnection_IsConnected(conn) ) {
        return true;
    }
log->log("IsConnected returned false\n");
    
    // If the card has been removed or reset, this call will fail.
    unsigned long cardState;
    CKYBuffer aid;
    CKYBuffer_InitEmpty(&aid);
    status = CKYCardConnection_GetStatus(conn, &cardState, &aid);
    CKYBuffer_FreeData(&aid);
    if( status != CKYSUCCESS ) {
        disconnect();
        return true;
    }
    return false;
}

void
Slot::invalidateLogin(bool hard)
{
    if (isVersion1Key) {
	if (hard) {
	    reverify = false; /* no need to revalidate in the future,
	                       * we're clearing the nonce now */
	    nonceValid = false;
	    CKYBuffer_Zero(&nonce);
	    CKYBuffer_Resize(&nonce,8);
	} else {
	    reverify = true;
	}
    } else {
	loggedIn = false;
	if (hard) {
	    pinCache.invalidate();
	    pinCache.clearPin();
	}
    }
}

void
Slot::disconnect()
{
    CKYCardConnection_Disconnect(conn);
    state = UNKNOWN;
    closeAllSessions();
    invalidateLogin(false);
}

void
Slot::refreshTokenState()
{
    if( cardStateMayHaveChanged() ) {
log->log("card changed\n");
	invalidateLogin(true);
        closeAllSessions();
	unloadObjects();
        connectToToken();


        if( state & APPLET_PERSONALIZED ) {
            try {
                loadObjects();
            } catch(PKCS11Exception&) {
                log->log("refreshTokenState: Failed to load objects.\n");
                unloadObjects();
            }
        } else if (state & APPLET_SELECTABLE) {
	    initEmpty();
	}

    }
}

bool
Slot::isTokenPresent()
{
    refreshTokenState();
    log->log("isTokenPresent, card state is 0x%x\n", state);
    return (state & APPLET_SELECTABLE) != 0;
}

CK_SESSION_HANDLE
makeSessionHandle(CK_SLOT_ID slotID, SessionHandleSuffix suffix)
{
    assert( (slotID & 0x000000ff) == slotID );
    return (slotID << 24) | suffix;
}

void
SlotList::decomposeSessionHandle(CK_SESSION_HANDLE hSession, CK_SLOT_ID& slotID,
    SessionHandleSuffix& suffix) const
{
    slotID = hSession >> 24;
    suffix = SessionHandleSuffix(hSession);
    try {
        validateSlotID(slotID);
    } catch(PKCS11Exception&) {
        log->log("Invalid slotID %d pulled from session handle 0x%08x\n",
            slotID, hSession);
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }
}

void
SlotList::openSession(Session::Type type, CK_SLOT_ID slotID,
    CK_SESSION_HANDLE_PTR phSession)
{
    validateSlotID(slotID);

    SessionHandleSuffix suffix = 
        slots[slotIDToIndex(slotID)]->openSession(type);

    *phSession = makeSessionHandle(slotID, suffix);
}

void
SlotList::closeSession(CK_SESSION_HANDLE hSession)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->closeSession(suffix);
}
    

SessionHandleSuffix
Slot::openSession(Session::Type type)
{
    ensureTokenPresent();
    return generateNewSession(type);
}

class SessionHandleSuffixMatch {
  private:
    SessionHandleSuffix suffix;
  public:
    explicit SessionHandleSuffixMatch(SessionHandleSuffix s) : suffix(s) { }
    bool operator()(const Session& session) {
        return session.getHandleSuffix() == suffix;
    }
};

bool
Slot::isValidSession(SessionHandleSuffix handleSuffix) const
{
    SessionConstIter iter;
    iter = findConstSession(handleSuffix);
    return (iter != sessions.end());
}

void
Slot::closeSession(SessionHandleSuffix handleSuffix)
{
    refreshTokenState();

    SessionIter iter;
    iter = findSession(handleSuffix);
    if( iter == sessions.end() )  {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID,
            "Invalid session handle suffix 0x%08x passed to closeSession\n",
                (unsigned long)handleSuffix);
    } else {
        log->log("Closed session 0x%08x\n", (unsigned long)handleSuffix);
        sessions.erase(iter);
    }
}

CK_RV
Slot::getSlotInfo(CK_SLOT_INFO_PTR pSlotInfo)
{
    static CK_VERSION firmwareVersion = {0,0};

    if( pSlotInfo == NULL ) {
        throw PKCS11Exception(CKR_ARGUMENTS_BAD);
    }
    pSlotInfo->flags = CKF_REMOVABLE_DEVICE | CKF_HW_SLOT;
    /*pSlotInfo->flags = CKF_REMOVABLE_DEVICE; */
    if( isTokenPresent() )
        pSlotInfo->flags |= CKF_TOKEN_PRESENT;
    memset(pSlotInfo->slotDescription, ' ', 64);
    memcpy(pSlotInfo->slotDescription, readerName,
        MIN(64, strlen(readerName)) );
    memset(pSlotInfo->manufacturerID, ' ', 32);
    memcpy(pSlotInfo->manufacturerID, manufacturer,
        MIN(32, strlen(manufacturer)) );
    pSlotInfo->hardwareVersion = hwVersion;
    pSlotInfo->firmwareVersion = firmwareVersion;

    return CKR_OK;
}

inline unsigned char 
hex(unsigned long digit) 
{
    return (digit > 9 )? (char)(digit+'a'-10) : (char)(digit+'0');
}

void
Slot::makeCUIDString(char *serialNumber, int maxSize,
						 const unsigned char *cuids)
{
    signed int i; // must be signed or for loop won't exit! 
    char *cp;

    memset(serialNumber, ' ', maxSize);
    // CUID is an 8 digit hex number with leading zeros.
    // we count down from 8 stripping hex digits. If there is not
    // enough space, we truncate the top digits 
    unsigned long cuid = 
	((unsigned long) cuids[6]) << 24 |
	((unsigned long) cuids[7]) << 16 |
	((unsigned long) cuids[8]) <<  8 |
		((unsigned long) cuids[9]) ;

    for (i = MIN(maxSize,8)-1, cp= serialNumber; i >= 0; 
						cp++, i--) {
	unsigned long digit = cuid >> (i*4);
	// if we truncated the beginning. show that with a '*' 
	*cp = (digit > 0xf) ? '*' : hex(digit);
	cuid -=  digit << (i*4);
    }
}


void
Slot::makeSerialString(char *serialNumber, int maxSize,
						 const unsigned char *cuid)
{
    memset(serialNumber, ' ', maxSize);

    // otherwise we use the eepromSerialNumber as a hex value 
    if (cuid) {
         makeCUIDString(serialNumber, maxSize, cuid);
    }
    return;
}

void
Slot::makeLabelString(char *label, int maxSize, const unsigned char *cuid)
{
    int personLen;
    memset(label, ' ', maxSize);
    if (fullTokenName) {
	personLen = strlen(personName);
	memcpy(label, personName, MIN(personLen, maxSize));
        // UTF8 Truncate fixup! don't drop halfway through a UTF8 character 
	return;
    }
    
// 
// Legacy tokens only 'speak' english.
//
#define COOLKEY "CoolKey"
#define POSSESSION " for "
    if (!personName || personName[0] == '\0' ) {
	const int coolKeySize = sizeof(COOLKEY) ;
	memcpy(label, COOLKEY, coolKeySize-1);
	makeSerialString(&label[coolKeySize], maxSize-coolKeySize, cuid);
	return;
    }
    const int prefixSize = sizeof (COOLKEY POSSESSION )-1;
    memcpy(label, COOLKEY POSSESSION, prefixSize);
    personLen = strlen(personName);
    memcpy(&label[prefixSize], personName, 
				MIN(personLen, maxSize-prefixSize));

}

void
Slot::makeModelString(char *model, int maxSize, const unsigned char *cuid)
{
    char *cp = model;
    memset(model, ' ', maxSize);
    assert(maxSize >= 8);

    if (!cuid) {
	return;
    }

    *cp++ = hex(cuid[2] >> 4);
    *cp++ = hex(cuid[2] & 0xf);
    *cp++ = hex(cuid[3] >> 4);
    *cp++ = hex(cuid[3] & 0xf);
    *cp++ = hex(cuid[4] >> 4);
    *cp++ = hex(cuid[4] & 0xf);
    *cp++ = hex(cuid[5] >> 4);
    *cp++ = hex(cuid[5] & 0xf);
    makeCUIDString(&model[8],maxSize -8, cuid);

    return;
}

struct _manList {
     unsigned short type;
     char *string;
};

static const struct _manList  manList[] = {
        { 0x4090, "Axalto" },
        { 0x2050, "Oberthur" },
        { 0x4780, "RSA" }
};

static int manListSize = sizeof(manList)/sizeof(manList[0]);

void
Slot::makeManufacturerString(char *man, int maxSize, const unsigned char *cuid)
{
    char *cp = man;
    memset(man, ' ', maxSize);

    if (!cuid) {
	return;
    }
    unsigned short fabricator = ((unsigned short)cuid[0]) << 8 | cuid[1];

    assert(maxSize >=4 );

     /* first give the raw manufacture ID for CUID calculations */
    *cp++ = hex(cuid[0] >> 4);
    *cp++ = hex(cuid[0] & 0xf);
    *cp++ = hex(cuid[1] >> 4);
    *cp++ = hex(cuid[1] & 0xf);
    cp++; /* leave a space */


    for (int i=0; i < manListSize; i++) {
	if (fabricator == manList[i].type) {
	    int len = strlen(manList[i].string);
	    memcpy(cp,manList[i].string, MIN(len,maxSize-5));
	    break;
	}
    }
    /* just leave the number bare if we don't recognize it */
}

CK_RV
Slot::getTokenInfo(CK_TOKEN_INFO_PTR pTokenInfo)
{
    if(pTokenInfo == NULL ) {
        throw PKCS11Exception(CKR_ARGUMENTS_BAD);
    }
    ensureTokenPresent();
    const unsigned char *cuid = CKYBuffer_Data(&mCUID);

    /// format the token string
    makeLabelString((char *)pTokenInfo->label, sizeof(pTokenInfo->label),cuid);
    makeSerialString((char *)pTokenInfo->serialNumber, 
				sizeof(pTokenInfo->serialNumber), cuid);
    makeModelString((char *)pTokenInfo->model, 
				sizeof(pTokenInfo->model), cuid);
    makeManufacturerString((char *)pTokenInfo->manufacturerID, 
				sizeof(pTokenInfo->manufacturerID), cuid);

    pTokenInfo->flags = CKF_WRITE_PROTECTED;
    if (state & APPLET_PERSONALIZED) {
	pTokenInfo->flags |=  CKF_TOKEN_INITIALIZED;
	if (needLogin) {
	    pTokenInfo->flags |= CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED;
	}
    }
    pTokenInfo->ulMaxSessionCount = CK_EFFECTIVELY_INFINITE;
    pTokenInfo->ulSessionCount = CK_UNAVAILABLE_INFORMATION;
    pTokenInfo->ulMaxRwSessionCount = 0;
    pTokenInfo->ulMaxPinLen = 32;
    pTokenInfo->ulMinPinLen = 0;
    pTokenInfo->ulTotalPublicMemory = publicTotal;
    pTokenInfo->ulFreePublicMemory = publicFree;
    pTokenInfo->ulTotalPrivateMemory = CK_EFFECTIVELY_INFINITE;
    pTokenInfo->ulFreePrivateMemory = privateFree;
    pTokenInfo->hardwareVersion.major = cuid ? cuid[4] : 0;
    pTokenInfo->hardwareVersion.minor = cuid ? cuid[5] : 0;
    pTokenInfo->firmwareVersion = tokenFWVersion;


    return CKR_OK;
}

void
SlotList::validateSlotID(CK_SLOT_ID slotID) const
{
    if( slotID < 1 || slotID > numSlots ) {
        throw PKCS11Exception(CKR_SLOT_ID_INVALID);
    }
}

#define PKCS11_WAIT_LATENCY 500 /* 500 msec or 1/2 sec */
#define PKCS11_CARD_ERROR_LATENCY 300
void
SlotList::waitForSlotEvent(CK_FLAGS flag, CK_SLOT_ID_PTR slotp, CK_VOID_PTR res)
{
    unsigned long timeout = (flag ==CKF_DONT_BLOCK) ? 0 : PKCS11_WAIT_LATENCY;
    unsigned int i;
    bool found = FALSE;
    CKYStatus status;
    SCARD_READERSTATE *myReaderStates = NULL;
    unsigned int myNumReaders = 0;
#ifndef notdef
    do {
	readerListLock.getLock();
	try {
	    updateReaderList();
	} catch(PKCS11Exception&) {
	    readerListLock.releaseLock();
	    if (myReaderStates) {
		delete [] myReaderStates;
	    }
	    throw;
	}

	if (myNumReaders != numReaders) {
	    if (myReaderStates) {
		delete [] myReaderStates;
	    } 
	    myReaderStates = new SCARD_READERSTATE [numReaders];
	}
	memcpy(myReaderStates, readerStates, 
				sizeof(SCARD_READERSTATE)*numReaders);
	myNumReaders = numReaders;
	readerListLock.releaseLock();
	status = CKYCardContext_WaitForStatusChange(context,
				 myReaderStates, myNumReaders, timeout);
	if (status == CKYSUCCESS) {
	    for (i=0; i < myNumReaders; i++) {
		SCARD_READERSTATE *rsp = &myReaderStates[i];
	        unsigned long eventState = CKYReader_GetEventState(rsp);
		if (eventState & SCARD_STATE_CHANGED) {
		    readerListLock.getLock();
		    CKYReader_SetKnownState(&readerStates[i], eventState & ~SCARD_STATE_CHANGED);
		    readerListLock.releaseLock();
		    *slotp = slotIndexToID(i);
		    found = TRUE;
		    break;
		}
	    }
	}

        if (found || (flag == CKF_DONT_BLOCK) || shuttingDown) {
            break;
        }

        #ifndef WIN32
        if (status != CKYSUCCESS) {

            if ( (CKYCardContext_GetLastError(context) ==
                                        SCARD_E_READER_UNAVAILABLE) ||
                (CKYCardContext_GetLastError(context) == SCARD_E_TIMEOUT))
            {
                OSSleep(timeout*PKCS11_CARD_ERROR_LATENCY);
            }


        }
        #endif
    } while ((status == CKYSUCCESS) ||
       (CKYCardContext_GetLastError(context) == SCARD_E_TIMEOUT) ||
        ( CKYCardContext_GetLastError(context) == SCARD_E_READER_UNAVAILABLE));
#else
    do {
	OSSleep(100);
    } while ((flag != CKF_DONT_BLOCK) && !shuttingDown);
#endif

    if (myReaderStates) {
	delete [] myReaderStates;
    }

    if (!found) {
	throw PKCS11Exception(CKR_NO_EVENT);
    }
    return;
}

void
Slot::handleConnectionError()
{
    long error = CKYCardConnection_GetLastError(conn);

    log->log("Connection Error = 0x%x\n", error);

    // Force a reconnect after a token operation fails. The most
    // common reason for it to fail is that it has been removed, but
    // it doesn't hurt to do it in other cases either (such as a reset).
    disconnect();

    // Convert the PCSC error to a PKCS #11 error, and throw the exception.
    CK_RV ckrv;
    switch( error ) {
      case SCARD_E_NO_SMARTCARD:
      case SCARD_W_RESET_CARD:
      case SCARD_W_REMOVED_CARD:
        ckrv = CKR_DEVICE_REMOVED;
        break;
      default:
        ckrv = CKR_DEVICE_ERROR;
        break;
    }
    throw PKCS11Exception(ckrv);
}

list<ListObjectInfo>
Slot::getObjectList()
{
    list<ListObjectInfo> objInfoList;

    while(true) {
	CKYISOStatus result;
        ListObjectInfo info;
        CKYByte seq = objInfoList.size() == 0  ? CKY_LIST_RESET : CKY_LIST_NEXT;
	CKYStatus status=CKYApplet_ListObjects(conn, seq,  &info.obj, &result);
	if (status != CKYSUCCESS) {
	    // we failed because of a connection error
	    if (status == CKYSCARDERR) {
		handleConnectionError();
	    }
	    // we failed simply because we hit the end of the list
	    // (in which case we are done)
	    if ((result == CKYISO_SUCCESS)  || (result == CKYISO_SEQUENCE_END)) {
		break;
	    }
	    // we failed fror some other reason...
  	    throw PKCS11Exception(CKR_DEVICE_ERROR);
	}

        log->log("===Object\n");
        log->log("===id: 0x%04x\n", info.obj.objectID);
        log->log("===size: %d\n", info.obj.objectSize);
        log->log("===acl: 0x%02x,0x%02x,0x%02x\n", info.obj.readACL,
				info.obj.writeACL, info.obj.deleteACL);
        log->log("\n");

        objInfoList.push_back(info);
    }

    return objInfoList;
}

// Should already have a transaction
void
Slot::selectApplet()
{
    CKYStatus status;
    status = CKYApplet_SelectCoolKeyManager(conn, NULL);
    if ( status == CKYSCARDERR ) handleConnectionError();
    if ( status != CKYSUCCESS) {
        // could not select applet: this just means it's not there
        disconnect();
        throw PKCS11Exception(CKR_DEVICE_REMOVED);
    }
}

void
Slot::selectCACApplet(CKYByte instance)
{
    CKYStatus status;
    status = CACApplet_SelectPKI(conn, instance, NULL);
    if ( status == CKYSCARDERR ) handleConnectionError();
    if ( status != CKYSUCCESS) {
        // could not select applet: this just means it's not there
        disconnect();
        throw PKCS11Exception(CKR_DEVICE_REMOVED);
    }
}
// assume we are already in a transaction
void
Slot::readMuscleObject(CKYBuffer *data, unsigned long objectID, 
							unsigned int objSize)
{
    CKYStatus status;

    status = CKYApplet_ReadObjectFull(conn, objectID, 0, objSize,
		getNonce(), data, NULL);
    if (status == CKYSCARDERR) { 
        handleConnectionError();
    }
    if (status != CKYSUCCESS) {
        throw PKCS11Exception(CKR_DEVICE_ERROR);
    }
    return;
}


class DERCertObjIDMatch {
  private:
    unsigned short certnum;
    const Slot      &slot;
  public:
    DERCertObjIDMatch(unsigned short cn, const Slot &s) : 
		certnum(cn), slot(s) { }

    bool operator()(const ListObjectInfo& info) {
        return  (slot.getObjectClass(info.obj.objectID) == 'C') 
		&& ( slot.getObjectIndex(info.obj.objectID) == certnum );
    }
};

class ObjectHandleMatch {
  private:
    CK_OBJECT_HANDLE handle;
  public:
    ObjectHandleMatch(CK_OBJECT_HANDLE handle_) : handle(handle_) { }
    bool operator()(const PKCS11Object& obj) {
        return obj.getHandle() == handle;
    }
};

class KeyNumMatch {
  private:
    CKYByte keyNum;
    const Slot &slot;
  public:
    KeyNumMatch(CKYByte keyNum_, const Slot &s) : keyNum(keyNum_), slot(s) { }
    bool operator() (const PKCS11Object& obj) {
        unsigned long objID = obj.getMuscleObjID();
        return (slot.getObjectClass(objID) == 'k')
               && (slot.getObjectIndex(objID) == keyNum);
    }
};

class ObjectCertCKAIDMatch {
  private:
    CKYByte cka_id;
  public:
    ObjectCertCKAIDMatch(CKYByte cka_id_) : cka_id(cka_id_) {}
    bool operator()(const PKCS11Object& obj) {
	const CKYBuffer *id;
        const CKYBuffer *objClass;
	CK_OBJECT_CLASS certClass = CKO_CERTIFICATE;
	objClass = obj.getAttribute(CKA_CLASS);
        if (objClass == NULL || !CKYBuffer_DataIsEqual(objClass, 
				(CKYByte *)&certClass, sizeof(certClass))) {
	    return false;
        }
 	id = obj.getAttribute(CKA_ID);
        return (id != NULL && CKYBuffer_DataIsEqual(id,&cka_id, 1))
						 ? true : false;
    }
};

CK_OBJECT_HANDLE
Slot::generateUnusedObjectHandle()
{
    CK_OBJECT_HANDLE handle;
    ObjectConstIter iter;
    do {
        handle = ++objectHandleCounter;
        iter = find_if(tokenObjects.begin(), tokenObjects.end(),
            ObjectHandleMatch(handle));
    } while( handle == CK_INVALID_HANDLE || iter != tokenObjects.end() );
    return handle;
}

void
Slot::addKeyObject(list<PKCS11Object>& objectList, const ListObjectInfo& info,
    CK_OBJECT_HANDLE handle, bool isCombined)
{
    ObjectConstIter iter;
    Key keyObj(info.obj.objectID, &info.data, handle);
    CK_OBJECT_CLASS objClass = keyObj.getClass();
    const CKYBuffer *id;


    if (isCombined &&
	   ((objClass == CKO_PUBLIC_KEY) || (objClass == CKO_PRIVATE_KEY))) {
	id = keyObj.getAttribute(CKA_ID);
	if ((!id) || (CKYBuffer_Size(id) != 1)) {
	    throw PKCS11Exception(CKR_DEVICE_ERROR,
			"Missing or invalid CKA_ID value");
	}
	iter = find_if(objectList.begin(), objectList.end(),
			ObjectCertCKAIDMatch(CKYBuffer_GetChar(id,0)));
	if ( iter == objectList.end() ) {
            // We failed to find a cert with a matching CKA_ID. This
            // can happen if the cert is not present on the token, or
            // the der encoded cert stored on the token was corrupted.
	    throw PKCS11Exception(CKR_DEVICE_ERROR,
			"Failed to find cert with matching CKA_ID value");
	}
	keyObj.completeKey(*iter);
    }
    objectList.push_back(keyObj);

}

void
Slot::addObject(list<PKCS11Object>& objectList, const ListObjectInfo& info,
    CK_OBJECT_HANDLE handle)
{
    objectList.push_back(PKCS11Object(info.obj.objectID, &info.data, handle));
}

void
Slot::addCertObject(list<PKCS11Object>& objectList, 
    const ListObjectInfo& certAttrs,
    const CKYBuffer *derCert, CK_OBJECT_HANDLE handle)
{
    Cert certObj(certAttrs.obj.objectID, 
				&certAttrs.data, handle, derCert);
    if (personName == NULL) {
	personName = strdup(certObj.getLabel());
	fullTokenName = false;
    }

    objectList.push_back(certObj);
}
void
Slot::unloadObjects()
{
    tokenObjects.clear();
    free(personName);
    personName = NULL;
    fullTokenName = false;
}

#ifdef USE_SHMEM

// The shared memory segment is used to cache the raw token objects from
// the card so mupltiple instances do not need to read all the data in
// by themselves. It also allows us to recover data from a token on 
// reinsertion if that token is inserted into the same 'slot' as it was
// originally.
//
// There is one memory segment for each slot.
//
// The process that creates the shared memory segment will initialize the
// valid byte to '0'. Otherwise the Memory Segment must be accessed while 
// in a transaction for the connection to a reader that the memory segment 
// represents is held.
//
// If the memory segment is not valid, does not match the CUID of the 
// current token, or does not match the current data version, the current 
// process will read the object data out of the card  and into shared memory.
// Since access to the shared memory is protected by the interprocess 
// transaction lock on the reader, data consistancy is
// maintained.
//
// shared memory is layed out as follows:
//
// Header:
//  1 short  (version) shared mem layout version number (currrent 1,0)
//  1 short  (header size) size in bytes of the shared memory header
//  1 byte   (valid)  segment is valid or not (valid =1; not valid =0 )
//  1 byte   (reserved) (set to zero)
//  10 bytes (CUID)  Unique card identifier.
//  1 short  (reserved) (set to zero)
//  1 short  (data version) version number of the embeded data
//  1 short  (header offset) offset to the card's data header.
//  1 short  (data offset) offset to the uncompressed card data.
//  1 long   (header size) size in bytes of the card's data header.
//  1 long   (data size) size in bytes of the uncompressed data.
//  .
//  .
// DataHeader:
//  n bytes  DataHeader.
//  .
//  .
// Data:
//  n bytes   Data.
//
// All data in the shared memory header is stored in machine order, packing,
//  and size. Data in the DataHeader and Data sections are stored in applet 
//  byte order.
//
// Shared memory segments are fixed size (equal to the object memory size of
// the token). 
//

struct SlotSegmentHeader {
    unsigned short version;
    unsigned short headerSize;
    unsigned char  valid;
    unsigned char  reserved;
    unsigned char  cuid[10];
    unsigned short reserved2;
    unsigned short dataVersion;
    unsigned short dataHeaderOffset;
    unsigned short dataOffset;
    unsigned long  dataHeaderSize;
    unsigned long  dataSize;
    unsigned long  cert2Offset;
    unsigned long  cert2Size;
};

#define MAX_OBJECT_STORE_SIZE 15000
//
// previous development versions used a segment prefix of
// "coolkeypk11s"
//
#define SEGMENT_PREFIX "coolkeypk11s"
#define CAC_FAKE_CUID "CAC Certs"
SlotMemSegment::SlotMemSegment(const char *readerName): 
	segmentAddr(NULL),  segmentSize(0), segment(NULL)
{
   bool needInit;
   char *segName;

   segName = new char[strlen(readerName)+sizeof(SEGMENT_PREFIX)+1];
   if (!segName) {
	// just run without shared memory
	return;
    }
    sprintf(segName,SEGMENT_PREFIX"%s",readerName); 
    segment = SHMem::initSegment(segName, MAX_OBJECT_STORE_SIZE, needInit);
    delete [] segName;
    if (!segment) {
	// just run without shared memory
	return;
    }
    segmentAddr = segment->getSHMemAddr();
    assert(segmentAddr);
    // paranoia, shouldn't happen..
    if (!segmentAddr) {
	delete segment;
	segment = NULL;
	return;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    if (needInit) {
	segmentHeader->valid = 0;
    }
    segmentSize = segment->getSHMemSize();
}

SlotMemSegment::~SlotMemSegment()
{
    if (segment) {
	delete segment;
    }
}

bool
SlotMemSegment::CUIDIsEqual(const CKYBuffer *cuid) const
{
    if (!segment) {
	return false;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;

    return 
     CKYBuffer_DataIsEqual(cuid, (CKYByte *)segmentHeader->cuid, 
	sizeof(segmentHeader->cuid)) ? true : false;
}

void
SlotMemSegment::setCUID(const CKYBuffer *cuid)
{
    if (!segment) {
	return;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;

    if (CKYBuffer_Size(cuid) != sizeof(segmentHeader->cuid)) {
	// should throw and exception?
	return;
    }
    memcpy (segmentHeader->cuid, CKYBuffer_Data(cuid),
					sizeof(segmentHeader->cuid));
}

const unsigned char *
SlotMemSegment::getCUID() const
{
    if (!segment) {
	return NULL;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    return segmentHeader->cuid;
}

unsigned short
SlotMemSegment::getVersion() const
{
    if (!segment) {
	return 0;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    return segmentHeader->version;
}

unsigned short
SlotMemSegment::getDataVersion() const
{
    if (!segment) {
	return 0;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    return segmentHeader->dataVersion;
}

void
SlotMemSegment::setVersion(unsigned short version)
{
    if (!segment) {
	return;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    segmentHeader->version = version;
}


void
SlotMemSegment::setDataVersion(unsigned short version)
{
    if (!segment) {
	return;
    }

    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    segmentHeader->dataVersion = version;
}

bool
SlotMemSegment::isValid() const
{
    if (!segment) {
	return false;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    return segmentHeader->valid == 1;
}

void
SlotMemSegment::readHeader(CKYBuffer *dataHeader) const
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size = segmentHeader->dataHeaderSize;
    CKYByte *data = (CKYByte *) &segmentAddr[segmentHeader->dataHeaderOffset];
    CKYBuffer_Replace(dataHeader, 0, data, size);
}

void
SlotMemSegment::readData(CKYBuffer *objData) const
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size = segmentHeader->dataSize;
    CKYByte *data = (CKYByte *) &segmentAddr[segmentHeader->dataOffset];
    CKYBuffer_Replace(objData, 0, data, size);
}


void
SlotMemSegment::writeHeader(const CKYBuffer *dataHeader)
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size = CKYBuffer_Size(dataHeader);
    segmentHeader->headerSize = sizeof *segmentHeader;
    segmentHeader->dataHeaderSize = size;
    segmentHeader->dataHeaderOffset = sizeof *segmentHeader;
    segmentHeader->dataOffset = segmentHeader->dataHeaderOffset + size;
    CKYByte *data = (CKYByte *) &segmentAddr[segmentHeader->dataHeaderOffset];
    memcpy(data, CKYBuffer_Data(dataHeader), size);
}

void
SlotMemSegment::writeData(const CKYBuffer *objData)
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size = CKYBuffer_Size(objData);
    segmentHeader->dataSize = size;
    CKYByte *data = (CKYByte *) &segmentAddr[segmentHeader->dataOffset];
    memcpy(data, CKYBuffer_Data(objData), size);
}

void
SlotMemSegment::readCACCert(CKYBuffer *objData, CKYByte instance) const
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size;
    CKYByte *data;

    switch (instance) {
    case 0:
	data  = (CKYByte *) &segmentAddr[segmentHeader->dataHeaderOffset];
	size = segmentHeader->dataHeaderSize;
	break;
    case 1:
	data  = (CKYByte *) &segmentAddr[segmentHeader->dataOffset];
	size = segmentHeader->dataSize;
	break;
    case 2:
	data  = (CKYByte *) &segmentAddr[segmentHeader->cert2Offset];
	size = segmentHeader->cert2Size;
	break;
    default:
	CKYBuffer_Resize(objData, 0);
	return;
    }
    CKYBuffer_Replace(objData, 0, data, size);
}


void
SlotMemSegment::writeCACCert(const CKYBuffer *data, CKYByte instance)
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    int size = CKYBuffer_Size(data);
    CKYByte *shmData;
    switch (instance) {
    case 0:
	segmentHeader->headerSize = sizeof *segmentHeader;
	segmentHeader->dataHeaderOffset = sizeof *segmentHeader;
	segmentHeader->dataHeaderSize = size;
	segmentHeader->dataOffset = segmentHeader->dataHeaderOffset + size;
	segmentHeader->dataSize = 0;
	segmentHeader->cert2Offset = segmentHeader->dataOffset;
	segmentHeader->cert2Size = 0;
	shmData = (CKYByte *) &segmentAddr[segmentHeader->dataHeaderOffset];
	break;
    case 1:
	segmentHeader->dataSize = size;
	segmentHeader->cert2Offset = segmentHeader->dataOffset + size;
	segmentHeader->cert2Size = 0;
	shmData = (CKYByte *) &segmentAddr[segmentHeader->dataOffset];
	break;
    case 2:
	segmentHeader->cert2Size = size;
	shmData = (CKYByte *) &segmentAddr[segmentHeader->cert2Offset];
	break;
    default:
	return;
    }
    memcpy(shmData, CKYBuffer_Data(data), size);
}

void
SlotMemSegment::clearValid(CKYByte instance)
{

    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    switch (instance) {
    case 0:
	segmentHeader->headerSize = 0;
	segmentHeader->dataHeaderSize = 0;
	/* fall through */
    case 1:
	segmentHeader->dataSize = 0;
    }
    segmentHeader->valid = 0;
}

void
SlotMemSegment::setValid()
{
    if (!segment) {
	return;
    }
    SlotSegmentHeader *segmentHeader = (SlotSegmentHeader *)segmentAddr;
    segmentHeader->valid = 1;
}

#endif

void
Slot::initEmpty(void)
{
    // check the shared memory area first
    // shared memory is protected by our transaction call on the card
    //
    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS ) {
        handleConnectionError();
    }

    loadReaderObject();
    readCUID();
}

void
Slot::readCUID(void)
{
    // check the shared memory area first
    // shared memory is protected by our transaction call on the card
    //
    CKYStatus status;
    if (state & CAC_CARD) {
	status = CACApplet_SelectCardManager(conn, NULL);
    } else {
	status = CKYApplet_SelectCardManager(conn, NULL);
    }
    CKYBuffer_Resize(&mCUID, 0);
    if (status == CKYSCARDERR) {
	handleConnectionError();
    }
    status = CKYApplet_GetCUID(conn, &mCUID, NULL);
    if (status == CKYSCARDERR) {
	handleConnectionError();
    }
}

list<ListObjectInfo>
Slot::fetchSeparateObjects()
{
    int i;

    list<ListObjectInfo> objInfoList;
    std::list<ListObjectInfo>::iterator iter;

    OSTime time = OSTimeNow();
    readCUID();
    selectApplet();
    log->log(
     "time fetch separate: getting  cuid & applet select (again) %d ms\n",
							 OSTimeNow() - time);

#ifdef USE_SHMEM
    shmem.clearValid(0);
#endif

    //
    // get the list of objects on the muscle token
    //
    objInfoList = getObjectList();


    log->log("time fetch separate:  getObjectList %d ms\n",OSTimeNow() - time);
    //
    // get the content of each object
    //
    for (i=0, iter = objInfoList.begin(); iter != objInfoList.end(); 
								++iter, i++) {
	// check the ACL to make sure this will succeed.
	unsigned short readPerm = iter->obj.readACL;

	log->log("Object has read perm 0x%04x\n", readPerm);
	if ( (!isVersion1Key && ((readPerm & 0x2) == readPerm)) ||
 				(isVersion1Key && ((readPerm & 0x1))) ) {
	    readMuscleObject(&iter->data, iter->obj.objectID, 
						iter->obj.objectSize);
	    log->log("Object:\n");
	    log->dump(&iter->data);
	}
    }
    log->log("time fetch separate: readObjects %dms\n", OSTimeNow() - time);
    return objInfoList;
}

list<ListObjectInfo>
Slot::fetchCombinedObjects(const CKYBuffer *header)
{
    CKYBuffer objBuffer;
    CKYStatus status;

    list<ListObjectInfo> objInfoList;
    CKYBuffer_InitEmpty(&objBuffer);
    unsigned short compressedOffset = CKYBuffer_GetShort(
					header, OBJ_COMP_OFFSET_OFFSET);
    unsigned short compressedSize = CKYBuffer_GetShort(
					header, OBJ_COMP_SIZE_OFFSET);
    OSTime time = OSTimeNow();

#ifdef USE_SHMEM

    // check the shared memory area first
    // shared memory is protected by our transaction call on the card
    //
    CKYBuffer_Resize(&mCUID,0);
    CKYBuffer_AppendBuffer(&mCUID, header, OBJ_CUID_OFFSET, OBJ_CUID_SIZE);
    unsigned short dataVersion = CKYBuffer_GetShort(
					header, OBJ_OBJECT_VERSION_OFFSET);

    if (shmem.isValid() &&  shmem.CUIDIsEqual(&mCUID) && 
			shmem.getDataVersion() == dataVersion) {
	shmem.readData(&objBuffer);
    } else {
	shmem.clearValid(0);
	shmem.setCUID(&mCUID);
	shmem.setVersion(SHMEM_VERSION);
	shmem.setDataVersion(dataVersion);
	CKYBuffer dataHeader;
	CKYBuffer_InitFromBuffer(&dataHeader, header, 0, 
					(CKYSize) compressedOffset);

	shmem.writeHeader(&dataHeader);
	CKYBuffer_FreeData(&dataHeader);
	log->log("time fetch combined: play with shared memory %d ms\n",
		 OSTimeNow() - time);
#endif
	CKYBuffer_Reserve(&objBuffer, compressedSize);
	CKYSize headerSize = CKYBuffer_Size(header);
	CKYSize headerBytes = headerSize - compressedOffset;


	CKYBuffer_AppendBuffer(&objBuffer,header,compressedOffset,headerBytes);
	log->log("time fetch combined: "
		"headerbytes = %d compressedOffset = %d compressedSize = %d\n",
				headerBytes, compressedOffset, compressedSize);
	status = CKYApplet_ReadObjectFull(conn, COMBINED_ID, 
		headerSize, compressedSize - headerBytes, getNonce(), 
						&objBuffer, NULL);
	log->log("time fetch combined: read status = %d objectBuffSize = %d\n",
			 status, CKYBuffer_Size(&objBuffer));
	if (status == CKYSCARDERR) { 
	    CKYBuffer_FreeData(&objBuffer);
	    handleConnectionError();
	}
	log->log("time fetch combined: "
		"Read Object Data %d  ms (object size = %d bytes)\n",
		 OSTimeNow() - time, compressedSize);
	if (CKYBuffer_GetShort(header, OBJ_COMP_TYPE_OFFSET) == COMP_ZLIB) {
	    CKYBuffer compBuffer;
	    CKYSize guessFinalSize = CKYBuffer_Size(&objBuffer);
	    CKYSize objSize = 0;
	    int zret = Z_MEM_ERROR;

	    CKYBuffer_InitFromCopy(&compBuffer,&objBuffer);
	    do {
		guessFinalSize *= 2;
		status = CKYBuffer_Resize(&objBuffer, guessFinalSize);
		if (status != CKYSUCCESS) {
		    break;
		}
		objSize = guessFinalSize;
		zret = uncompress((Bytef *)CKYBuffer_Data(&objBuffer),&objSize,
			CKYBuffer_Data(&compBuffer), CKYBuffer_Size(&compBuffer));
	    } while (zret == Z_BUF_ERROR);
	    log->log("time fetch combined: "
		"uncompress objects %d  ms (object size = %d bytes)\n",
		 OSTimeNow() - time, objSize);

	    CKYBuffer_FreeData(&compBuffer);
	    if (zret != Z_OK) {
		CKYBuffer_FreeData(&objBuffer);
		throw PKCS11Exception(CKR_DEVICE_ERROR, 
				"Corrupted compressed object Data");
	    }
	    CKYBuffer_Resize(&objBuffer,objSize);
 	}
	
	// uncompress...
#ifdef USE_SHMEM
	shmem.writeData(&objBuffer);
	shmem.setDataVersion(dataVersion);
	shmem.setValid();
    }
#endif

     //
     // now pull apart the objects
     //
    unsigned short offset = 
		CKYBuffer_GetShort(&objBuffer, OBJ_OBJECT_OFFSET_OFFSET);
    unsigned short objectCount = CKYBuffer_GetShort(
					&objBuffer, OBJ_OBJECT_COUNT_OFFSET);
    int tokenNameSize = CKYBuffer_GetChar(&objBuffer,OBJ_TOKENNAME_SIZE_OFFSET);
    int i;
    CKYSize size = CKYBuffer_Size(&objBuffer);

    if (offset < tokenNameSize+OBJ_TOKENNAME_OFFSET) {
	CKYBuffer_FreeData(&objBuffer);
	throw PKCS11Exception(CKR_DEVICE_ERROR,
			"Tokenname/object Data overlap");
    }
    if (personName) {
	free(personName);
    }
    personName = (char *)malloc(tokenNameSize+1);
    memcpy(personName,CKYBuffer_Data(&objBuffer)+OBJ_TOKENNAME_OFFSET,
								tokenNameSize);
    personName[tokenNameSize] = 0;
    fullTokenName = true;

    for (i=0; i < objectCount && offset < size; i++) {
	ListObjectInfo info;
	unsigned long objectID = CKYBuffer_GetLong(&objBuffer, offset);
	unsigned long attrsCount= CKYBuffer_GetShort(&objBuffer, offset+8);
	unsigned long start = offset;
	unsigned int j;

	info.obj.objectID = objectID;
	offset +=10;

	/* get the length of the attribute block */
	for (j=0; j < attrsCount; j++) {
	    CKYByte attributeDataType=CKYBuffer_GetChar(&objBuffer, offset +4);

	    offset += 5;

	    switch (attributeDataType) {
	    case DATATYPE_STRING:
                offset += CKYBuffer_GetShort(&objBuffer, offset) + 2;
                break;
            case DATATYPE_BOOL_FALSE:
	    case DATATYPE_BOOL_TRUE:
                break;
	    case DATATYPE_INTEGER:
                offset += 4;
                break;
            }
	}
	if (offset > size) {
	    CKYBuffer_FreeData(&objBuffer);
	    throw PKCS11Exception(CKR_DEVICE_ERROR,
			"Inconsistant combined object data");
	}
	CKYSize objSize = offset - start;
	CKYBuffer_Reserve(&info.data, objSize +1);
	// tell the object parsing code that this is a new, compact type
	CKYBuffer_AppendChar(&info.data,1);
	// copy the object
	CKYBuffer_AppendBuffer(&info.data, &objBuffer, start, objSize);
        objInfoList.push_back(info);
    }
    CKYBuffer_FreeData(&objBuffer);
    log->log("fetch combined: format objects %d ms\n", OSTimeNow() - time);
    return objInfoList;
}

void
Slot::loadCACCert(CKYByte instance)
{
    CKYISOStatus apduRC;
    CKYStatus status = CKYSUCCESS;
    CKYBuffer cert;
    CKYBuffer rawCert;
    CKYBuffer shmCert;
    CKYSize  nextSize;

    OSTime time = OSTimeNow();

    CKYBuffer_InitEmpty(&cert);
    CKYBuffer_InitEmpty(&rawCert);
    CKYBuffer_InitEmpty(&shmCert);

    //
    // not all CAC cards have all the PKI instances
    // catch the applet selection errors if they don't
    //
    try {
        selectCACApplet(instance);
    } catch(PKCS11Exception& e) {
	// all CAC's must have instance '0', throw the error it
	// they don't.
	if (instance == 0) throw e;
	// If the CAC doesn't have instance '2', and we were updating
	// the shared memory, set it to valid now.
	if ((instance == 2) && !shmem.isValid()) {
	    shmem.setValid();
	}
	return;
    }

    log->log("CAC Cert %d: select CAC applet:  %d ms\n",
						 instance, OSTimeNow() - time);

    if (instance == 0) {
	/* get the first 100 bytes of the cert */
	status = CACApplet_GetCertificateFirst(conn, &rawCert, 
						&nextSize, &apduRC);
	if (status != CKYSUCCESS) {
	    handleConnectionError();
	}
	log->log("CAC Cert %d: fetch CAC Cert:  %d ms\n", 
						instance, OSTimeNow() - time);
    }

    unsigned short dataVersion = 1;
    CKYBool needRead = 1;

    /* see if it matches the shared memory */
    if (shmem.isValid() &&  shmem.getDataVersion() == dataVersion) {
	shmem.readCACCert(&shmCert, instance);
	CKYSize certSize = CKYBuffer_Size(&rawCert);
	CKYSize shmCertSize = CKYBuffer_Size(&shmCert);
	const CKYByte *shmData = CKYBuffer_Data(&shmCert);

	if (instance != 0) {
	    needRead = 0;
	}

	if (shmCertSize >= certSize) {
	    if (memcmp(shmData, CKYBuffer_Data(&rawCert), certSize) == 0) {
		/* yes it does, no need to read the rest of the cert, use
		 * the cache */
		CKYBuffer_Replace(&rawCert, 0, shmData, shmCertSize);
		needRead = 0;
	    }
	}
	if (!needRead && (shmCertSize == 0)) {	
	    /* no cert of this type, just return */
	    return;
	}
    }
    CKYBuffer_FreeData(&shmCert);

    if (needRead) {
	/* it doesn't, read the new cert and update the cache */
	if (instance == 0) {
	    shmem.clearValid(0);
	    shmem.setVersion(SHMEM_VERSION);
	    shmem.setDataVersion(dataVersion);
	} else {
	    status = CACApplet_GetCertificateFirst(conn, &rawCert, 
						&nextSize, &apduRC);
	
	    if (status != CKYSUCCESS) {
		/* CAC only requires the Certificate in pki '0' */
		/* if pki '1' or '2' are empty, treat it as a non-fatal error*/
		if (instance == 2) {
		    /* we've attempted to read all the certs, shared memory
		     * is now valid */
		    shmem.setValid();
		}
		return;
	    }
	}

	if (nextSize) {
	    status = CACApplet_GetCertificateAppend(conn, &rawCert, 
						nextSize, &apduRC);
	}
	log->log("CAC Cert %d: Fetch rest :  %d ms\n", 
						instance, OSTimeNow() - time);
	if (status != CKYSUCCESS) {
	    handleConnectionError();
	}
	shmem.writeCACCert(&rawCert, instance);
	if (instance == 2) {
	    shmem.setValid();
	}
    }


    log->log("CAC Cert %d: Cert has been read:  %d ms\n",
						instance, OSTimeNow() - time);
    if (CKYBuffer_GetChar(&rawCert,0) == 1) {
	CKYSize guessFinalSize = CKYBuffer_Size(&rawCert);
	CKYSize certSize = 0;
	int zret = Z_MEM_ERROR;

	do {
	    guessFinalSize *= 2;
	    status = CKYBuffer_Resize(&cert, guessFinalSize);
	    if (status != CKYSUCCESS) {
		    break;
	    }
	    certSize = guessFinalSize;
	    zret = uncompress((Bytef *)CKYBuffer_Data(&cert),&certSize,
			CKYBuffer_Data(&rawCert)+1, CKYBuffer_Size(&rawCert)-1);
	} while (zret == Z_BUF_ERROR);

	if (zret != Z_OK) {
	    CKYBuffer_FreeData(&rawCert);
	    CKYBuffer_FreeData(&cert);
	    throw PKCS11Exception(CKR_DEVICE_ERROR, 
				"Corrupted compressed CAC Cert");
	}
	CKYBuffer_Resize(&cert,certSize);
    } else {
	CKYBuffer_InitFromBuffer(&cert,&rawCert,1,CKYBuffer_Size(&rawCert)-1);
    }
    CKYBuffer_FreeData(&rawCert);
    log->log("CAC Cert %d: Cert has been uncompressed:  %d ms\n",
						instance, OSTimeNow() - time);

    CACCert certObj(instance, &cert);
    CACPrivKey privKey(instance, certObj);
    CACPubKey pubKey(instance, certObj);
    tokenObjects.push_back(privKey);
    tokenObjects.push_back(pubKey);
    tokenObjects.push_back(certObj);

    if (personName == NULL) {
	const char *name = certObj.getName();
	if (name) {
            personName = strdup(name);
            fullTokenName = true;
	}
    }
}

void
Slot::loadObjects()
{
    // throw away all token objects!

    Transaction trans;
    CKYBuffer header;
    CKYBuffer_InitEmpty(&header);
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS ) {
        handleConnectionError();
    }
    OSTime time = OSTimeNow();


    list<ListObjectInfo> objInfoList;
    std::list<ListObjectInfo>::iterator iter;

    if (state & CAC_CARD) {
	loadCACCert(0);
	loadCACCert(1);
	loadCACCert(2);
	status = trans.end();
	loadReaderObject();
	return;
    }

    selectApplet();
    log->log("time load object: Select Applet (again) %d ms\n",
						OSTimeNow() - time);
    

    status = CKYApplet_ReadObjectFull(conn, COMBINED_ID, 0, 
			CKY_MAX_READ_CHUNK_SIZE, getNonce(), &header, NULL);
    log->log("time load object: ReadCombined Header %d ms\n", 
						OSTimeNow() - time);
    if (status == CKYSCARDERR) { 
        CKYBuffer_FreeData(&header);
        handleConnectionError();
    }
    bool isCombined = (status == CKYSUCCESS) ? true : false;
    try {
	objInfoList = isCombined ? fetchCombinedObjects(&header) 
						: fetchSeparateObjects();
    } catch(PKCS11Exception& e) {
	CKYBuffer_FreeData(&header);
	throw(e);
    }
    log->log("time load object: Fetch %d ms\n", OSTimeNow() - time);
    CKYBuffer_FreeData(&header);
    status = trans.end();

    //
    // load up the keys, certs and others.
    //
    for( iter = objInfoList.begin(); iter != objInfoList.end(); ++iter ) {
	CKYByte type = getObjectClass(iter->obj.objectID);
        if( type == 'k' ) {
	    CK_OBJECT_HANDLE handle = generateUnusedObjectHandle();
            addKeyObject(tokenObjects, *iter, handle, isCombined);
        } else if( type == 'c' ) {
            // cert attribute object. find the DER encoding
            unsigned short certnum = getObjectIndex(iter->obj.objectID);
            if( certnum > 9 ) {
                //invalid object id
                throw PKCS11Exception(CKR_DEVICE_ERROR,
                    "Invalid object id %08x",iter->obj.objectID);
            }
            std::list<ListObjectInfo>::iterator derCert;
	    /*
	     * Old tokens stored certs separately from the attributes
	     */
	    if (!isCombined) {
        	derCert = find_if(objInfoList.begin(), objInfoList.end(),
                    DERCertObjIDMatch(certnum, *this));
        	if( derCert == objInfoList.end() ) {
                    throw PKCS11Exception(CKR_DEVICE_ERROR,
			"No DER cert object for cert %d\n", certnum);
		}
            }
	    CK_OBJECT_HANDLE handle = generateUnusedObjectHandle();
            addCertObject(tokenObjects, *iter, 
			isCombined ? NULL : &derCert->data, handle);
        } else if ( type == 'C' ) {
	    // This is a DER Cert object (as opposed to a cert attribute
	    // object, 'c' above).  skip it.
        } else if (type == 'd') {
	    CK_OBJECT_HANDLE handle = generateUnusedObjectHandle();
	    addObject(tokenObjects, *iter, handle);
	} else {
            log->log("Ignoring unknown object %08x\n",iter->obj.objectID);
        }
    }
    log->log("time load objects: Process %d ms\n", OSTimeNow() - time);

    loadReaderObject();
}

void
Slot::loadReaderObject(void)
{
    // now generate an Moz "reader" object.
    CK_OBJECT_HANDLE handle = generateUnusedObjectHandle();
    Reader rdr(READER_ID, handle, readerName, &cardATR, mCoolkey);
    tokenObjects.push_back(rdr);
}

void
Slot::closeAllSessions()
{
    sessions.clear();
    log->log("cleared all sessions\n");
}

SessionHandleSuffix
Slot::generateNewSession(Session::Type type)
{
    SessionHandleSuffix suffix;
    SessionIter iter;

    do {
        suffix = (++sessionHandleCounter) & 0x00ffffff;
        iter = findSession(suffix);
    } while( iter != sessions.end() );

    sessions.push_back(Session(suffix, type));

    return suffix;
}

void
SlotList::getSessionInfo(CK_SESSION_HANDLE hSession,
    CK_SESSION_INFO_PTR pInfo)
{

    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->getSessionInfo(suffix, pInfo);

    pInfo->slotID = slotID;
}

void
Slot::ensureTokenPresent()
{
    if( ! isTokenPresent() ) {
        throw PKCS11Exception(CKR_DEVICE_REMOVED);
    }
}

SessionIter
Slot::findSession(SessionHandleSuffix suffix)
{
    return find_if(sessions.begin(), sessions.end(),
        SessionHandleSuffixMatch(suffix));
}

SessionConstIter
Slot::findConstSession(SessionHandleSuffix suffix) const
{
    return find_if(sessions.begin(), sessions.end(),
        SessionHandleSuffixMatch(suffix));
}

void
Slot::getSessionInfo(SessionHandleSuffix handleSuffix,
    CK_SESSION_INFO_PTR pInfo)
{
    refreshTokenState();

    SessionIter iter = findSession(handleSuffix);
    if( iter == sessions.end() ) {
            throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID,
                "Unknown session handle suffix 0x%08x passed to "
                    "getSessionInfo\n", (unsigned long) handleSuffix);
    } else {
        if( iter->getType() == Session::RO ) {
            pInfo->state = isLoggedIn() ?
                CKS_RO_USER_FUNCTIONS : CKS_RO_PUBLIC_SESSION;
            pInfo->flags = CKF_SERIAL_SESSION;
        } else {
            pInfo->state = isLoggedIn() ?
                CKS_RW_USER_FUNCTIONS : CKS_RW_PUBLIC_SESSION;
            pInfo->flags = CKF_RW_SESSION | CKF_SERIAL_SESSION;
        }
        pInfo->ulDeviceError = CKYCardConnection_GetLastError(conn);
    }
}

void
SlotList::login(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pPin,
    CK_ULONG ulPinLen)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->login(suffix, pPin, ulPinLen);
}

void
Slot::testNonce()
{
    reverify = false;
    if (!nonceValid) {
	return;
    }
#ifdef notdef
    Transaction trans;
    CKYStatus status = trans.begin(conn);
    try {
        if ( status != CKYSUCCESS ) handleConnectionError();

         selectApplet();
    } catch (PKCS11Exception &) {
	invalidateLogin(true);
	return;
    }

    CKYBuffer data;
    CKYBuffer_InitEmpty(&data);

    status = CKYApplet_ReadObject(conn, 0xffffffff, 0, 1, &nonce, &data, NULL);
    trans.end();
    CKYBuffer_FreeData(&data);
    if( status != CKYSUCCESS )  {
	invalidateLogin(true);
	return;
    }
#else
    invalidateLogin(true);
#endif
}

bool
Slot::isLoggedIn()
{
    if (isVersion1Key) {
	if (reverify) {
	    testNonce();
	}
	return nonceValid;
    }
    return loggedIn;
}

void
Slot::login(SessionHandleSuffix handleSuffix, CK_UTF8CHAR_PTR pPin,
    CK_ULONG ulPinLen)
{
    refreshTokenState();

    if( ! isValidSession(handleSuffix) ) {
        log->log("Invalid session handle suffix 0x%08x passed to "
            "Slot::login\n", (unsigned long) handleSuffix);
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }

    if (!isVersion1Key) {
	pinCache.set((const char *)pPin, ulPinLen);
    } else if (nonceValid) {
	throw PKCS11Exception(CKR_USER_ALREADY_LOGGED_IN);
    }

    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if(status != CKYSUCCESS ) handleConnectionError();

    if (state & CAC_CARD) {
	selectCACApplet(0);
    } else {
	selectApplet();
    }

    if (isVersion1Key) {
	attemptLogin((const char *)pPin);
    } else if (state & CAC_CARD) {
	attemptCACLogin();
    } else {
	oldAttemptLogin();
    }
}

void
Slot::attemptCACLogin()
{
    loggedIn = false;
    pinCache.invalidate();

    CKYStatus status;
    CKYISOStatus result;

    status = CACApplet_VerifyPIN(conn, 
		(const char *)CKYBuffer_Data(pinCache.get()), &result);
    if( status == CKYSCARDERR ) {
	handleConnectionError();
    }
    switch( result ) {
      case CKYISO_SUCCESS:
        break;
      case 6981:
        throw PKCS11Exception(CKR_PIN_LOCKED);
      default:
	if ((result & 0xff00) == 0x6300) {
            throw PKCS11Exception(CKR_PIN_INCORRECT);
	}
        throw PKCS11Exception(CKR_DEVICE_ERROR, "Applet returned 0x%04x", 
								result);
    }

    pinCache.validate();
    loggedIn = true;
}

void
Slot::oldAttemptLogin()
{
    loggedIn = false;
    pinCache.invalidate();

    CKYStatus status;
    CKYISOStatus result;
    status = CKYApplet_VerifyPinV0(conn, CKY_OLD_USER_PIN_NUM,
		(const char *)CKYBuffer_Data(pinCache.get()), &result);
    if( status == CKYSCARDERR ) {
	handleConnectionError();
    }
    switch( result ) {
      case CKYISO_SUCCESS:
        break;
      case CKYISO_AUTH_FAILED:
        throw PKCS11Exception(CKR_PIN_INCORRECT);
      case CKYISO_IDENTITY_BLOCKED:
        throw PKCS11Exception(CKR_PIN_LOCKED);
      default:
        throw PKCS11Exception(CKR_DEVICE_ERROR, "Applet returned 0x%04x", 
								result);
    }

    pinCache.validate();
    loggedIn = true;
}

// should already be in a transaction, and applet selected
void
Slot::attemptLogin(const char *pin)
{
    CKYStatus status;
    CKYISOStatus result;
    status = CKYApplet_VerifyPIN(conn, CKY_USER_PIN_NUM, pin, &nonce, &result);
    if( status == CKYSCARDERR ) {
	handleConnectionError();
    }

    switch( result ) {
      case CKYISO_SUCCESS:
        break;
      case CKYISO_AUTH_FAILED:
        throw PKCS11Exception(CKR_PIN_INCORRECT);
      case CKYISO_IDENTITY_BLOCKED:
        throw PKCS11Exception(CKR_PIN_LOCKED);
      default:
        throw PKCS11Exception(CKR_DEVICE_ERROR,
            "Applet returned 0x%04x", result);
    }
    nonceValid = true;

}

void
SlotList::logout(CK_SESSION_HANDLE hSession)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->logout(suffix);
}

//
// The old "logout All" from pre-version 1 CoolKeys.
//
void
Slot::oldLogout()
{
    invalidateLogin(true);

    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS) handleConnectionError();

    selectApplet();

    status = CKYApplet_LogoutAllV0(conn, NULL);
    if (status != CKYSUCCESS) {
	if (status == CKYSCARDERR) {
	    handleConnectionError();
	}
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }
}

//
//
void
Slot::CACLogout()
{
    /* use get properties which has the side effect of logging out */
    invalidateLogin(true);
}

void
Slot::logout(SessionHandleSuffix suffix)
{
    refreshTokenState();

    if( !isValidSession(suffix) ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }

    if (state & CAC_CARD) {
	CACLogout();
	return;
    }

    if (!isVersion1Key) {
	oldLogout();
	return;
    }

    if (!nonceValid) {
	throw PKCS11Exception(CKR_USER_NOT_LOGGED_IN);
    }

    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS) handleConnectionError();

    status = CKYApplet_Logout(conn, CKY_USER_PIN_NUM, getNonce(), NULL);
    invalidateLogin(true);
    if (status != CKYSUCCESS) {
	if (status == CKYSCARDERR) {
	    handleConnectionError();
	}
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }

}

void
SlotList::findObjectsInit(CK_SESSION_HANDLE hSession,
        CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->findObjectsInit(suffix, pTemplate, ulCount);
}

void
Slot::findObjectsInit(SessionHandleSuffix suffix, CK_ATTRIBUTE_PTR pTemplate,
    CK_ULONG ulCount)
{
    refreshTokenState();

    SessionIter session = findSession(suffix);
    if( session == sessions.end() ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }

    session->foundObjects.clear();

    ObjectConstIter iter;
    for( iter = tokenObjects.begin(); iter != tokenObjects.end(); ++iter) {
        if( iter->matchesTemplate(pTemplate, ulCount) ) {
            log->log("C_FindObjectsInit found matching object 0x%08x\n",
                iter->getHandle());
            session->foundObjects.push_back(iter->getHandle());
        }
    }

    session->curFoundObject = session->foundObjects.begin();
}

void
SlotList::findObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject,
        CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->findObjects(suffix, phObject,
        ulMaxObjectCount, pulObjectCount);
}

void
Slot::findObjects(SessionHandleSuffix suffix, CK_OBJECT_HANDLE_PTR phObject,
        CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount)
{
    refreshTokenState();

    SessionIter session = findSession(suffix);
    if( session == sessions.end() ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }

    unsigned int objectsReturned = 0;
    while( objectsReturned < ulMaxObjectCount &&
        session->curFoundObject != session->foundObjects.end() )
    {
        phObject[objectsReturned++] = *(session->curFoundObject++);
    }

    *pulObjectCount = objectsReturned;
}

void
SlotList::getAttributeValue(CK_SESSION_HANDLE hSession,
    CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
    const
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->getAttributeValue(suffix, hObject,
        pTemplate, ulCount);
}

void
Slot::getAttributeValue(SessionHandleSuffix suffix,
    CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
{
    refreshTokenState();

    if( ! isValidSession(suffix) ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }

    ObjectConstIter iter = find_if(tokenObjects.begin(), tokenObjects.end(),
        ObjectHandleMatch(hObject));

    if( iter == tokenObjects.end() ) {
        throw PKCS11Exception(CKR_OBJECT_HANDLE_INVALID);
    }

    iter->getAttributeValue(pTemplate, ulCount, log);
}

void
SlotList::signInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->signInit(suffix, pMechanism, hKey);
}

void
SlotList::decryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->decryptInit(suffix, pMechanism, hKey);
}

void
SlotList::sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen, CK_BYTE_PTR pSignature,
        CK_ULONG_PTR pulSignatureLen)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->sign(suffix, pData, ulDataLen,
        pSignature, pulSignatureLen);
}

void
SlotList::decrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen, CK_BYTE_PTR pDecryptedData,
        CK_ULONG_PTR pulDecryptedDataLen)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->decrypt(suffix, pData, ulDataLen,
        pDecryptedData, pulDecryptedDataLen);
}

void
SlotList::seedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->seedRandom(suffix, pData, ulDataLen);
}

void
SlotList::generateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen)
{
    CK_SLOT_ID slotID;
    SessionHandleSuffix suffix;

    decomposeSessionHandle(hSession, slotID, suffix);

    slots[slotIDToIndex(slotID)]->generateRandom(suffix, pData, ulDataLen);
}

void
Slot::ensureValidSession(SessionHandleSuffix suffix)
{
    if( ! isValidSession(suffix) ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }
}

//
// Looks up an object and pulls the key number from the Muscle Object ID.
// Keys in Muscle have IDs of the form 'kn  ', where 'n' is the key number
// from 0-9.
//
CKYByte
Slot::objectHandleToKeyNum(CK_OBJECT_HANDLE hKey)
{
    ObjectConstIter iter = find_if(tokenObjects.begin(), tokenObjects.end(),
        ObjectHandleMatch(hKey));

    if( iter == tokenObjects.end() ) {
        // no such object
        throw PKCS11Exception(CKR_KEY_HANDLE_INVALID);
    }

    if( getObjectClass(iter->getMuscleObjID()) != 'k' ) {
        throw PKCS11Exception(CKR_KEY_HANDLE_INVALID);
    }
    unsigned short keyNum = getObjectIndex(iter->getMuscleObjID());
    if( keyNum > 9 ) {
        throw PKCS11Exception(CKR_KEY_HANDLE_INVALID);
    }
    return keyNum & 0xFF;
}

void
Slot::signInit(SessionHandleSuffix suffix, CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey)
{
    refreshTokenState();
    SessionIter session = findSession(suffix);
    if( session == sessions.end() ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }
    session->signatureState.initialize(objectHandleToKeyNum(hKey));
}

void
Slot::decryptInit(SessionHandleSuffix suffix, CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey)
{
    refreshTokenState();
    SessionIter session = findSession(suffix);
    if( session == sessions.end() ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }
    session->decryptionState.initialize(objectHandleToKeyNum(hKey));
}

/**
 * Padding algorithm defined in RSA's PKCS #1.
 * to: pre-allocated buffer to receive the padded data
 * toLen: the length of the buffer. This should be the same as the size
 *      of the RSA modulus.  (toLen - 3) > fromLen.
 * from: data to be padded.
 * fromLen: size of data to be padded. fromLen < (toLen-3).
 * Returns: nonzero for success, zero for failure.
 */
static void
padRSAType1(const CKYBuffer *raw, CKYBuffer *padded)
{
    int i = 0;
    unsigned int padLen = CKYBuffer_Size(padded) - 3 - CKYBuffer_Size(raw);

    /* First byte: 00 */
    CKYBuffer_SetChar(padded, i++, 0x00);

    /* Second Byte: Block Type == 01 */
    CKYBuffer_SetChar(padded, i++, 0x01);

    /* Padding String, each byte is 0xFF for block type 01 */
    CKYBuffer_SetChars(padded, i, 0xFF, padLen);
    i += padLen;

    /* Separator byte: 00 */
    CKYBuffer_SetChar(padded, i++, 0x00);

    /* Finally, the data */
    CKYBuffer_Replace(padded, i, CKYBuffer_Data(raw), CKYBuffer_Size(raw));
}

static void
stripRSAPadding(CKYBuffer *stripped, const CKYBuffer *padded)
{
    unsigned int size = CKYBuffer_Size(padded);
    if( size < 2 ) {
        throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
    }
    if( CKYBuffer_GetChar(padded,0) != 0 ) {
        throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
    }

    unsigned int dataStart = 3;

    CKYByte blockType = CKYBuffer_GetChar(padded, 1);
    // There are three block types in PKCS #1 padding: 00, 01, and 02.
    switch(blockType) {
      case 0x00:
        // The padding string is all zeroes. The first nonzero byte
        // is the beginning of the data.
        for( ; dataStart < size; ++dataStart ) {
            if( CKYBuffer_GetChar(padded,dataStart) != 0 ) {
                break;
            }
        }
        if( dataStart == size ) {
            throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
        }
        break;
      case 0x01:
        // The padding string is all 0xFF, followed by a 0x00 separator byte,
        // and then the data.
        for( ; dataStart < size; ++dataStart ) {
            if( CKYBuffer_GetChar(padded,dataStart) == 0xff ) {
                // padding, continue;
            } else if( CKYBuffer_GetChar(padded,dataStart) == 0x00 ) {
                // end of padding
                break;
            } else {
                // invalid character
                throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
            }
        }
        if( dataStart == size  ) {
            // we never found the separator byte
            throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
        }
        dataStart++; // data starts after separator byte
        break;
      case 0x02:
        // padding is non-zero. First non-zero byte is the separator,
        // and then the data.
        for( ; dataStart < size; ++dataStart) {
            if( CKYBuffer_GetChar(padded,dataStart) == 0x00 ) {
                break;
            }
        }
        if( dataStart == size ) {
            // we never found the separator byte
            throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID);
        }
        dataStart++; // data starts after separator byte
        break;
      default:
        throw PKCS11Exception(CKR_ENCRYPTED_DATA_INVALID,
            "Unknown PKCS#1 block type %x", blockType);
    }

    CKYStatus status = CKYBuffer_Replace(stripped, 0, 
		CKYBuffer_Data(padded)+dataStart, size-dataStart);
    if (status != CKYSUCCESS) {
	throw PKCS11Exception(CKR_HOST_MEMORY);
    }
}

class RSASignatureParams : public CryptParams {
  public:
    RSASignatureParams(unsigned int keysize) : CryptParams(keysize) { }

    CKYByte getDirection() const { return CKY_DIR_ENCRYPT; }

    CryptOpState& getOpState(Session& session) const {
        return session.signatureState;
    }

    void padInput(CKYBuffer *paddedInput, const CKYBuffer *unpaddedInput) const {
        // RSA_NO_PAD requires RSA PKCS #1 Type 1 padding
  	CKYStatus status = CKYBuffer_Resize(paddedInput,getKeySize()/8);
	if (status != CKYSUCCESS) {
	    throw PKCS11Exception(CKR_HOST_MEMORY);
	}
        padRSAType1(unpaddedInput, paddedInput);
        return;
    }

    void
    unpadOutput(CKYBuffer *unpaddedOutput, const CKYBuffer *paddedOutput) const {
        // no need to unpad ciphertext
	CKYBuffer_Replace(unpaddedOutput, 0, CKYBuffer_Data(paddedOutput),
					CKYBuffer_Size(paddedOutput));
	
    }
};

class RSADecryptParams: public CryptParams {
  public:
    RSADecryptParams(unsigned int keysize) : CryptParams(keysize) { }

    CKYByte getDirection() const { return CKY_DIR_DECRYPT; }

    CryptOpState& getOpState(Session& session) const {
        return session.decryptionState;
    }

    void padInput(CKYBuffer *paddedInput, const CKYBuffer *unpaddedInput) const {
        // no need to unpad ciphertext
	CKYBuffer_Replace(paddedInput, 0, CKYBuffer_Data(unpaddedInput),
					CKYBuffer_Size(unpaddedInput));
    }

    void
    unpadOutput(CKYBuffer *unpaddedOutput, const CKYBuffer *paddedOutput) const {
        // strip off PKCS #1 padding
        stripRSAPadding( unpaddedOutput, paddedOutput );
	return;
    }
};

void
Slot::sign(SessionHandleSuffix suffix, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen, CK_BYTE_PTR pSignature,
        CK_ULONG_PTR pulSignatureLen)
{
    RSASignatureParams params(CryptParams::DEFAULT_KEY_SIZE);
    cryptRSA(suffix, pData, ulDataLen, pSignature, pulSignatureLen,
        params);
}

void
Slot::decrypt(SessionHandleSuffix suffix, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen, CK_BYTE_PTR pDecryptedData,
        CK_ULONG_PTR pulDecryptedDataLen)
{
    RSADecryptParams params(CryptParams::DEFAULT_KEY_SIZE);
    cryptRSA(suffix, pData, ulDataLen, pDecryptedData, pulDecryptedDataLen,
        params);
}

void
Slot::cryptRSA(SessionHandleSuffix suffix, CK_BYTE_PTR pInput,
        CK_ULONG ulInputLen, CK_BYTE_PTR pOutput,
        CK_ULONG_PTR pulOutputLen, CryptParams& params)
{
    refreshTokenState();
    SessionIter session = findSession(suffix);
    if( session == sessions.end() ) {
        throw PKCS11Exception(CKR_SESSION_HANDLE_INVALID);
    }
    // version 1 keys may not need login. We catch the error
    // on the operation. The token will not allow us to sign with
    // a protected key unless we are logged in.
    // can be removed when version 0 support is depricated.
    if (!isVersion1Key && ! isLoggedIn() ) {
        throw PKCS11Exception(CKR_USER_NOT_LOGGED_IN);
    }
    CryptOpState& opState = params.getOpState(*session);
    CKYBuffer *result = &opState.result;
    CKYByte keyNum = opState.keyNum;

    unsigned int keySize = getKeySize(keyNum);

    if(keySize != CryptParams::DEFAULT_KEY_SIZE)
        params.setKeySize(keySize);

    if( CKYBuffer_Size(result) == 0 ) {
        // we haven't already peformed the decryption, so do it now.
        if( pInput == NULL || ulInputLen == 0) {
            throw PKCS11Exception(CKR_DATA_LEN_RANGE);
        }
	// OK, this is gross. We should get our own C++ like buffer
        // management at this point. This code has nothing to do with
	// the applet, it shouldn't be using applet specific buffers.
        CKYBuffer input;
        CKYBuffer inputPad;
        CKYBuffer output;
        CKYBuffer_InitEmpty(&output);
        CKYBuffer_InitEmpty(&inputPad);
	CKYStatus status = CKYBuffer_InitFromData(&input, pInput, ulInputLen);
 	if (status != CKYSUCCESS) {
	    throw PKCS11Exception(CKR_HOST_MEMORY);
  	}
	try {
	    params.padInput(&inputPad, &input);
            performRSAOp(&output, &inputPad, keyNum, params.getDirection());
	    params.unpadOutput(result, &output);
	    CKYBuffer_FreeData(&input);
	    CKYBuffer_FreeData(&inputPad);
	    CKYBuffer_FreeData(&output);
	} catch(PKCS11Exception& e) {
	    CKYBuffer_FreeData(&input);
	    CKYBuffer_FreeData(&inputPad);
	    CKYBuffer_FreeData(&output);
	    throw(e);
	}
    }

    if( pulOutputLen == NULL ) {
        throw PKCS11Exception(CKR_DATA_INVALID,
            "output length is NULL");
    }

    if( pOutput != NULL ) {
        if( *pulOutputLen < CKYBuffer_Size(result) ) {
            *pulOutputLen = CKYBuffer_Size(result);
            throw PKCS11Exception(CKR_BUFFER_TOO_SMALL);
        }
        memcpy(pOutput, CKYBuffer_Data(result), CKYBuffer_Size(result));
    }
    *pulOutputLen = CKYBuffer_Size(result);
}

const CKYBuffer *
Slot::getNonce()
{
    if (!isVersion1Key) {
	return NULL;
    }
    return &nonce;
}

void
Slot::performRSAOp(CKYBuffer *output, const CKYBuffer *input, 
					CKYByte keyNum, CKYByte direction)
{
    //
    // establish a transaction
    //
    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS ) handleConnectionError();

    //
    // select the applet
    //
    if (state & CAC_CARD) {
	selectCACApplet(keyNum);
    } else {
	selectApplet();
    }

    CKYISOStatus result;
    int loginAttempted = 0;
retry:
    if (state & CAC_CARD) {
        status = CACApplet_SignDecrypt(conn, input, output, &result);
    } else {
        status = CKYApplet_ComputeCrypt(conn, keyNum, CKY_RSA_NO_PAD, direction,
		input, NULL, output, getNonce(), &result);
    } 
    if (status != CKYSUCCESS) {
	if ( status == CKYSCARDERR ) {
	    handleConnectionError();
	}
        if (result == CKYISO_DATA_INVALID) {
            throw PKCS11Exception(CKR_DATA_INVALID);
	}
	// version0 keys could be logged out in the middle by someone else,
	// reauthenticate... This code can go away when we depricate.
        // version0 applets.
	if (!isVersion1Key && !loginAttempted  && 
					(result == CKYISO_UNAUTHORIZED)) {
	    // try to reauthenticate 
	    try {
		oldAttemptLogin();
	    } catch(PKCS11Exception& ) {
		// attemptLogin can throw things like CKR_PIN_INCORRECT
		// that don't make sense from a crypto operation. This is
		// a result of pin caching. We will reformat any login
		// exception to a CKR_DEVICE_ERROR.
		throw PKCS11Exception(CKR_DEVICE_ERROR);
	    }
	    loginAttempted = true;
	    goto retry; // easier to understand than a while loop in this case.
	}
 	throw PKCS11Exception( result == CKYISO_UNAUTHORIZED ?
		 CKR_USER_NOT_LOGGED_IN : CKR_DEVICE_ERROR);
    }
}

void
Slot::seedRandom(SessionHandleSuffix suffix, CK_BYTE_PTR pData,
        CK_ULONG ulDataLen)
{
    if (state & CAC_CARD) {
	/* should throw unsupported */
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }

    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS ) handleConnectionError();

    CKYBuffer random;
    CKYBuffer seed;
    CKYOffset offset = 0;
    CKYISOStatus result;
    int i;

    CKYBuffer_InitEmpty(&random);
    CKYBuffer_InitFromData(&seed, pData, ulDataLen);


    while (ulDataLen) {
	CKYByte len = (CKYByte) MIN(ulDataLen, 0xff);

	status = CKYApplet_GetRandom(conn, &random, len, &result);
	if (status != CKYSUCCESS) break;

	for (i=0; i < len ; i++) {
	    CKYBuffer_SetChar(&random, i, 
			CKYBuffer_GetChar(&random,i) ^
			CKYBuffer_GetChar(&seed,i+offset));
	}
	status = CKYApplet_SeedRandom(conn, &random, &result);
	if (status != CKYSUCCESS) break;

	ulDataLen -= (unsigned char)len;
	offset += (unsigned char)len;
    }

    CKYBuffer_FreeData(&random);
    CKYBuffer_FreeData(&seed);

    if (status != CKYSUCCESS) {
	if ( status == CKYSCARDERR ) {
	    handleConnectionError();
	}
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }
}

void
Slot::generateRandom(SessionHandleSuffix suffix, const CK_BYTE_PTR pData,
        CK_ULONG ulDataLen)
{
    if (state & CAC_CARD) {
	/* should throw unsupported */
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }

    Transaction trans;
    CKYStatus status = trans.begin(conn);
    if( status != CKYSUCCESS ) handleConnectionError();

    CKYBuffer random;
    CKYBuffer_InitEmpty(&random);

    CKYISOStatus result;

    while (ulDataLen) {
	CKYByte len = (CKYByte) MIN(ulDataLen, 0xff);

	status = CKYApplet_GetRandomAppend(conn, &random, len, &result);
	if (status != CKYSUCCESS) break;

	ulDataLen -= (unsigned char)len;
    }
    CKYBuffer_FreeData(&random);

    if (status != CKYSUCCESS) {
	if ( status == CKYSCARDERR ) {
	    handleConnectionError();
	}
	throw PKCS11Exception(CKR_DEVICE_ERROR);
    }
}

#define MAX_NUM_KEYS 8
unsigned int
Slot::getKeySize(CKYByte keyNum)
{
    unsigned int keySize = CryptParams::DEFAULT_KEY_SIZE;
    int modSize = 0;

    if(keyNum >= MAX_NUM_KEYS) {
        return keySize;
    }

    ObjectConstIter iter;
    iter = find_if(tokenObjects.begin(), tokenObjects.end(),
        KeyNumMatch(keyNum,*this));

    if( iter == tokenObjects.end() ) {
        return keySize;
    }

    CKYBuffer const *modulus = iter->getAttribute(CKA_MODULUS);

    if(modulus) {
        modSize = CKYBuffer_Size(modulus);
        if(CKYBuffer_GetChar(modulus,0) == 0x0) {
            modSize--;
        }
        if(modSize > 0)
            keySize = modSize * 8;
    }

    return keySize;
}